History log of /openbsd-current/sbin/iked/iked.h
Revision (<<< Hide revision tags) (Show revision tags >>>) Date Author Comments
# 1.230 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


# 1.229 15-Feb-2024 tobhe

Introduce new IMSG_CTL_PROCREADY which is used to signal that all pipes
are set up by child processes. The parent sends a ping to all children
and only starts once it has received an acknowledgement from all of them.
This fixes a race condition on process startup when the parent starts
running before all children are ready.

From markus@


# 1.228 15-Feb-2024 tobhe

Delay enabling sockets until ikev2 process is ready.

from markus@


# 1.227 15-Feb-2024 tobhe

Remove unused control_socks queue.

from markus@


# 1.226 24-Jan-2024 tobhe

Use per connection peerid for control replies
instead of 'broadcasting' replies for 'ikectl show sa' and
similar control requests, we now assign a uniq peerid to each
request and pass this peerid between the processes so the reply
can be sent on the matching connection.

from markus@


# 1.225 15-Jan-2024 tobhe

Include cert_partial_chain in iked_static instead of sending a separate
message.

from markus@


Revision tags: OPENBSD_7_4_BASE
# 1.224 11-Aug-2023 tobhe

Add iked support for route based sec(4) tunnels.

To use sec(4) instead of policy based tunnels, create a sec(4)
interface and add 'iface secXX' to your policy config.
sec(4) interfaces also support auto configuration for dynamic client
IPs via 'request any' like all other interfaces.
The config won't work without traffic selectors, 'from any to any'
should work for now but I plan to make this optional in the future.

ok dlg@


# 1.223 28-Jul-2023 claudio

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


# 1.222 18-Jul-2023 claudio

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


# 1.221 16-Jul-2023 claudio

Merge ibuf_get() with ibuf_getdata() and rename it to ibuf_getdata().
Also replace a ibuf_reserve() call with ibuf_add_zero() and
remove a buf->buf == NULL check in ibuf_length() since it is not necessary.
OK tobhe@ tb@


# 1.220 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.219 25-Jun-2023 op

remove ca_sslinit()

it's a noop; nowadays both LibreSSL and OpenSSL libcrypto and libssl
initialize themselves automatically before doing anything.

spotted by tb, ok tb tobhe


# 1.218 19-Jun-2023 claudio

Improve the ibuf API by adding these functions:
Functions extending ibuf_add to work with more specific data types
ibuf_add_buf, ibuf_add_zero, ibuf_add_n8, ibuf_add_n16, ibuf_add_n32,
ibuf_add_n64
Functions replacing ibuf_seek where data at a specific offset is modified
ibuf_set, ibuf_set_n8, ibuf_set_n16, ibuf_set_n32, ibuf_set_n64
Functions to check, get and set the filedescriptor stored on the ibuf
ibuf_fd_avail, ibuf_fd_get, ibuf_fd_set
and ibuf_data() to access the data buffer, to be used together with ibuf_size()

On top of this add an optimized imsg_compose_ibuf() where an ibuf is wrapped
into an imsg in an efficent way.

Finally remove msgbuf_drain since it is not used by anything outside of
the ibuf code. Because of this removal bump the major of libutil.

Remove ibuf_data() in iked since the same function is now provided by libutil.
OK tb@


# 1.217 16-Jun-2023 tb

Now that print_host() is unused, rename it to print_addr() and simplify.

ok claudio tobhe


# 1.216 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.215 12-Jun-2023 claudio

Use stdio open_memstream(3) to build up log strings instead of trying to
abuse ibufs for that. Using stdio for this has the benefit of using any
stdio function to build up strings including fprintf().
With and OK tb@


# 1.214 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.213 23-May-2023 claudio

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


# 1.212 23-May-2023 claudio

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


# 1.211 23-May-2023 claudio

There is no need to ibuf_zero() or memset() any buffers.
More cleanup will follow.
OK tobhe@


Revision tags: OPENBSD_7_3_BASE
# 1.210 05-Mar-2023 tobhe

Fix clean process shutdown by storing env globally like vmd and httpd do
instead of getting it from p_ps. The old approach does not work anymore
after the recent fork + exec update.

ok patrick@


# 1.209 04-Mar-2023 tobhe

Sync proc.c from vmd(8) to enabled fork + exec for all processes. This gives
each process a fresh and unique address space to further improve randomization
of ASLR and stack protector.

ok bluhm@ patrick@


# 1.208 03-Dec-2022 tobhe

Consistently use uintXX_t from <stdint.h> instead of u_intXX_t.


Revision tags: OPENBSD_7_2_BASE
# 1.207 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@


# 1.206 22-Jul-2022 tobhe

Include an OpenIKED Vendor ID payload in the initial handshake. This will
make it easier to handle interoperability problems with older versions in
the future. The ID is constructed from the string "OpenIKED-" followed by
the version number.
Sending of the vendor ID payload can be disabled by specifying
"set novendorid" in iked.conf(5).

ok markus@ bluhm@


# 1.205 08-Jul-2022 tobhe

Support sending certificate chains with intermediate CAs in multiple CERT
payloads. Local certificate chains as required with LetsEncrypt certs will
work between iked and other IKEv2 implementations, iked to iked connections
won't work yet because of missing support to receive multiple CERT
payloads.

from Katsuhiro Ueno
tested by and ok sthen@


Revision tags: OPENBSD_7_1_BASE
# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.229 15-Feb-2024 tobhe

Introduce new IMSG_CTL_PROCREADY which is used to signal that all pipes
are set up by child processes. The parent sends a ping to all children
and only starts once it has received an acknowledgement from all of them.
This fixes a race condition on process startup when the parent starts
running before all children are ready.

From markus@


# 1.228 15-Feb-2024 tobhe

Delay enabling sockets until ikev2 process is ready.

from markus@


# 1.227 15-Feb-2024 tobhe

Remove unused control_socks queue.

from markus@


# 1.226 24-Jan-2024 tobhe

Use per connection peerid for control replies
instead of 'broadcasting' replies for 'ikectl show sa' and
similar control requests, we now assign a uniq peerid to each
request and pass this peerid between the processes so the reply
can be sent on the matching connection.

from markus@


# 1.225 15-Jan-2024 tobhe

Include cert_partial_chain in iked_static instead of sending a separate
message.

from markus@


Revision tags: OPENBSD_7_4_BASE
# 1.224 11-Aug-2023 tobhe

Add iked support for route based sec(4) tunnels.

To use sec(4) instead of policy based tunnels, create a sec(4)
interface and add 'iface secXX' to your policy config.
sec(4) interfaces also support auto configuration for dynamic client
IPs via 'request any' like all other interfaces.
The config won't work without traffic selectors, 'from any to any'
should work for now but I plan to make this optional in the future.

ok dlg@


# 1.223 28-Jul-2023 claudio

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


# 1.222 18-Jul-2023 claudio

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


# 1.221 16-Jul-2023 claudio

Merge ibuf_get() with ibuf_getdata() and rename it to ibuf_getdata().
Also replace a ibuf_reserve() call with ibuf_add_zero() and
remove a buf->buf == NULL check in ibuf_length() since it is not necessary.
OK tobhe@ tb@


# 1.220 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.219 25-Jun-2023 op

remove ca_sslinit()

it's a noop; nowadays both LibreSSL and OpenSSL libcrypto and libssl
initialize themselves automatically before doing anything.

spotted by tb, ok tb tobhe


# 1.218 19-Jun-2023 claudio

Improve the ibuf API by adding these functions:
Functions extending ibuf_add to work with more specific data types
ibuf_add_buf, ibuf_add_zero, ibuf_add_n8, ibuf_add_n16, ibuf_add_n32,
ibuf_add_n64
Functions replacing ibuf_seek where data at a specific offset is modified
ibuf_set, ibuf_set_n8, ibuf_set_n16, ibuf_set_n32, ibuf_set_n64
Functions to check, get and set the filedescriptor stored on the ibuf
ibuf_fd_avail, ibuf_fd_get, ibuf_fd_set
and ibuf_data() to access the data buffer, to be used together with ibuf_size()

On top of this add an optimized imsg_compose_ibuf() where an ibuf is wrapped
into an imsg in an efficent way.

Finally remove msgbuf_drain since it is not used by anything outside of
the ibuf code. Because of this removal bump the major of libutil.

Remove ibuf_data() in iked since the same function is now provided by libutil.
OK tb@


# 1.217 16-Jun-2023 tb

Now that print_host() is unused, rename it to print_addr() and simplify.

ok claudio tobhe


# 1.216 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.215 12-Jun-2023 claudio

Use stdio open_memstream(3) to build up log strings instead of trying to
abuse ibufs for that. Using stdio for this has the benefit of using any
stdio function to build up strings including fprintf().
With and OK tb@


# 1.214 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.213 23-May-2023 claudio

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


# 1.212 23-May-2023 claudio

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


# 1.211 23-May-2023 claudio

There is no need to ibuf_zero() or memset() any buffers.
More cleanup will follow.
OK tobhe@


Revision tags: OPENBSD_7_3_BASE
# 1.210 05-Mar-2023 tobhe

Fix clean process shutdown by storing env globally like vmd and httpd do
instead of getting it from p_ps. The old approach does not work anymore
after the recent fork + exec update.

ok patrick@


# 1.209 04-Mar-2023 tobhe

Sync proc.c from vmd(8) to enabled fork + exec for all processes. This gives
each process a fresh and unique address space to further improve randomization
of ASLR and stack protector.

ok bluhm@ patrick@


# 1.208 03-Dec-2022 tobhe

Consistently use uintXX_t from <stdint.h> instead of u_intXX_t.


Revision tags: OPENBSD_7_2_BASE
# 1.207 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@


# 1.206 22-Jul-2022 tobhe

Include an OpenIKED Vendor ID payload in the initial handshake. This will
make it easier to handle interoperability problems with older versions in
the future. The ID is constructed from the string "OpenIKED-" followed by
the version number.
Sending of the vendor ID payload can be disabled by specifying
"set novendorid" in iked.conf(5).

ok markus@ bluhm@


# 1.205 08-Jul-2022 tobhe

Support sending certificate chains with intermediate CAs in multiple CERT
payloads. Local certificate chains as required with LetsEncrypt certs will
work between iked and other IKEv2 implementations, iked to iked connections
won't work yet because of missing support to receive multiple CERT
payloads.

from Katsuhiro Ueno
tested by and ok sthen@


Revision tags: OPENBSD_7_1_BASE
# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.226 24-Jan-2024 tobhe

Use per connection peerid for control replies
instead of 'broadcasting' replies for 'ikectl show sa' and
similar control requests, we now assign a uniq peerid to each
request and pass this peerid between the processes so the reply
can be sent on the matching connection.

from markus@


# 1.225 15-Jan-2024 tobhe

Include cert_partial_chain in iked_static instead of sending a separate
message.

from markus@


Revision tags: OPENBSD_7_4_BASE
# 1.224 11-Aug-2023 tobhe

Add iked support for route based sec(4) tunnels.

To use sec(4) instead of policy based tunnels, create a sec(4)
interface and add 'iface secXX' to your policy config.
sec(4) interfaces also support auto configuration for dynamic client
IPs via 'request any' like all other interfaces.
The config won't work without traffic selectors, 'from any to any'
should work for now but I plan to make this optional in the future.

ok dlg@


# 1.223 28-Jul-2023 claudio

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


# 1.222 18-Jul-2023 claudio

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


# 1.221 16-Jul-2023 claudio

Merge ibuf_get() with ibuf_getdata() and rename it to ibuf_getdata().
Also replace a ibuf_reserve() call with ibuf_add_zero() and
remove a buf->buf == NULL check in ibuf_length() since it is not necessary.
OK tobhe@ tb@


# 1.220 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.219 25-Jun-2023 op

remove ca_sslinit()

it's a noop; nowadays both LibreSSL and OpenSSL libcrypto and libssl
initialize themselves automatically before doing anything.

spotted by tb, ok tb tobhe


# 1.218 19-Jun-2023 claudio

Improve the ibuf API by adding these functions:
Functions extending ibuf_add to work with more specific data types
ibuf_add_buf, ibuf_add_zero, ibuf_add_n8, ibuf_add_n16, ibuf_add_n32,
ibuf_add_n64
Functions replacing ibuf_seek where data at a specific offset is modified
ibuf_set, ibuf_set_n8, ibuf_set_n16, ibuf_set_n32, ibuf_set_n64
Functions to check, get and set the filedescriptor stored on the ibuf
ibuf_fd_avail, ibuf_fd_get, ibuf_fd_set
and ibuf_data() to access the data buffer, to be used together with ibuf_size()

On top of this add an optimized imsg_compose_ibuf() where an ibuf is wrapped
into an imsg in an efficent way.

Finally remove msgbuf_drain since it is not used by anything outside of
the ibuf code. Because of this removal bump the major of libutil.

Remove ibuf_data() in iked since the same function is now provided by libutil.
OK tb@


# 1.217 16-Jun-2023 tb

Now that print_host() is unused, rename it to print_addr() and simplify.

ok claudio tobhe


# 1.216 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.215 12-Jun-2023 claudio

Use stdio open_memstream(3) to build up log strings instead of trying to
abuse ibufs for that. Using stdio for this has the benefit of using any
stdio function to build up strings including fprintf().
With and OK tb@


# 1.214 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.213 23-May-2023 claudio

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


# 1.212 23-May-2023 claudio

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


# 1.211 23-May-2023 claudio

There is no need to ibuf_zero() or memset() any buffers.
More cleanup will follow.
OK tobhe@


Revision tags: OPENBSD_7_3_BASE
# 1.210 05-Mar-2023 tobhe

Fix clean process shutdown by storing env globally like vmd and httpd do
instead of getting it from p_ps. The old approach does not work anymore
after the recent fork + exec update.

ok patrick@


# 1.209 04-Mar-2023 tobhe

Sync proc.c from vmd(8) to enabled fork + exec for all processes. This gives
each process a fresh and unique address space to further improve randomization
of ASLR and stack protector.

ok bluhm@ patrick@


# 1.208 03-Dec-2022 tobhe

Consistently use uintXX_t from <stdint.h> instead of u_intXX_t.


Revision tags: OPENBSD_7_2_BASE
# 1.207 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@


# 1.206 22-Jul-2022 tobhe

Include an OpenIKED Vendor ID payload in the initial handshake. This will
make it easier to handle interoperability problems with older versions in
the future. The ID is constructed from the string "OpenIKED-" followed by
the version number.
Sending of the vendor ID payload can be disabled by specifying
"set novendorid" in iked.conf(5).

ok markus@ bluhm@


# 1.205 08-Jul-2022 tobhe

Support sending certificate chains with intermediate CAs in multiple CERT
payloads. Local certificate chains as required with LetsEncrypt certs will
work between iked and other IKEv2 implementations, iked to iked connections
won't work yet because of missing support to receive multiple CERT
payloads.

from Katsuhiro Ueno
tested by and ok sthen@


Revision tags: OPENBSD_7_1_BASE
# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.225 15-Jan-2024 tobhe

Include cert_partial_chain in iked_static instead of sending a separate
message.

from markus@


Revision tags: OPENBSD_7_4_BASE
# 1.224 11-Aug-2023 tobhe

Add iked support for route based sec(4) tunnels.

To use sec(4) instead of policy based tunnels, create a sec(4)
interface and add 'iface secXX' to your policy config.
sec(4) interfaces also support auto configuration for dynamic client
IPs via 'request any' like all other interfaces.
The config won't work without traffic selectors, 'from any to any'
should work for now but I plan to make this optional in the future.

ok dlg@


# 1.223 28-Jul-2023 claudio

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


# 1.222 18-Jul-2023 claudio

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


# 1.221 16-Jul-2023 claudio

Merge ibuf_get() with ibuf_getdata() and rename it to ibuf_getdata().
Also replace a ibuf_reserve() call with ibuf_add_zero() and
remove a buf->buf == NULL check in ibuf_length() since it is not necessary.
OK tobhe@ tb@


# 1.220 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.219 25-Jun-2023 op

remove ca_sslinit()

it's a noop; nowadays both LibreSSL and OpenSSL libcrypto and libssl
initialize themselves automatically before doing anything.

spotted by tb, ok tb tobhe


# 1.218 19-Jun-2023 claudio

Improve the ibuf API by adding these functions:
Functions extending ibuf_add to work with more specific data types
ibuf_add_buf, ibuf_add_zero, ibuf_add_n8, ibuf_add_n16, ibuf_add_n32,
ibuf_add_n64
Functions replacing ibuf_seek where data at a specific offset is modified
ibuf_set, ibuf_set_n8, ibuf_set_n16, ibuf_set_n32, ibuf_set_n64
Functions to check, get and set the filedescriptor stored on the ibuf
ibuf_fd_avail, ibuf_fd_get, ibuf_fd_set
and ibuf_data() to access the data buffer, to be used together with ibuf_size()

On top of this add an optimized imsg_compose_ibuf() where an ibuf is wrapped
into an imsg in an efficent way.

Finally remove msgbuf_drain since it is not used by anything outside of
the ibuf code. Because of this removal bump the major of libutil.

Remove ibuf_data() in iked since the same function is now provided by libutil.
OK tb@


# 1.217 16-Jun-2023 tb

Now that print_host() is unused, rename it to print_addr() and simplify.

ok claudio tobhe


# 1.216 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.215 12-Jun-2023 claudio

Use stdio open_memstream(3) to build up log strings instead of trying to
abuse ibufs for that. Using stdio for this has the benefit of using any
stdio function to build up strings including fprintf().
With and OK tb@


# 1.214 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.213 23-May-2023 claudio

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


# 1.212 23-May-2023 claudio

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


# 1.211 23-May-2023 claudio

There is no need to ibuf_zero() or memset() any buffers.
More cleanup will follow.
OK tobhe@


Revision tags: OPENBSD_7_3_BASE
# 1.210 05-Mar-2023 tobhe

Fix clean process shutdown by storing env globally like vmd and httpd do
instead of getting it from p_ps. The old approach does not work anymore
after the recent fork + exec update.

ok patrick@


# 1.209 04-Mar-2023 tobhe

Sync proc.c from vmd(8) to enabled fork + exec for all processes. This gives
each process a fresh and unique address space to further improve randomization
of ASLR and stack protector.

ok bluhm@ patrick@


# 1.208 03-Dec-2022 tobhe

Consistently use uintXX_t from <stdint.h> instead of u_intXX_t.


Revision tags: OPENBSD_7_2_BASE
# 1.207 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@


# 1.206 22-Jul-2022 tobhe

Include an OpenIKED Vendor ID payload in the initial handshake. This will
make it easier to handle interoperability problems with older versions in
the future. The ID is constructed from the string "OpenIKED-" followed by
the version number.
Sending of the vendor ID payload can be disabled by specifying
"set novendorid" in iked.conf(5).

ok markus@ bluhm@


# 1.205 08-Jul-2022 tobhe

Support sending certificate chains with intermediate CAs in multiple CERT
payloads. Local certificate chains as required with LetsEncrypt certs will
work between iked and other IKEv2 implementations, iked to iked connections
won't work yet because of missing support to receive multiple CERT
payloads.

from Katsuhiro Ueno
tested by and ok sthen@


Revision tags: OPENBSD_7_1_BASE
# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.224 11-Aug-2023 tobhe

Add iked support for route based sec(4) tunnels.

To use sec(4) instead of policy based tunnels, create a sec(4)
interface and add 'iface secXX' to your policy config.
sec(4) interfaces also support auto configuration for dynamic client
IPs via 'request any' like all other interfaces.
The config won't work without traffic selectors, 'from any to any'
should work for now but I plan to make this optional in the future.

ok dlg@


# 1.223 28-Jul-2023 claudio

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


# 1.222 18-Jul-2023 claudio

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


# 1.221 16-Jul-2023 claudio

Merge ibuf_get() with ibuf_getdata() and rename it to ibuf_getdata().
Also replace a ibuf_reserve() call with ibuf_add_zero() and
remove a buf->buf == NULL check in ibuf_length() since it is not necessary.
OK tobhe@ tb@


# 1.220 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.219 25-Jun-2023 op

remove ca_sslinit()

it's a noop; nowadays both LibreSSL and OpenSSL libcrypto and libssl
initialize themselves automatically before doing anything.

spotted by tb, ok tb tobhe


# 1.218 19-Jun-2023 claudio

Improve the ibuf API by adding these functions:
Functions extending ibuf_add to work with more specific data types
ibuf_add_buf, ibuf_add_zero, ibuf_add_n8, ibuf_add_n16, ibuf_add_n32,
ibuf_add_n64
Functions replacing ibuf_seek where data at a specific offset is modified
ibuf_set, ibuf_set_n8, ibuf_set_n16, ibuf_set_n32, ibuf_set_n64
Functions to check, get and set the filedescriptor stored on the ibuf
ibuf_fd_avail, ibuf_fd_get, ibuf_fd_set
and ibuf_data() to access the data buffer, to be used together with ibuf_size()

On top of this add an optimized imsg_compose_ibuf() where an ibuf is wrapped
into an imsg in an efficent way.

Finally remove msgbuf_drain since it is not used by anything outside of
the ibuf code. Because of this removal bump the major of libutil.

Remove ibuf_data() in iked since the same function is now provided by libutil.
OK tb@


# 1.217 16-Jun-2023 tb

Now that print_host() is unused, rename it to print_addr() and simplify.

ok claudio tobhe


# 1.216 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.215 12-Jun-2023 claudio

Use stdio open_memstream(3) to build up log strings instead of trying to
abuse ibufs for that. Using stdio for this has the benefit of using any
stdio function to build up strings including fprintf().
With and OK tb@


# 1.214 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.213 23-May-2023 claudio

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


# 1.212 23-May-2023 claudio

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


# 1.211 23-May-2023 claudio

There is no need to ibuf_zero() or memset() any buffers.
More cleanup will follow.
OK tobhe@


Revision tags: OPENBSD_7_3_BASE
# 1.210 05-Mar-2023 tobhe

Fix clean process shutdown by storing env globally like vmd and httpd do
instead of getting it from p_ps. The old approach does not work anymore
after the recent fork + exec update.

ok patrick@


# 1.209 04-Mar-2023 tobhe

Sync proc.c from vmd(8) to enabled fork + exec for all processes. This gives
each process a fresh and unique address space to further improve randomization
of ASLR and stack protector.

ok bluhm@ patrick@


# 1.208 03-Dec-2022 tobhe

Consistently use uintXX_t from <stdint.h> instead of u_intXX_t.


Revision tags: OPENBSD_7_2_BASE
# 1.207 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@


# 1.206 22-Jul-2022 tobhe

Include an OpenIKED Vendor ID payload in the initial handshake. This will
make it easier to handle interoperability problems with older versions in
the future. The ID is constructed from the string "OpenIKED-" followed by
the version number.
Sending of the vendor ID payload can be disabled by specifying
"set novendorid" in iked.conf(5).

ok markus@ bluhm@


# 1.205 08-Jul-2022 tobhe

Support sending certificate chains with intermediate CAs in multiple CERT
payloads. Local certificate chains as required with LetsEncrypt certs will
work between iked and other IKEv2 implementations, iked to iked connections
won't work yet because of missing support to receive multiple CERT
payloads.

from Katsuhiro Ueno
tested by and ok sthen@


Revision tags: OPENBSD_7_1_BASE
# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.223 28-Jul-2023 claudio

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


# 1.222 18-Jul-2023 claudio

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


# 1.221 16-Jul-2023 claudio

Merge ibuf_get() with ibuf_getdata() and rename it to ibuf_getdata().
Also replace a ibuf_reserve() call with ibuf_add_zero() and
remove a buf->buf == NULL check in ibuf_length() since it is not necessary.
OK tobhe@ tb@


# 1.220 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.219 25-Jun-2023 op

remove ca_sslinit()

it's a noop; nowadays both LibreSSL and OpenSSL libcrypto and libssl
initialize themselves automatically before doing anything.

spotted by tb, ok tb tobhe


# 1.218 19-Jun-2023 claudio

Improve the ibuf API by adding these functions:
Functions extending ibuf_add to work with more specific data types
ibuf_add_buf, ibuf_add_zero, ibuf_add_n8, ibuf_add_n16, ibuf_add_n32,
ibuf_add_n64
Functions replacing ibuf_seek where data at a specific offset is modified
ibuf_set, ibuf_set_n8, ibuf_set_n16, ibuf_set_n32, ibuf_set_n64
Functions to check, get and set the filedescriptor stored on the ibuf
ibuf_fd_avail, ibuf_fd_get, ibuf_fd_set
and ibuf_data() to access the data buffer, to be used together with ibuf_size()

On top of this add an optimized imsg_compose_ibuf() where an ibuf is wrapped
into an imsg in an efficent way.

Finally remove msgbuf_drain since it is not used by anything outside of
the ibuf code. Because of this removal bump the major of libutil.

Remove ibuf_data() in iked since the same function is now provided by libutil.
OK tb@


# 1.217 16-Jun-2023 tb

Now that print_host() is unused, rename it to print_addr() and simplify.

ok claudio tobhe


# 1.216 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.215 12-Jun-2023 claudio

Use stdio open_memstream(3) to build up log strings instead of trying to
abuse ibufs for that. Using stdio for this has the benefit of using any
stdio function to build up strings including fprintf().
With and OK tb@


# 1.214 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.213 23-May-2023 claudio

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


# 1.212 23-May-2023 claudio

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


# 1.211 23-May-2023 claudio

There is no need to ibuf_zero() or memset() any buffers.
More cleanup will follow.
OK tobhe@


Revision tags: OPENBSD_7_3_BASE
# 1.210 05-Mar-2023 tobhe

Fix clean process shutdown by storing env globally like vmd and httpd do
instead of getting it from p_ps. The old approach does not work anymore
after the recent fork + exec update.

ok patrick@


# 1.209 04-Mar-2023 tobhe

Sync proc.c from vmd(8) to enabled fork + exec for all processes. This gives
each process a fresh and unique address space to further improve randomization
of ASLR and stack protector.

ok bluhm@ patrick@


# 1.208 03-Dec-2022 tobhe

Consistently use uintXX_t from <stdint.h> instead of u_intXX_t.


Revision tags: OPENBSD_7_2_BASE
# 1.207 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@


# 1.206 22-Jul-2022 tobhe

Include an OpenIKED Vendor ID payload in the initial handshake. This will
make it easier to handle interoperability problems with older versions in
the future. The ID is constructed from the string "OpenIKED-" followed by
the version number.
Sending of the vendor ID payload can be disabled by specifying
"set novendorid" in iked.conf(5).

ok markus@ bluhm@


# 1.205 08-Jul-2022 tobhe

Support sending certificate chains with intermediate CAs in multiple CERT
payloads. Local certificate chains as required with LetsEncrypt certs will
work between iked and other IKEv2 implementations, iked to iked connections
won't work yet because of missing support to receive multiple CERT
payloads.

from Katsuhiro Ueno
tested by and ok sthen@


Revision tags: OPENBSD_7_1_BASE
# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.222 18-Jul-2023 claudio

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


# 1.221 16-Jul-2023 claudio

Merge ibuf_get() with ibuf_getdata() and rename it to ibuf_getdata().
Also replace a ibuf_reserve() call with ibuf_add_zero() and
remove a buf->buf == NULL check in ibuf_length() since it is not necessary.
OK tobhe@ tb@


# 1.220 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.219 25-Jun-2023 op

remove ca_sslinit()

it's a noop; nowadays both LibreSSL and OpenSSL libcrypto and libssl
initialize themselves automatically before doing anything.

spotted by tb, ok tb tobhe


# 1.218 19-Jun-2023 claudio

Improve the ibuf API by adding these functions:
Functions extending ibuf_add to work with more specific data types
ibuf_add_buf, ibuf_add_zero, ibuf_add_n8, ibuf_add_n16, ibuf_add_n32,
ibuf_add_n64
Functions replacing ibuf_seek where data at a specific offset is modified
ibuf_set, ibuf_set_n8, ibuf_set_n16, ibuf_set_n32, ibuf_set_n64
Functions to check, get and set the filedescriptor stored on the ibuf
ibuf_fd_avail, ibuf_fd_get, ibuf_fd_set
and ibuf_data() to access the data buffer, to be used together with ibuf_size()

On top of this add an optimized imsg_compose_ibuf() where an ibuf is wrapped
into an imsg in an efficent way.

Finally remove msgbuf_drain since it is not used by anything outside of
the ibuf code. Because of this removal bump the major of libutil.

Remove ibuf_data() in iked since the same function is now provided by libutil.
OK tb@


# 1.217 16-Jun-2023 tb

Now that print_host() is unused, rename it to print_addr() and simplify.

ok claudio tobhe


# 1.216 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.215 12-Jun-2023 claudio

Use stdio open_memstream(3) to build up log strings instead of trying to
abuse ibufs for that. Using stdio for this has the benefit of using any
stdio function to build up strings including fprintf().
With and OK tb@


# 1.214 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.213 23-May-2023 claudio

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


# 1.212 23-May-2023 claudio

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


# 1.211 23-May-2023 claudio

There is no need to ibuf_zero() or memset() any buffers.
More cleanup will follow.
OK tobhe@


Revision tags: OPENBSD_7_3_BASE
# 1.210 05-Mar-2023 tobhe

Fix clean process shutdown by storing env globally like vmd and httpd do
instead of getting it from p_ps. The old approach does not work anymore
after the recent fork + exec update.

ok patrick@


# 1.209 04-Mar-2023 tobhe

Sync proc.c from vmd(8) to enabled fork + exec for all processes. This gives
each process a fresh and unique address space to further improve randomization
of ASLR and stack protector.

ok bluhm@ patrick@


# 1.208 03-Dec-2022 tobhe

Consistently use uintXX_t from <stdint.h> instead of u_intXX_t.


Revision tags: OPENBSD_7_2_BASE
# 1.207 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@


# 1.206 22-Jul-2022 tobhe

Include an OpenIKED Vendor ID payload in the initial handshake. This will
make it easier to handle interoperability problems with older versions in
the future. The ID is constructed from the string "OpenIKED-" followed by
the version number.
Sending of the vendor ID payload can be disabled by specifying
"set novendorid" in iked.conf(5).

ok markus@ bluhm@


# 1.205 08-Jul-2022 tobhe

Support sending certificate chains with intermediate CAs in multiple CERT
payloads. Local certificate chains as required with LetsEncrypt certs will
work between iked and other IKEv2 implementations, iked to iked connections
won't work yet because of missing support to receive multiple CERT
payloads.

from Katsuhiro Ueno
tested by and ok sthen@


Revision tags: OPENBSD_7_1_BASE
# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.222 18-Jul-2023 claudio

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


# 1.221 16-Jul-2023 claudio

Merge ibuf_get() with ibuf_getdata() and rename it to ibuf_getdata().
Also replace a ibuf_reserve() call with ibuf_add_zero() and
remove a buf->buf == NULL check in ibuf_length() since it is not necessary.
OK tobhe@ tb@


# 1.220 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.219 25-Jun-2023 op

remove ca_sslinit()

it's a noop; nowadays both LibreSSL and OpenSSL libcrypto and libssl
initialize themselves automatically before doing anything.

spotted by tb, ok tb tobhe


# 1.218 19-Jun-2023 claudio

Improve the ibuf API by adding these functions:
Functions extending ibuf_add to work with more specific data types
ibuf_add_buf, ibuf_add_zero, ibuf_add_n8, ibuf_add_n16, ibuf_add_n32,
ibuf_add_n64
Functions replacing ibuf_seek where data at a specific offset is modified
ibuf_set, ibuf_set_n8, ibuf_set_n16, ibuf_set_n32, ibuf_set_n64
Functions to check, get and set the filedescriptor stored on the ibuf
ibuf_fd_avail, ibuf_fd_get, ibuf_fd_set
and ibuf_data() to access the data buffer, to be used together with ibuf_size()

On top of this add an optimized imsg_compose_ibuf() where an ibuf is wrapped
into an imsg in an efficent way.

Finally remove msgbuf_drain since it is not used by anything outside of
the ibuf code. Because of this removal bump the major of libutil.

Remove ibuf_data() in iked since the same function is now provided by libutil.
OK tb@


# 1.217 16-Jun-2023 tb

Now that print_host() is unused, rename it to print_addr() and simplify.

ok claudio tobhe


# 1.216 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.215 12-Jun-2023 claudio

Use stdio open_memstream(3) to build up log strings instead of trying to
abuse ibufs for that. Using stdio for this has the benefit of using any
stdio function to build up strings including fprintf().
With and OK tb@


# 1.214 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.213 23-May-2023 claudio

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


# 1.212 23-May-2023 claudio

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


# 1.211 23-May-2023 claudio

There is no need to ibuf_zero() or memset() any buffers.
More cleanup will follow.
OK tobhe@


Revision tags: OPENBSD_7_3_BASE
# 1.210 05-Mar-2023 tobhe

Fix clean process shutdown by storing env globally like vmd and httpd do
instead of getting it from p_ps. The old approach does not work anymore
after the recent fork + exec update.

ok patrick@


# 1.209 04-Mar-2023 tobhe

Sync proc.c from vmd(8) to enabled fork + exec for all processes. This gives
each process a fresh and unique address space to further improve randomization
of ASLR and stack protector.

ok bluhm@ patrick@


# 1.208 03-Dec-2022 tobhe

Consistently use uintXX_t from <stdint.h> instead of u_intXX_t.


Revision tags: OPENBSD_7_2_BASE
# 1.207 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@


# 1.206 22-Jul-2022 tobhe

Include an OpenIKED Vendor ID payload in the initial handshake. This will
make it easier to handle interoperability problems with older versions in
the future. The ID is constructed from the string "OpenIKED-" followed by
the version number.
Sending of the vendor ID payload can be disabled by specifying
"set novendorid" in iked.conf(5).

ok markus@ bluhm@


# 1.205 08-Jul-2022 tobhe

Support sending certificate chains with intermediate CAs in multiple CERT
payloads. Local certificate chains as required with LetsEncrypt certs will
work between iked and other IKEv2 implementations, iked to iked connections
won't work yet because of missing support to receive multiple CERT
payloads.

from Katsuhiro Ueno
tested by and ok sthen@


Revision tags: OPENBSD_7_1_BASE
# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.220 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.219 25-Jun-2023 op

remove ca_sslinit()

it's a noop; nowadays both LibreSSL and OpenSSL libcrypto and libssl
initialize themselves automatically before doing anything.

spotted by tb, ok tb tobhe


# 1.218 19-Jun-2023 claudio

Improve the ibuf API by adding these functions:
Functions extending ibuf_add to work with more specific data types
ibuf_add_buf, ibuf_add_zero, ibuf_add_n8, ibuf_add_n16, ibuf_add_n32,
ibuf_add_n64
Functions replacing ibuf_seek where data at a specific offset is modified
ibuf_set, ibuf_set_n8, ibuf_set_n16, ibuf_set_n32, ibuf_set_n64
Functions to check, get and set the filedescriptor stored on the ibuf
ibuf_fd_avail, ibuf_fd_get, ibuf_fd_set
and ibuf_data() to access the data buffer, to be used together with ibuf_size()

On top of this add an optimized imsg_compose_ibuf() where an ibuf is wrapped
into an imsg in an efficent way.

Finally remove msgbuf_drain since it is not used by anything outside of
the ibuf code. Because of this removal bump the major of libutil.

Remove ibuf_data() in iked since the same function is now provided by libutil.
OK tb@


# 1.217 16-Jun-2023 tb

Now that print_host() is unused, rename it to print_addr() and simplify.

ok claudio tobhe


# 1.216 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.215 12-Jun-2023 claudio

Use stdio open_memstream(3) to build up log strings instead of trying to
abuse ibufs for that. Using stdio for this has the benefit of using any
stdio function to build up strings including fprintf().
With and OK tb@


# 1.214 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.213 23-May-2023 claudio

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


# 1.212 23-May-2023 claudio

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


# 1.211 23-May-2023 claudio

There is no need to ibuf_zero() or memset() any buffers.
More cleanup will follow.
OK tobhe@


Revision tags: OPENBSD_7_3_BASE
# 1.210 05-Mar-2023 tobhe

Fix clean process shutdown by storing env globally like vmd and httpd do
instead of getting it from p_ps. The old approach does not work anymore
after the recent fork + exec update.

ok patrick@


# 1.209 04-Mar-2023 tobhe

Sync proc.c from vmd(8) to enabled fork + exec for all processes. This gives
each process a fresh and unique address space to further improve randomization
of ASLR and stack protector.

ok bluhm@ patrick@


# 1.208 03-Dec-2022 tobhe

Consistently use uintXX_t from <stdint.h> instead of u_intXX_t.


Revision tags: OPENBSD_7_2_BASE
# 1.207 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@


# 1.206 22-Jul-2022 tobhe

Include an OpenIKED Vendor ID payload in the initial handshake. This will
make it easier to handle interoperability problems with older versions in
the future. The ID is constructed from the string "OpenIKED-" followed by
the version number.
Sending of the vendor ID payload can be disabled by specifying
"set novendorid" in iked.conf(5).

ok markus@ bluhm@


# 1.205 08-Jul-2022 tobhe

Support sending certificate chains with intermediate CAs in multiple CERT
payloads. Local certificate chains as required with LetsEncrypt certs will
work between iked and other IKEv2 implementations, iked to iked connections
won't work yet because of missing support to receive multiple CERT
payloads.

from Katsuhiro Ueno
tested by and ok sthen@


Revision tags: OPENBSD_7_1_BASE
# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.210 05-Mar-2023 tobhe

Fix clean process shutdown by storing env globally like vmd and httpd do
instead of getting it from p_ps. The old approach does not work anymore
after the recent fork + exec update.

ok patrick@


# 1.209 04-Mar-2023 tobhe

Sync proc.c from vmd(8) to enabled fork + exec for all processes. This gives
each process a fresh and unique address space to further improve randomization
of ASLR and stack protector.

ok bluhm@ patrick@


# 1.208 03-Dec-2022 tobhe

Consistently use uintXX_t from <stdint.h> instead of u_intXX_t.


Revision tags: OPENBSD_7_2_BASE
# 1.207 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@


# 1.206 22-Jul-2022 tobhe

Include an OpenIKED Vendor ID payload in the initial handshake. This will
make it easier to handle interoperability problems with older versions in
the future. The ID is constructed from the string "OpenIKED-" followed by
the version number.
Sending of the vendor ID payload can be disabled by specifying
"set novendorid" in iked.conf(5).

ok markus@ bluhm@


# 1.205 08-Jul-2022 tobhe

Support sending certificate chains with intermediate CAs in multiple CERT
payloads. Local certificate chains as required with LetsEncrypt certs will
work between iked and other IKEv2 implementations, iked to iked connections
won't work yet because of missing support to receive multiple CERT
payloads.

from Katsuhiro Ueno
tested by and ok sthen@


Revision tags: OPENBSD_7_1_BASE
# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.208 03-Dec-2022 tobhe

Consistently use uintXX_t from <stdint.h> instead of u_intXX_t.


Revision tags: OPENBSD_7_2_BASE
# 1.207 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@


# 1.206 22-Jul-2022 tobhe

Include an OpenIKED Vendor ID payload in the initial handshake. This will
make it easier to handle interoperability problems with older versions in
the future. The ID is constructed from the string "OpenIKED-" followed by
the version number.
Sending of the vendor ID payload can be disabled by specifying
"set novendorid" in iked.conf(5).

ok markus@ bluhm@


# 1.205 08-Jul-2022 tobhe

Support sending certificate chains with intermediate CAs in multiple CERT
payloads. Local certificate chains as required with LetsEncrypt certs will
work between iked and other IKEv2 implementations, iked to iked connections
won't work yet because of missing support to receive multiple CERT
payloads.

from Katsuhiro Ueno
tested by and ok sthen@


Revision tags: OPENBSD_7_1_BASE
# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.207 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@


# 1.206 22-Jul-2022 tobhe

Include an OpenIKED Vendor ID payload in the initial handshake. This will
make it easier to handle interoperability problems with older versions in
the future. The ID is constructed from the string "OpenIKED-" followed by
the version number.
Sending of the vendor ID payload can be disabled by specifying
"set novendorid" in iked.conf(5).

ok markus@ bluhm@


# 1.205 08-Jul-2022 tobhe

Support sending certificate chains with intermediate CAs in multiple CERT
payloads. Local certificate chains as required with LetsEncrypt certs will
work between iked and other IKEv2 implementations, iked to iked connections
won't work yet because of missing support to receive multiple CERT
payloads.

from Katsuhiro Ueno
tested by and ok sthen@


Revision tags: OPENBSD_7_1_BASE
# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.206 22-Jul-2022 tobhe

Include an OpenIKED Vendor ID payload in the initial handshake. This will
make it easier to handle interoperability problems with older versions in
the future. The ID is constructed from the string "OpenIKED-" followed by
the version number.
Sending of the vendor ID payload can be disabled by specifying
"set novendorid" in iked.conf(5).

ok markus@ bluhm@


# 1.205 08-Jul-2022 tobhe

Support sending certificate chains with intermediate CAs in multiple CERT
payloads. Local certificate chains as required with LetsEncrypt certs will
work between iked and other IKEv2 implementations, iked to iked connections
won't work yet because of missing support to receive multiple CERT
payloads.

from Katsuhiro Ueno
tested by and ok sthen@


Revision tags: OPENBSD_7_1_BASE
# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.205 08-Jul-2022 tobhe

Support sending certificate chains with intermediate CAs in multiple CERT
payloads. Local certificate chains as required with LetsEncrypt certs will
work between iked and other IKEv2 implementations, iked to iked connections
won't work yet because of missing support to receive multiple CERT
payloads.

from Katsuhiro Ueno
tested by and ok sthen@


Revision tags: OPENBSD_7_1_BASE
# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.204 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.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.203 09-Dec-2021 tobhe

Properly enable NAT-T without udpencap if mobike was negotiated without NAT.
Fixes a bug where iked sent zero-prefixed NAT-T messages on port 500 causing
parsing errors.

ok markus@ patrick@


# 1.202 09-Dec-2021 tobhe

Move switch to NAT-T port and udpencap activation to ikev2_enable_natt().

ok patrick@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.201 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.200 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.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.199 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.198 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@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.197 24-Nov-2021 tobhe

Unregister event on pfkey socket during pfkey_reply(). Using events
and poll() at the same time may lead to a race that locks up the
process in recv().

ok bluhm@


# 1.196 24-Nov-2021 tobhe

Pass env to pfkey API. Consistently call pfkey file descriptor fd.

ok bluhm@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.195 26-Oct-2021 tobhe

Make proto config option accept a list to allow specifying multiple
protocols for a single policy, e.g. "proto { ipencap, ipv6 }".

feedback and ok benno@
ok patrick@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.194 12-Oct-2021 tobhe

Change responder to prefer DH group from KE payload.
Without this change the responder would always prefer the first DH
group configured in its policy. This would lead to invalid KE
messages that cause an additional exchange which old
implementations do not support correctly. Now we ignore the order
of DH groups in the policy and prefer the group from the policy
that matches the KE payload.

from markus@
ok patrick@


Revision tags: OPENBSD_7_0_BASE
# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.193 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@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.192 23-Jun-2021 tobhe

Factor out vroute_addr().

ok markus@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.191 13-May-2021 tobhe

Refactor iked process shutdown and cleanup. Remember configured
addresses and routes in iked_vroute_sc to not depend on ikev2
process for cleanup.

This makes sure that all flows, routes and addresses are deleted
no matter which process is killed first.

ok patrick@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.190 20-Apr-2021 dv

Move TAILQ initialization to files where they are used.

These priv-sep daemons all follow a similar design and use TAILQs
for tracking control process connections. In most cases, the TAILQs
are initialized separate from where they are used. Since the scope
of use is generally confined to a specific control process file,
this commit also removes any extern definitions and exposing the
TAILQ structures to other compilation units.

ok bluhm@, tb@


Revision tags: OPENBSD_6_9_BASE
# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.189 05-Mar-2021 tobhe

Print PFS group for rekeyed Child SAs.

ok patrick@


# 1.188 05-Mar-2021 tobhe

Move policy printing code from parse.y to new print.c

ok patrick@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.187 25-Feb-2021 tobhe

Constify cipher API.

ok markus@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.186 22-Feb-2021 tobhe

Don't pass 'id' as argument to make function signature match similar
functions. config_setpfkey() is always called with id PROC_IKEV2.


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.185 13-Feb-2021 tobhe

Add dynamic address configuration for roadwarrior clients.
The new 'iface' config option can be used to specify an interface
for the virtual addresses received from the peer.
Routes are automatically added based on the configured flows.

Input from sthen@ and claudio@
ok patrick@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.184 04-Feb-2021 tobhe

Rename 'struct group' to 'struct dh_group' for more clarity and
to avoid name clashes.

ok patrick@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.183 01-Feb-2021 tobhe

Take flows into consideration for policy lookup as initiator.
Fixes a bug where policies that only differ in their flow
configuration lead to a handshake error.

Found by claudio@
ok patrick@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.182 28-Jan-2021 mortimer

Extern privsep_process. Fixes compilation with -fno-common.

ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.181 26-Jan-2021 tobhe

Add support for RSA-PSS PKCS1 signatures. Don't enable them by
default for now because of interoperability issues.

ok patrick@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.180 21-Jan-2021 tobhe

Add support for INVALID_KE_PAYLOAD in CREATE_CHILD_SA
exchange. In the case of an invalid KE error, retry
CREATE_CHILD_SA exchange with different group instead
of restarting the full IKE handshake.

ok markus@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.179 21-Dec-2020 tobhe

Use policy_test() to reassign existing SAs to updated policies after
'ikectl reload'. This prevents initiation of new additional SAs
for each policy every time the config is reloaded.

ok patrick@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.178 03-Dec-2020 tobhe

Fix type mismatch. auth_method should be uint8_t.

ok markus@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.177 30-Nov-2020 tobhe

We need to rekey every child SA (even if acquired): Otherwise we can
get out of sync with the peer and the peer would keep on using the
expired SA because the lifetime is not negotiated.

ok patrick@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.176 29-Nov-2020 tobhe

Add 'set stickyaddress' option. If this option is enabled, iked will try
to assign the same 'config address' when an IKESA is negotiated with the
DSTID of an existing IKESA. The original IKESA will be closed and the
address will be transferred to the new IKESA.

ok patrick@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.175 26-Nov-2020 tobhe

Use a counter instead of random IV for AES-GCM. Security depends on
choosing a unique IV for every encryption operation, using a counter
as IV eliminates the risk of random collisions.

ok markus@ patrick@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.174 25-Nov-2020 tobhe

Fix proposal error handling. If a proposal contains an unknown transform
type or id, ignore the proposal instead of failing the exchange.

ok patrick@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.173 21-Nov-2020 tobhe

Clean up NATT hack. Pass 'frompeer' as parameter instead of manipulating
msg header to get the correct addresses and spis.

ok patrick@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.172 18-Nov-2020 tobhe

Constify sa in ikev2_pld_eap(). The parser code must not change any
sa or policy state, this should help make it clearer.

ok patrick@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.171 30-Oct-2020 tobhe

style(9)


# 1.170 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.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.169 24-Oct-2020 tobhe

Don't modify sa in ikev2_pld_cp. Store cp_type in msg until message has
passed all checks.

ok patrick@


# 1.168 19-Oct-2020 tobhe

Handle NO_PROPOSAL_CHOSEN as IKE_AUTH initiator.

ok markus@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.167 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.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.166 23-Sep-2020 tobhe

Add new 'set cert_partial_chain' config option to allow verification of
partial certificate chains if a trusted intermediate CA is found in
/etc/iked/ca/.

ok patrick@


# 1.165 16-Sep-2020 tobhe

Move all the EAP logic from a single branch in the message parsing code to
somewhere past successful message verification, closer to where the other
exchanges are handled. EAP is stll special, but this fits a lot better into
the overall architecture.

Tested with iOS, Stronswan and Windows
ok patrick@ sthen@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.164 28-Aug-2020 tobhe

Rename ikev2_*_sa() functions to make clear they handle Child SAs.

ok patrick@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.163 26-Aug-2020 tobhe

Allow disabling DPD liveness checks by setting dpd_check_interval to 0.

ok patrick@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.162 25-Aug-2020 tobhe

Add dpd_check_interval configuration option. If for any IKE SA no IPsec
or IKE message has been received within the specified time interval,
iked will start sending DPD messages.

ok patrick@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.161 24-Aug-2020 tobhe

Reduce the amount of boilerplate code and imsgs for config options by
grouping fixed-size values in 'struct iked_static' which is sent in
a single message.

ok patrick@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.160 23-Aug-2020 tobhe

Add a new configuration option to limit the number of connections for
each peer (identified by their 'dstid'). When 'set enforcesingleikesa'
is enabled, each peer can only have one active IKE SA at a time.
On successful authentication of a new connection, the old IKE SA is
automatically deleted.

ok patrick@


# 1.159 23-Aug-2020 tobhe

Rename natt_mode to sc_nattmode for consistency.


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.158 21-Aug-2020 tobhe

Use trusted CA from /etc/iked/ca/ as OCSP issuer to get rid of
/etc/iked/ocsp/issuer.crt.
Try to get the OCSP url from the CA/issuer certificate, otherwise
use the URL configured in 'set ocsp' in iked.conf.

ok patrick@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.157 18-Aug-2020 tobhe

Add optional time-stamp validaten for ocsp. The new optional 'tolerate'
parameter specifies how many seconds leeway are allowed in the check.
The optional maxage parameter indicates the allowed maximum age of
the `thisUpdate' OCSP attribute value.

ok patrick@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.156 16-Aug-2020 tobhe

Clean up unused parameters.


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.155 11-Aug-2020 tobhe

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

ok patrick@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.154 21-Jul-2020 tobhe

Handle TEMPORARY_FAILURE notification on IKESA rekeying.
If we rekey both the IKESA and an CHILDSA in a small time
window a strongswan peer might reposend with a TEMPORARY_FAILURE
notification.
In this case we retry the rekey of the IKESA after a short
timeout and queue PFKEY expire messages (by returning -1 in
ikev2_rekey_sa()), so the CHILDSA rekeying gets delayed.

ok markus@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.153 15-Jul-2020 tobhe

Make CERT and CERTREQ payloads optional for public key authentication.

When using certificate authentication the CERT payload is mandatory and as the
name suggests is used to send a certificate containing a public key used for
the authentication signature.
For pubkey authentication the key is preshared and stored locally, but only
the 'ca' process can read the local keys. The 'ikev2' process had to get the
key from the received CERT payload to verify the authentication signature.
The peer ID + raw key was then forwarded to the 'ca' process which
compared the key against the contents of /etc/iked/pubkey and returned either
CERTVALID or CERTINVALID.

With this change a message containing only the ID may be sent from 'ikev2' to
the 'ca' process if CERT was not included. In this case the CA process will
try to find a local key matching the ID and return it to the 'ikev2' process.
The auth verification happens after the 'ca' process has verified or found a
key and returned it to the 'ikev2' process, eliminating the need for
the CERT payload.

Making CERTREQ optional is easier because we already have a fallback case if
the CERTREQ can not be fulfilled. If no CERTREQ was received we now use this
same fallback.

This should fix public key authentication interoperability with *swan and
other IKEv2 implementations.

ok and tested by kn@
ok patrick@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.152 03-Jun-2020 tobhe

Pass sockaddr instead of sockaddr_storage to sa_address.

ok patrick@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.151 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.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.150 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.149 13-May-2020 tobhe

Remove dead 'iked_flow' member 'flow_type'.


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.148 08-May-2020 tobhe

Remove unneccessary X509_NAME_oneline wrapper. Passing NULL as buf
does the same thing.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.147 23-Apr-2020 tobhe

Add support for switching rdomain on IPsec encryption/decryption.
It can be configured per policy with the new 'rdomain' option
(see iked.conf(5)).
Only the unencrypted (inner) rdomain has to be configured, the
encrypted rdomain is always the one the responsible iked instance
is running in.

The configured rdomain must exist before iked activates the IPsec SAs,
otherwise pfkey will return an error.

ok markus@, patrick@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.146 20-Apr-2020 tobhe

Remove unused 'dsa_cert' variable.

ok markus@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.145 13-Apr-2020 tobhe

Try to send a DELETE message if the SA is reset with 'ikectl reset id'.
This way the peer can delete its SAs and eventually reestablish the
connection without having to wait for a timeout.

ok markus@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.144 11-Apr-2020 tobhe

If we haven't received any IKE message from our partner for some
time, make sure to send a DPD packet to him so that we break up
the connection faster if it's dead.

ok patrick@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.143 10-Apr-2020 tobhe

Only make the type part of the idstring lowercase when looking for certs in
'/etc/iked', otherwise certs with SubjAltNames containing uppercase
letters are not found.

ok markus@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.142 09-Apr-2020 tobhe

Simplify socket creation logic. Normally iked needs two sockets, one
for normal operation (UDP port 500) and one for NAT traversal (UDP 4500).
There are several command line options resulting in only one of the sockets
being created (-T, -t and -p). Add a new 'enum natt_mode' to make the
logic for those somewhat less complicated as well as some comments where
it makes sense.

From Wataru Ashihara <wataash (at) wataash (dot) com>
ok patrick@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.141 08-Apr-2020 tobhe

Prevent multiple ibuf leaks. Clean up on proccess shutdown.

ok markus@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.140 02-Apr-2020 tobhe

Store USE_TRANSPORTMODE in iked_message until the full message was parsed
and set the corresponding iked_sa field in ikev2_handle_notifies() like it
is done for other NOTIFY payloads.

ok markus@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.139 01-Apr-2020 tobhe

Properly handle multiple CERTREQ payloads in CA process. Only for the
last CERTREQ a mismatch should trigger the fallback case, otherwise the
following CERTREQs are ignored.

ok markus@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.138 31-Mar-2020 tobhe

Log summary of certificates in cert store when iked fails to find a
certificate for the policy's 'srcid'.

ok markus@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.137 24-Mar-2020 tobhe

Add ikev2_print_static_id() to print static IDs in log_debug() output.

ok markus@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.136 10-Mar-2020 tobhe

Relookup policy based on received cryptographic parameter proposal.
The IKEv2 responder does not know which policy is negotiated until
the ID payload is received in the IKE_AUTH exchange.
iked therefore chooses a default policy until the final policy is
selected. This change adds a policy relookup during the IKE_SA_INIT.
If the received proposal is not compatible with the default policy
we switch to the next highest ranked policy that is compatible
with the received proposal.

ok kn@ markus@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.135 01-Mar-2020 tobhe

When the proposals are first matched the responder does
not yet know the initiators ID and thus does not know which
policy applies. The policy is later updated based on the
received ID payload. Make sure the policy looked up during
IKE_AUTH is compatible with the negotiated proposal.

ok kn@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

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


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.134 21-Feb-2020 tobhe

Add transport mode for child SAs. This is useful for GRE over IPsec and
similar settings to prevent double encapsulation.

ok kn@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

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

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

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

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

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


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

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


# 1.72 22-Apr-2014 reyk

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

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

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


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

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


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

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


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.133 13-Feb-2020 tobhe

Constify "buf" argument in print_hex and print_hexval.

ok patrick@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.132 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.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.131 14-Jan-2020 tobhe

Remove IPsec flow blocking unencrypted IPv6 traffic which was
meant to prevent VPN leakage but repeatedly broke people's
setups. The -6 flag which used to disable the blocking flow is
now ignored and prints a deprecation warning.

ok kn@ bluhm@ phessler@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.130 07-Jan-2020 tobhe

Link ESP-SA and IPcomp-SA using GRPSPIS instead of using a self-built
solution for multi-SA flows. As a result we only need a single
outgoing IPCOMP flow and can get rid of the two extra transport mode flows
for ESP.

ok bluhm@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.129 10-Dec-2019 tobhe

We can receive a delete and free an SA that is referenced in sa_nextr.
Remove references when deleting the SA, otherwise we trigger a
use-after-free.

ok markus@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.128 03-Dec-2019 tobhe

Correctly represent flows as traffic selectors as described in RFC 7296. This
allows us to deduplicate the network ranges sent in the TS payload and saves
some bytes on the wire.

ok patrick@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.127 30-Nov-2019 tobhe

Log loaded SPIs and flows.

ok patrick@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.126 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.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.125 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.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.124 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.123 14-Aug-2019 tobhe

Fix NAT traversal detection bug when "local" option is not explicitly
set.

ok patrick@


# 1.122 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.121 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.121 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.120 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_4_BASE OPENBSD_6_5_BASE
# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.119 06-Aug-2018 mestre

Remove cpath pledge(2) promise. We decided that not deleting the unix control
sockets cause no harm and this way we close another attack surface by not
allowing the daemon to create/delete any more files.

OK kn@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.118 16-Mar-2018 mpi

Consistently spell "IPsec" in comments and debug outputs.

From Raf Czlonka, ok sthen@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@


# 1.117 30-Nov-2017 patrick

Add support for rejecting IKE SA messages. This means that we can reply
to IKE SA INIT messages with no proposal chosen, as we already do for
Child SAs. For that the error "adding" is done in a new function shared
by both send error handlers. We need two "send error" functions because
the init error is unencrypted, while all later ones are not. Now we can
add more cases, like Child SA not found or that the DH group is not what
we expect.

Save the IKE SA INIT responses, even if it's an error message, so we can
retransmit it if the response is lost on the way back to the initiator
and he tries again. This also helps mitigate DoS attacks as specified
in the RFC. Only if it is indeed a new attempt, like after an INVALID
KE PAYLOAD response, we can drop the old SA so that iked(8) can attempt
to create a new SA.

ok sthen@


# 1.116 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.115 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


# 1.114 13-Apr-2017 patrick

Add a NAT-T keepalive timer in case we are behind a NAT gateway.

See RFC 5996, section 2.23, NAT Traversal:
In the case of a mismatching NAT_DETECTION_DESTINATION_IP hash, it
means that the system receiving the NAT_DETECTION_DESTINATION_IP
payload is behind a NAT and that system SHOULD start sending
keepalive packets as defined in [UDPENCAPS].

With markus@, ok reyk@


Revision tags: OPENBSD_6_1_BASE
# 1.113 27-Mar-2017 mikeb

Don't cache the DH group in the policy

When tearing IKE SA down, the DH group referred by it is destroyed,
however it remains cached in the policy. With the introduction of
IKE SA rekeying we have extended the life of this dangling pointer
by reusing it on new SAs. So instead of caching the pointer in the
policy we can store the DH group ID and create a DH group on demand
using this parameter if it's specified.

With and OK reyk


# 1.112 27-Mar-2017 mikeb

Factor out flows into separate configuration messages

We reach an imsg payload limit with just a few traffic selectors
so in order to load more we need to split them up and send separately.

Suggested and OK reyk


# 1.111 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.110 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.109 13-Mar-2017 mikeb

Resolve simultaneous Child SA rekeying

From and OK markus, OK reyk


# 1.108 13-Mar-2017 mikeb

Resolve simultaneous IKE SA rekeying

From and OK markus, OK reyk


# 1.107 13-Mar-2017 reyk

Make sure that proposal contains a DH group when rekeying with PFS enabled

Via markus, OK mikeb@


# 1.106 13-Mar-2017 mikeb

Don't rekey acquired Child SAs

From and OK markus, OK reyk


# 1.105 13-Mar-2017 patrick

When setting up IPcomp flows for the networks 'A' and 'B' between
gateways 'a' and 'b', we replace the ESP flow "A->B ESP" with an
IPCOMP flow "A->B IPCOMP" and add a matching (transport mode) ESP
flow between the gateways "a->b ESP". The later is now marked with
flow_ipcomp so it is not translated into "a->b IPCOMP" on rekeying.

When SAs get deleted we do an extra loop to figure out if matching
IPcomp SAs can now be removed, too. This allows faster expiry of
unused IPcomp SAs.

Disable bytes lifetime for IP compression.

ok markus@ reyk@


# 1.104 13-Mar-2017 reyk

Fix and improve the IKE SA rekeying timeout, add a randomized jitter.

Diff from markus@ with a small tweak from me.

OK mikeb@ patrick@


# 1.103 13-Mar-2017 patrick

flow_cmp() must compare the same flow-attributes as the kernel,
otherwise we never can keep the in-daemon and the in-kernel idea
of flows in sync and iked ends up deleting flows that are still
in use. Make use of flow_cmp() and a new flow_equal() instead
of handcrafting the compare in an if.

ok markus@ reyk@


# 1.102 03-Feb-2017 guenther

Stop assuming that in_{addr,port}_t are typedefed in <sys/types.h> and
instead pull in <netinet/in.h> or <arpa/inet.h> when those are needed.

ok florian@ beck@ millert@


# 1.101 20-Jan-2017 mikeb

Constify the data argument for ibuf_new

From and OK markus@, OK reyk


# 1.100 09-Jan-2017 reyk

Stop accessing verbose and debug variables from log.c directly.

This replaces log_verbose() and "extern int verbose" with the two functions
log_setverbose() and log_getverbose().

Pointed out by benno@
OK krw@ eric@ gilles@ (OK gilles@ for the snmpd bits as well)


# 1.99 03-Jan-2017 reyk

Fix pledge of the ca process by calling the right function on startup.
As a related change, load the local.pub and local.key keys after
privsep and reload them on SIGHUP/reload.

OK mikeb@


# 1.98 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


# 1.97 03-Sep-2016 vgross

Add the missing bits to have NAT on enc(4) support in iked.

Ok mikeb@


Revision tags: OPENBSD_6_0_BASE
# 1.96 01-Jun-2016 patrick

Implement a second address pool specifically for IPv6, so that
clients can be given an IPv4 and IPv6 address at the same time,
thus enabling dual stack usage.

ok markus@ mikeb@


Revision tags: OPENBSD_5_9_BASE
# 1.95 07-Dec-2015 reyk

Sync proc.c, use shorter proc_compose[v]()


# 1.94 23-Nov-2015 reyk

Replace socket_set_blockmode() and fcntl(fd, F_SETFL, O_NONBLOCK) calls
with the SOCK_NONBLOCK flag to socket() and accept4().

OK claudio@ jung@


# 1.93 22-Nov-2015 reyk

Update log.c: change fatal() and fatalx() into variadic functions,
include the process name, and replace all calls of fatal*(NULL) with
fatal(__func__) for better debugging.

OK benno@


# 1.92 21-Nov-2015 reyk

Move local logging functions to util.c (which is shared with ikectl),
sync log.c with relayd and httpd - all three daemons are using a copy
of the same file now. Nevertheless, adding "extern int debug/verbose"
in util.c is not super nice but helps for now. No functional change.


# 1.91 22-Oct-2015 reyk

iked hereby pledges that it will run with restricted system
operations. This adds pledge(2) too all processes, including the iked
parent process; the existing privsep design has been improved for
better pledgeability. There haven't been any serious problems as it
was already sane (eg. by receiving the PFKEYv2 and UDP sockets via fd
passing). The control socket moved to an independent process to
remove some abilities from the cert process.

Committed in agreement with many but nobody was brave enough to OK it.

Better testing will happen with having it in the tree.
"It's the truth" deraadt@
"Let's see what happens" benno@


# 1.90 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.89 01-Oct-2015 reyk

Fix interoperability with Apple iOS9: If we don't get a (valid)
CERTREQ but a CERT, respond with a local CERT that was selected based
on our own policy instead of leaving it out. This seems to be valid
with the RFC that makes the CERTREQ optional and allows to ignore it
or to apply an own policy.

OK mikeb@ sthen@


# 1.88 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


# 1.87 19-Aug-2015 reyk

spacing (no binary change, verified with checksums)


Revision tags: OPENBSD_5_8_BASE
# 1.86 07-Jul-2015 markus

repair policy-ikesa-linking by replacing the broken RB_TREE w/TAILQ
(e.g. the policy might be used-after-free on 'ikectl reconfig')
ok mikeb@


# 1.85 11-Jun-2015 reyk

Use "compliant" header guards by avoiding the reserved '_' namespace.

Pointed out by Markus Elfring

OK mikeb@ millert@


# 1.84 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.83 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.82 18-Aug-2014 reyk

Sync proc.c with httpd. httpd needs SIGUSR1 but iked will ignore it
now instead of terminating the process.

ok mikeb@


Revision tags: OPENBSD_5_6_BASE
# 1.81 09-May-2014 markus

get rid of redundant {csa,flow}_{src,dst}id pointers, so we don't need
to update it on rekey (fixes use-after-free); ok mikeb@


# 1.80 09-May-2014 markus

replace iked_transform pointer with xform id, since target of pointer
might be freed (e.g. on ike sa rekey); ok mikeb@


# 1.79 08-May-2014 blambert

match iked proc.c infrastructure with proc.c

ok reyk@


# 1.78 07-May-2014 markus

make authentication work with X509 certificates that don't have a
subject-altname, i.e. support IKEV2_ID_ASN1_DN correctly;
feedback & ok mikeb@


# 1.77 06-May-2014 markus

change the create-child-sa responder code, so it does not store any
state in the ikesa structure. this way we can initiate a create-child-sa
and process requests for the peer at the same time. ok mikeb@


# 1.76 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.75 06-May-2014 markus

initial support for PFS; ok reyk@


# 1.74 06-May-2014 markus

retire IKED_REQ_DELETE and fix delete parsing; ok reyk@


# 1.73 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.72 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.71 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.70 21-Feb-2014 markus

support rekeying for IPCOMP; ok mikeb@


# 1.69 17-Feb-2014 markus

interpret 'config address net/prefix' as a pool of addresses and
randomly choose the address for CFG_REQUEST. this address will be used
to replace 0.0.0.0/32 in the specified flow. e.g.
> ikev2 passive esp from 192.168.1.0/24 to 0.0.0.0 \
> config address 192.168.10.200/24
will assign an address between 192.168.10.200 and 192.168.10.254
and replace 0.0.0.0 with this address.
ok mikeb@ on older version of this diff.


# 1.68 17-Feb-2014 markus

basic OCSP support. enable with 'set ocsp "http://10.0.0.10:8888/"'
ok mikeb@


# 1.67 14-Feb-2014 benno

remove unused function that distracts from cleaning up the imsg_flush() mess
ok krw, florian, henning


# 1.66 14-Feb-2014 markus

initial support for IPComp
still experimental and rekeying needs some work; ok mikeb@


# 1.65 24-Jan-2014 markus

enable format-string checks for log_*(); ok mikeb


# 1.64 24-Jan-2014 mikeb

use a bit saner timer api


# 1.63 22-Jan-2014 markus

implement DPD similar to isakmpd, but only send DPD-messages 'on-demand'
(less aggressive, only if the ESP-SAs are actually used);
feedback & ok mikeb@


# 1.62 09-Dec-2013 markus

distingush between sa_msgid not set and 0; otherwise we start
dropping messages if we usually are the initiator and the peer
initiates rekeying first. ok mikeb@


# 1.61 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.60 28-Nov-2013 markus

document sa_msgid & sa_reqid; ok mikeb@


# 1.59 28-Nov-2013 markus

support raw pubkey authentication w/o x509 certificates;
mostly by Michael Cardell Widerkrantz, reyk@ and mikeb@; ok mike@


# 1.58 21-Nov-2013 millert

Make the bit string u_char * in print_bits(). In practice we
shouldn't have chars > 127 in these but it is better not to assume
this. OK deraadt@


# 1.57 14-Nov-2013 markus

pass caller to ca_sslerror for better error messages; ok mikeb


Revision tags: OPENBSD_5_3_BASE OPENBSD_5_4_BASE
# 1.56 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.55 29-Nov-2012 reyk

Prevent VPN traffic leakages in dual-stack hosts/networks.
See http://tools.ietf.org/html/draft-gont-opsec-vpn-leakages.

We forcibly block IPv6 traffic by loading a "flow esp out from ::/0 to
::/0 type deny" unless the protocol is used in any of the flows. Note
that this will block any IPv6 traffic, superseding routes and pf, on
the host by default when iked is running with IPv4 flows only. This
auto-blocking feature can be disabled by specifying the "-6" command
line flag to iked.

Thanks to Fernando Gont.

ok mikeb@


# 1.54 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.53 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.52 02-Jul-2012 mikeb

Don't close IKE SA immediately after creating a new one when rekeying.
Instead set a timeout that will shut it down in case we don't get an SA
delete notification.


# 1.51 29-Jun-2012 mikeb

Add missing ESN bits


# 1.50 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.49 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.48 22-Jun-2012 mikeb

decouple timer initialization from timer_register


# 1.47 30-May-2012 mikeb

more timer changes


# 1.46 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.45 29-May-2012 mikeb

improve timer framework; will be needed soon


# 1.44 23-May-2012 mikeb

factor out proposal matching code from ikev2_sa_negotiate and eliminate
the protoid argument as a first step towards successful ah negotiation;
make code a bit more readable while here.


# 1.43 08-May-2012 mikeb

When setting up NAT-T notify payloads, make sure to supply an
actual source address so that a valid hash can be generated.
Fixes a bug introduces some time ago that prevented iked from
initiating if NAT-T wasn't disabled (via -T) and local address
wasn't specified.


# 1.42 05-Apr-2012 deraadt

rate-limit accepting of new connections while we are experiencing
fd exhaustion.
ok mikeb


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.41 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.


# 1.40 05-May-2011 reyk

Small tweak - add direct pointer to env instead of using an indirect one.


# 1.39 05-May-2011 reyk

Move the proc.c-specific runtime state out of struct iked into a sub-struct.
This removes iked-specific stuff from proc.c.


# 1.38 05-May-2011 reyk

rename iked_proc* to privsep_proc*. no functional change.


# 1.37 02-May-2011 mikeb

store the peer address as it was specified in the policy in the
tree that is used to figure out whether the policy is active or
not. makes active sa lookup via policy work for nat traversal.
problem was reported and fix was tested by sthen, ok sthen, reyk


# 1.36 18-Apr-2011 reyk

When the kernel wants to acquire an SA for an unknown flow, lookup a
matching policy and init a new IKE SA. This adds support for "acquire mode"
from static flows.

ok mikeb@


# 1.35 15-Apr-2011 reyk

remove unused function ikev2_flows_delete()


Revision tags: OPENBSD_4_9_BASE
# 1.34 26-Jan-2011 mikeb

get rid of acquire flows completely, as they tend to pass traffic
when there's no sa established (as pointed out by reyk). instead
use require mode feature to send acquires from the kernel. this
allows us to get rid of the code that changes flow mode to acquire
and keep all installed flows in the tree and save up on some code
that deals with renegotiation. also several entities were renamed
(iked_acqflows -> iked_activeflows, iked_ipsecsas -> iked_activesas,
ikev2_acquire -> ikev2_acquire_sa). ok reyk


# 1.33 21-Jan-2011 reyk

don't use memcmp on comparing two iked_addrs but IKED_ADDR_EQ.

ok mikeb@


# 1.32 21-Jan-2011 reyk

- Fix traffic selector configuration that it is always "from $localnet
to $peernet" and not depending on the initiator/responder mode.
- Remove the flow hash calculated but not used anymore.

ok mikeb@


# 1.31 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.30 21-Jan-2011 reyk

split pfkey initialization into a privileged and unprivileged part to
prevent a possible crash.

ok mikeb@


# 1.29 17-Jan-2011 mikeb

Add initial acquire mode support and use it whenever Windows peers decide
to drop Child SA based on the inactivity timer. In this case we instruct
the kernel to send us an acquire message upon receiving a packet for those
hosts and initiate a Child SA creation exchange ourselves.

ok reyk


# 1.28 17-Jan-2011 mikeb

move mask2prefixlen functions to the util module; ok reyk


# 1.27 12-Jan-2011 mikeb

postpone processing of pfkey messages received in pfkey_reply instead of
just dropping them; ok reyk


# 1.26 12-Jan-2011 mikeb

decouple flow deletion from the ikev2_childsa_delete; ok reyk


# 1.25 22-Dec-2010 reyk

move and rename util.c:print_id() to ikev2.c:ikev2_print_id() because
it is too specific to be in util.c. This will allow to link util.c
into ikectl later without all the other dependencies of pritn_id().


# 1.24 22-Dec-2010 reyk

split util.c into two files: imsg_util.c for ibuf/imsg stuff and util for
everything else. we might need to include util.c in ikectl later.

sure mikeb@


# 1.23 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.22 01-Dec-2010 reyk

Clarify the internal ibuf API: rename ibuf_copy() to ibuf_get() because
it returns a new buffer from the internal read offset like stdio get
functions do and not the same buffer when it is called multiple times.
Also rename the old ibuf_get() to ibuf_getdata() because it returns
a "special" data type and it matches the stdio get* conventions.

pointed out by mikeb@


# 1.21 17-Nov-2010 ckuethe

Allow the -D command line flag to actually define macros.
ok mikeb@ reyk@


# 1.20 22-Sep-2010 mikeb

support INVALID_KE_PAYLOAD notification sent by the responder in case
the initiator chose wrong D-H group. in this case we throw away our
SA and start over with a proper group.

makes iked work as an initiator with strongswan/charon without any
specific "ikesa" (phase 1) configuration.

ok reyk


# 1.19 09-Sep-2010 mikeb

- allow esp proposals without integrity and ah proposals without
encryption;

- add additional nonce length field, use that for the ciphers that
require additional keying material;

- setup right flow direction depending on the mode: fixes up iked
working as an initiator against charon.

tested by me and jsg.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.18 01-Jul-2010 reyk

Add support for the tap extension (ikev2 ... tap "enc1") that will
tell the kernel to send all IPsec traffic for derived SAs to the
specified enc(4) interface instead of enc0.


# 1.17 29-Jun-2010 reyk

add code to lookup the RSA public keys in /etc/iked/pubkeys/ as an
alternative to X.509 CA verification. this will be needed to support public
key authentication like isakmpd does; a few bits are still missing.


# 1.16 27-Jun-2010 reyk

When a peer requests a certificate from the local gateway, we first
lookup a cert from /etc/iked/certs/ that is signed by a requested CA.
As a second step we also compare the subjectAltName of any found
certificate now to match the local srcid; this allows to have multiple
certs for the same CA but different srcids in the certs/ directory but
enforces that the subjectAltName has to be set correctly.

requested by jsg@


# 1.15 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.14 26-Jun-2010 reyk

revert the files that have been accidentally committed with my
previous parse.y change.


# 1.13 26-Jun-2010 reyk

mixing any (AF_UNSPEC) with AF_INET/INET6 is not an address family mismatch


# 1.12 26-Jun-2010 reyk

Include the Id type in the generated SA tag that is passed to the
kernel, just like isakmpd does it. In difference to isakmpd, the Id
type is printed in capital letters, eg. FQDN/foo.example.com, because
it is using the existing print_map() API. For consistency, rename a
few Id types in grammar and code from the RFC-names to the
OpenBSD-style names; including RFC822_ADDR to UFQDN, IPV4_ADDR to just
IPV4, DER_ASN1_DN to ASN1_DN etc.


# 1.11 14-Jun-2010 reyk

Initiator mode with certificates; needs more work but works.


# 1.10 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.9 14-Jun-2010 reyk

NAT detection again: make it work in initiator and responder mode


# 1.8 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.7 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.6 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.5 11-Jun-2010 reyk

add some infrastructure to support timers and initiator mode later.


# 1.4 10-Jun-2010 reyk

add new commands: the couple/decouple commands will set loading of the
learned flows and SAs to the kernel which is useful for testing and
debugging. the active/passive commands are required to use iked
with sasyncd(8); sasyncd just needs to call "ikectl active/passive" or
send the appropriate imsg to support iked but this is not implemented yet.


# 1.3 10-Jun-2010 reyk

Add another tree to lookup policy SAs by peer address.


# 1.2 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.1 03-Jun-2010 reyk

Import iked, a new implementation of the IKEv2 protocol.

iked(8) is an automatic keying daemon for IPsec, like isakmpd(8), that
IPsec creates flows and SAs automatically. Unlike isakmpd, iked(8)
implements the newer IKEv2 protocol instead of IKEv1/ISAKMP. The
daemon is still work-in-progress and not enabled in the builds, but is
already able to establish IKEv2 sessions with some other IKEv2
implementations as a responder.

with lots of help and debugging by jsg@
ok deraadt@