History log of /openbsd-current/sys/netinet/ip_esp.c
Revision (<<< Hide revision tags) (Show revision tags >>>) Date Author Comments
# 1.195 03-May-2022 claudio

Retire CRYPTO_F_MPSAFE it is no longer of any use. The crypto framework
no longer uses a callback and so there is no need to define the
callback as MPSAFE.
OK bluhm@


Revision tags: OPENBSD_7_1_BASE
# 1.194 20-Jan-2022 bluhm

Shifting signed integers left by 31 is undefined behavior in C.
found by kubsan; joint work with tobhe@; OK miod@


# 1.193 23-Dec-2021 bluhm

Remove unused variables and assignments in ah and esp output.
found by clang 13; OK tobhe@


# 1.192 23-Dec-2021 bluhm

IPsec is not MP safe yet. To allow forwarding in parallel without
dirty hacks, it is better to protect IPsec input and output with
kernel lock. Not much is lost as crypto needs the kernel lock
anyway. From here we can refine the lock later.
Note that there is no kernel lock in the SPD lockup path. Goal is
to keep that lock free to allow fast forwarding with non IPsec
traffic.
tested by Hrvoje Popovski; OK tobhe@


# 1.191 20-Dec-2021 tobhe

Remove unused variable 'clen'.

ok bluhm@


# 1.190 20-Dec-2021 mvs

Use per-CPU counters for tunnel descriptor block (TDB) statistics.
'tdb_data' struct became unused and was removed.

Tested by Hrvoje Popovski.
ok bluhm@


# 1.189 11-Dec-2021 bluhm

Protect the write access to the TDB flags field with a mutex per
TDB. Clearing the timeout flags just before pool put in tdb_free()
does not make sense. Move this to tdb_delete(). While there make
the parentheses in the flag check consistent.
tested by Hrvoje Popovski; OK tobhe@


# 1.188 21-Nov-2021 mvs

Add the new `ipsec_exctdb' ipsec(4) counter to count and expose to the
userland the TDBs which exceeded hard limit.

Also the `ipsec_notdb' counter description in header doesn't math to
netstat(1) description. We never count `ipsec_notdb' and the netstat(1)
description looks more appropriate so it's used to avoid confusion with
the new counter.

ok bluhm@


# 1.187 11-Nov-2021 bluhm

Do not call ip_deliver() recursively from IPsec. As there is no
crypto task anymore, it is possible to return the next protocol.
Then ip_deliver() will walk the header chain in its loop.
IPsec bridge(4) tested by jan@
OK mvs@ tobhe@ jan@


# 1.186 08-Nov-2021 tobhe

Use plen consistently.

ok patrick@


# 1.185 04-Nov-2021 tobhe

The authenticator is removed elsewhere.

ok patrick@


# 1.184 24-Oct-2021 tobhe

Merge esp_input_cb() intp esp_input().

ok bluhm@


# 1.183 24-Oct-2021 bluhm

There are more m_pullup() in IPsec input. Pass down the pointer
to the mbuf to update it globally. At the end it will reach
ip_deliver() which expects a pointer to an mbuf.
OK sashan@


# 1.182 24-Oct-2021 tobhe

Remove 'struct tdb_crypto' allocations from esp_input() and esp_output().
This was needed to pass arguments to the callback function, but is no longer
necessary after the API makeover.

ok bluhm@


# 1.181 24-Oct-2021 tobhe

Remove crp_etype and return errors directly from crypto_invoke()

ok patrick@


# 1.180 24-Oct-2021 bluhm

Pass the error of the IPsec callback to the caller. The dropped
counter is handled there.
OK tobhe@


# 1.179 23-Oct-2021 bluhm

There is an m_pullup() down in AH input. As it may free or change
the mbuf, the callers must be careful. Although there is no bug,
use the common pattern to handle this. Pass down an mbuf pointer
mp and let m_pullup() update the pointer in all callers.
It looks like the tcp signature functions should not be called.
Avoid an mbuf leak and return an error.
OK mvs@


# 1.178 23-Oct-2021 tobhe

Retire asynchronous crypto API as it is no longer required by any driver and
adds unnecessary complexity. Dedicated crypto offloading devices are not common
anymore. Modern CPU crypto acceleration works synchronously, eliminating the need
for callbacks.

Replace all occurrences of crypto_dispatch() with crypto_invoke(), which is
blocking and only returns after the operation has completed or an error occured.
Invoke callback functions directly from the consumer (e.g. IPsec, softraid)
instead of relying on the crypto driver to call crypto_done().

ok bluhm@ mvs@ patrick@


# 1.177 22-Oct-2021 bluhm

Make error handling in IPsec consistent. Pass errors to the callers.
OK tobhe@


# 1.176 21-Oct-2021 tobhe

Remove code to run crypto operations in a task queue. The code was
not reachable because all callers had set the CRYPTO_F_NOQUEUE flag.

ok patrick@ mvs@ bluhm@


# 1.175 21-Oct-2021 tobhe

Remove duplicate variable ibytes, use plen instead.

ok bluhm@


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.194 20-Jan-2022 bluhm

Shifting signed integers left by 31 is undefined behavior in C.
found by kubsan; joint work with tobhe@; OK miod@


# 1.193 23-Dec-2021 bluhm

Remove unused variables and assignments in ah and esp output.
found by clang 13; OK tobhe@


# 1.192 23-Dec-2021 bluhm

IPsec is not MP safe yet. To allow forwarding in parallel without
dirty hacks, it is better to protect IPsec input and output with
kernel lock. Not much is lost as crypto needs the kernel lock
anyway. From here we can refine the lock later.
Note that there is no kernel lock in the SPD lockup path. Goal is
to keep that lock free to allow fast forwarding with non IPsec
traffic.
tested by Hrvoje Popovski; OK tobhe@


# 1.191 20-Dec-2021 tobhe

Remove unused variable 'clen'.

ok bluhm@


# 1.190 20-Dec-2021 mvs

Use per-CPU counters for tunnel descriptor block (TDB) statistics.
'tdb_data' struct became unused and was removed.

Tested by Hrvoje Popovski.
ok bluhm@


# 1.189 11-Dec-2021 bluhm

Protect the write access to the TDB flags field with a mutex per
TDB. Clearing the timeout flags just before pool put in tdb_free()
does not make sense. Move this to tdb_delete(). While there make
the parentheses in the flag check consistent.
tested by Hrvoje Popovski; OK tobhe@


# 1.188 21-Nov-2021 mvs

Add the new `ipsec_exctdb' ipsec(4) counter to count and expose to the
userland the TDBs which exceeded hard limit.

Also the `ipsec_notdb' counter description in header doesn't math to
netstat(1) description. We never count `ipsec_notdb' and the netstat(1)
description looks more appropriate so it's used to avoid confusion with
the new counter.

ok bluhm@


# 1.187 11-Nov-2021 bluhm

Do not call ip_deliver() recursively from IPsec. As there is no
crypto task anymore, it is possible to return the next protocol.
Then ip_deliver() will walk the header chain in its loop.
IPsec bridge(4) tested by jan@
OK mvs@ tobhe@ jan@


# 1.186 08-Nov-2021 tobhe

Use plen consistently.

ok patrick@


# 1.185 04-Nov-2021 tobhe

The authenticator is removed elsewhere.

ok patrick@


# 1.184 24-Oct-2021 tobhe

Merge esp_input_cb() intp esp_input().

ok bluhm@


# 1.183 24-Oct-2021 bluhm

There are more m_pullup() in IPsec input. Pass down the pointer
to the mbuf to update it globally. At the end it will reach
ip_deliver() which expects a pointer to an mbuf.
OK sashan@


# 1.182 24-Oct-2021 tobhe

Remove 'struct tdb_crypto' allocations from esp_input() and esp_output().
This was needed to pass arguments to the callback function, but is no longer
necessary after the API makeover.

ok bluhm@


# 1.181 24-Oct-2021 tobhe

Remove crp_etype and return errors directly from crypto_invoke()

ok patrick@


# 1.180 24-Oct-2021 bluhm

Pass the error of the IPsec callback to the caller. The dropped
counter is handled there.
OK tobhe@


# 1.179 23-Oct-2021 bluhm

There is an m_pullup() down in AH input. As it may free or change
the mbuf, the callers must be careful. Although there is no bug,
use the common pattern to handle this. Pass down an mbuf pointer
mp and let m_pullup() update the pointer in all callers.
It looks like the tcp signature functions should not be called.
Avoid an mbuf leak and return an error.
OK mvs@


# 1.178 23-Oct-2021 tobhe

Retire asynchronous crypto API as it is no longer required by any driver and
adds unnecessary complexity. Dedicated crypto offloading devices are not common
anymore. Modern CPU crypto acceleration works synchronously, eliminating the need
for callbacks.

Replace all occurrences of crypto_dispatch() with crypto_invoke(), which is
blocking and only returns after the operation has completed or an error occured.
Invoke callback functions directly from the consumer (e.g. IPsec, softraid)
instead of relying on the crypto driver to call crypto_done().

ok bluhm@ mvs@ patrick@


# 1.177 22-Oct-2021 bluhm

Make error handling in IPsec consistent. Pass errors to the callers.
OK tobhe@


# 1.176 21-Oct-2021 tobhe

Remove code to run crypto operations in a task queue. The code was
not reachable because all callers had set the CRYPTO_F_NOQUEUE flag.

ok patrick@ mvs@ bluhm@


# 1.175 21-Oct-2021 tobhe

Remove duplicate variable ibytes, use plen instead.

ok bluhm@


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.193 23-Dec-2021 bluhm

Remove unused variables and assignments in ah and esp output.
found by clang 13; OK tobhe@


# 1.192 23-Dec-2021 bluhm

IPsec is not MP safe yet. To allow forwarding in parallel without
dirty hacks, it is better to protect IPsec input and output with
kernel lock. Not much is lost as crypto needs the kernel lock
anyway. From here we can refine the lock later.
Note that there is no kernel lock in the SPD lockup path. Goal is
to keep that lock free to allow fast forwarding with non IPsec
traffic.
tested by Hrvoje Popovski; OK tobhe@


# 1.191 20-Dec-2021 tobhe

Remove unused variable 'clen'.

ok bluhm@


# 1.190 20-Dec-2021 mvs

Use per-CPU counters for tunnel descriptor block (TDB) statistics.
'tdb_data' struct became unused and was removed.

Tested by Hrvoje Popovski.
ok bluhm@


# 1.189 11-Dec-2021 bluhm

Protect the write access to the TDB flags field with a mutex per
TDB. Clearing the timeout flags just before pool put in tdb_free()
does not make sense. Move this to tdb_delete(). While there make
the parentheses in the flag check consistent.
tested by Hrvoje Popovski; OK tobhe@


# 1.188 21-Nov-2021 mvs

Add the new `ipsec_exctdb' ipsec(4) counter to count and expose to the
userland the TDBs which exceeded hard limit.

Also the `ipsec_notdb' counter description in header doesn't math to
netstat(1) description. We never count `ipsec_notdb' and the netstat(1)
description looks more appropriate so it's used to avoid confusion with
the new counter.

ok bluhm@


# 1.187 11-Nov-2021 bluhm

Do not call ip_deliver() recursively from IPsec. As there is no
crypto task anymore, it is possible to return the next protocol.
Then ip_deliver() will walk the header chain in its loop.
IPsec bridge(4) tested by jan@
OK mvs@ tobhe@ jan@


# 1.186 08-Nov-2021 tobhe

Use plen consistently.

ok patrick@


# 1.185 04-Nov-2021 tobhe

The authenticator is removed elsewhere.

ok patrick@


# 1.184 24-Oct-2021 tobhe

Merge esp_input_cb() intp esp_input().

ok bluhm@


# 1.183 24-Oct-2021 bluhm

There are more m_pullup() in IPsec input. Pass down the pointer
to the mbuf to update it globally. At the end it will reach
ip_deliver() which expects a pointer to an mbuf.
OK sashan@


# 1.182 24-Oct-2021 tobhe

Remove 'struct tdb_crypto' allocations from esp_input() and esp_output().
This was needed to pass arguments to the callback function, but is no longer
necessary after the API makeover.

ok bluhm@


# 1.181 24-Oct-2021 tobhe

Remove crp_etype and return errors directly from crypto_invoke()

ok patrick@


# 1.180 24-Oct-2021 bluhm

Pass the error of the IPsec callback to the caller. The dropped
counter is handled there.
OK tobhe@


# 1.179 23-Oct-2021 bluhm

There is an m_pullup() down in AH input. As it may free or change
the mbuf, the callers must be careful. Although there is no bug,
use the common pattern to handle this. Pass down an mbuf pointer
mp and let m_pullup() update the pointer in all callers.
It looks like the tcp signature functions should not be called.
Avoid an mbuf leak and return an error.
OK mvs@


# 1.178 23-Oct-2021 tobhe

Retire asynchronous crypto API as it is no longer required by any driver and
adds unnecessary complexity. Dedicated crypto offloading devices are not common
anymore. Modern CPU crypto acceleration works synchronously, eliminating the need
for callbacks.

Replace all occurrences of crypto_dispatch() with crypto_invoke(), which is
blocking and only returns after the operation has completed or an error occured.
Invoke callback functions directly from the consumer (e.g. IPsec, softraid)
instead of relying on the crypto driver to call crypto_done().

ok bluhm@ mvs@ patrick@


# 1.177 22-Oct-2021 bluhm

Make error handling in IPsec consistent. Pass errors to the callers.
OK tobhe@


# 1.176 21-Oct-2021 tobhe

Remove code to run crypto operations in a task queue. The code was
not reachable because all callers had set the CRYPTO_F_NOQUEUE flag.

ok patrick@ mvs@ bluhm@


# 1.175 21-Oct-2021 tobhe

Remove duplicate variable ibytes, use plen instead.

ok bluhm@


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.191 20-Dec-2021 tobhe

Remove unused variable 'clen'.

ok bluhm@


# 1.190 20-Dec-2021 mvs

Use per-CPU counters for tunnel descriptor block (TDB) statistics.
'tdb_data' struct became unused and was removed.

Tested by Hrvoje Popovski.
ok bluhm@


# 1.189 11-Dec-2021 bluhm

Protect the write access to the TDB flags field with a mutex per
TDB. Clearing the timeout flags just before pool put in tdb_free()
does not make sense. Move this to tdb_delete(). While there make
the parentheses in the flag check consistent.
tested by Hrvoje Popovski; OK tobhe@


# 1.188 21-Nov-2021 mvs

Add the new `ipsec_exctdb' ipsec(4) counter to count and expose to the
userland the TDBs which exceeded hard limit.

Also the `ipsec_notdb' counter description in header doesn't math to
netstat(1) description. We never count `ipsec_notdb' and the netstat(1)
description looks more appropriate so it's used to avoid confusion with
the new counter.

ok bluhm@


# 1.187 11-Nov-2021 bluhm

Do not call ip_deliver() recursively from IPsec. As there is no
crypto task anymore, it is possible to return the next protocol.
Then ip_deliver() will walk the header chain in its loop.
IPsec bridge(4) tested by jan@
OK mvs@ tobhe@ jan@


# 1.186 08-Nov-2021 tobhe

Use plen consistently.

ok patrick@


# 1.185 04-Nov-2021 tobhe

The authenticator is removed elsewhere.

ok patrick@


# 1.184 24-Oct-2021 tobhe

Merge esp_input_cb() intp esp_input().

ok bluhm@


# 1.183 24-Oct-2021 bluhm

There are more m_pullup() in IPsec input. Pass down the pointer
to the mbuf to update it globally. At the end it will reach
ip_deliver() which expects a pointer to an mbuf.
OK sashan@


# 1.182 24-Oct-2021 tobhe

Remove 'struct tdb_crypto' allocations from esp_input() and esp_output().
This was needed to pass arguments to the callback function, but is no longer
necessary after the API makeover.

ok bluhm@


# 1.181 24-Oct-2021 tobhe

Remove crp_etype and return errors directly from crypto_invoke()

ok patrick@


# 1.180 24-Oct-2021 bluhm

Pass the error of the IPsec callback to the caller. The dropped
counter is handled there.
OK tobhe@


# 1.179 23-Oct-2021 bluhm

There is an m_pullup() down in AH input. As it may free or change
the mbuf, the callers must be careful. Although there is no bug,
use the common pattern to handle this. Pass down an mbuf pointer
mp and let m_pullup() update the pointer in all callers.
It looks like the tcp signature functions should not be called.
Avoid an mbuf leak and return an error.
OK mvs@


# 1.178 23-Oct-2021 tobhe

Retire asynchronous crypto API as it is no longer required by any driver and
adds unnecessary complexity. Dedicated crypto offloading devices are not common
anymore. Modern CPU crypto acceleration works synchronously, eliminating the need
for callbacks.

Replace all occurrences of crypto_dispatch() with crypto_invoke(), which is
blocking and only returns after the operation has completed or an error occured.
Invoke callback functions directly from the consumer (e.g. IPsec, softraid)
instead of relying on the crypto driver to call crypto_done().

ok bluhm@ mvs@ patrick@


# 1.177 22-Oct-2021 bluhm

Make error handling in IPsec consistent. Pass errors to the callers.
OK tobhe@


# 1.176 21-Oct-2021 tobhe

Remove code to run crypto operations in a task queue. The code was
not reachable because all callers had set the CRYPTO_F_NOQUEUE flag.

ok patrick@ mvs@ bluhm@


# 1.175 21-Oct-2021 tobhe

Remove duplicate variable ibytes, use plen instead.

ok bluhm@


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.189 11-Dec-2021 bluhm

Protect the write access to the TDB flags field with a mutex per
TDB. Clearing the timeout flags just before pool put in tdb_free()
does not make sense. Move this to tdb_delete(). While there make
the parentheses in the flag check consistent.
tested by Hrvoje Popovski; OK tobhe@


# 1.188 21-Nov-2021 mvs

Add the new `ipsec_exctdb' ipsec(4) counter to count and expose to the
userland the TDBs which exceeded hard limit.

Also the `ipsec_notdb' counter description in header doesn't math to
netstat(1) description. We never count `ipsec_notdb' and the netstat(1)
description looks more appropriate so it's used to avoid confusion with
the new counter.

ok bluhm@


# 1.187 11-Nov-2021 bluhm

Do not call ip_deliver() recursively from IPsec. As there is no
crypto task anymore, it is possible to return the next protocol.
Then ip_deliver() will walk the header chain in its loop.
IPsec bridge(4) tested by jan@
OK mvs@ tobhe@ jan@


# 1.186 08-Nov-2021 tobhe

Use plen consistently.

ok patrick@


# 1.185 04-Nov-2021 tobhe

The authenticator is removed elsewhere.

ok patrick@


# 1.184 24-Oct-2021 tobhe

Merge esp_input_cb() intp esp_input().

ok bluhm@


# 1.183 24-Oct-2021 bluhm

There are more m_pullup() in IPsec input. Pass down the pointer
to the mbuf to update it globally. At the end it will reach
ip_deliver() which expects a pointer to an mbuf.
OK sashan@


# 1.182 24-Oct-2021 tobhe

Remove 'struct tdb_crypto' allocations from esp_input() and esp_output().
This was needed to pass arguments to the callback function, but is no longer
necessary after the API makeover.

ok bluhm@


# 1.181 24-Oct-2021 tobhe

Remove crp_etype and return errors directly from crypto_invoke()

ok patrick@


# 1.180 24-Oct-2021 bluhm

Pass the error of the IPsec callback to the caller. The dropped
counter is handled there.
OK tobhe@


# 1.179 23-Oct-2021 bluhm

There is an m_pullup() down in AH input. As it may free or change
the mbuf, the callers must be careful. Although there is no bug,
use the common pattern to handle this. Pass down an mbuf pointer
mp and let m_pullup() update the pointer in all callers.
It looks like the tcp signature functions should not be called.
Avoid an mbuf leak and return an error.
OK mvs@


# 1.178 23-Oct-2021 tobhe

Retire asynchronous crypto API as it is no longer required by any driver and
adds unnecessary complexity. Dedicated crypto offloading devices are not common
anymore. Modern CPU crypto acceleration works synchronously, eliminating the need
for callbacks.

Replace all occurrences of crypto_dispatch() with crypto_invoke(), which is
blocking and only returns after the operation has completed or an error occured.
Invoke callback functions directly from the consumer (e.g. IPsec, softraid)
instead of relying on the crypto driver to call crypto_done().

ok bluhm@ mvs@ patrick@


# 1.177 22-Oct-2021 bluhm

Make error handling in IPsec consistent. Pass errors to the callers.
OK tobhe@


# 1.176 21-Oct-2021 tobhe

Remove code to run crypto operations in a task queue. The code was
not reachable because all callers had set the CRYPTO_F_NOQUEUE flag.

ok patrick@ mvs@ bluhm@


# 1.175 21-Oct-2021 tobhe

Remove duplicate variable ibytes, use plen instead.

ok bluhm@


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.188 21-Nov-2021 mvs

Add the new `ipsec_exctdb' ipsec(4) counter to count and expose to the
userland the TDBs which exceeded hard limit.

Also the `ipsec_notdb' counter description in header doesn't math to
netstat(1) description. We never count `ipsec_notdb' and the netstat(1)
description looks more appropriate so it's used to avoid confusion with
the new counter.

ok bluhm@


# 1.187 11-Nov-2021 bluhm

Do not call ip_deliver() recursively from IPsec. As there is no
crypto task anymore, it is possible to return the next protocol.
Then ip_deliver() will walk the header chain in its loop.
IPsec bridge(4) tested by jan@
OK mvs@ tobhe@ jan@


# 1.186 08-Nov-2021 tobhe

Use plen consistently.

ok patrick@


# 1.185 04-Nov-2021 tobhe

The authenticator is removed elsewhere.

ok patrick@


# 1.184 24-Oct-2021 tobhe

Merge esp_input_cb() intp esp_input().

ok bluhm@


# 1.183 24-Oct-2021 bluhm

There are more m_pullup() in IPsec input. Pass down the pointer
to the mbuf to update it globally. At the end it will reach
ip_deliver() which expects a pointer to an mbuf.
OK sashan@


# 1.182 24-Oct-2021 tobhe

Remove 'struct tdb_crypto' allocations from esp_input() and esp_output().
This was needed to pass arguments to the callback function, but is no longer
necessary after the API makeover.

ok bluhm@


# 1.181 24-Oct-2021 tobhe

Remove crp_etype and return errors directly from crypto_invoke()

ok patrick@


# 1.180 24-Oct-2021 bluhm

Pass the error of the IPsec callback to the caller. The dropped
counter is handled there.
OK tobhe@


# 1.179 23-Oct-2021 bluhm

There is an m_pullup() down in AH input. As it may free or change
the mbuf, the callers must be careful. Although there is no bug,
use the common pattern to handle this. Pass down an mbuf pointer
mp and let m_pullup() update the pointer in all callers.
It looks like the tcp signature functions should not be called.
Avoid an mbuf leak and return an error.
OK mvs@


# 1.178 23-Oct-2021 tobhe

Retire asynchronous crypto API as it is no longer required by any driver and
adds unnecessary complexity. Dedicated crypto offloading devices are not common
anymore. Modern CPU crypto acceleration works synchronously, eliminating the need
for callbacks.

Replace all occurrences of crypto_dispatch() with crypto_invoke(), which is
blocking and only returns after the operation has completed or an error occured.
Invoke callback functions directly from the consumer (e.g. IPsec, softraid)
instead of relying on the crypto driver to call crypto_done().

ok bluhm@ mvs@ patrick@


# 1.177 22-Oct-2021 bluhm

Make error handling in IPsec consistent. Pass errors to the callers.
OK tobhe@


# 1.176 21-Oct-2021 tobhe

Remove code to run crypto operations in a task queue. The code was
not reachable because all callers had set the CRYPTO_F_NOQUEUE flag.

ok patrick@ mvs@ bluhm@


# 1.175 21-Oct-2021 tobhe

Remove duplicate variable ibytes, use plen instead.

ok bluhm@


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.187 11-Nov-2021 bluhm

Do not call ip_deliver() recursively from IPsec. As there is no
crypto task anymore, it is possible to return the next protocol.
Then ip_deliver() will walk the header chain in its loop.
IPsec bridge(4) tested by jan@
OK mvs@ tobhe@ jan@


# 1.186 08-Nov-2021 tobhe

Use plen consistently.

ok patrick@


# 1.185 04-Nov-2021 tobhe

The authenticator is removed elsewhere.

ok patrick@


# 1.184 24-Oct-2021 tobhe

Merge esp_input_cb() intp esp_input().

ok bluhm@


# 1.183 24-Oct-2021 bluhm

There are more m_pullup() in IPsec input. Pass down the pointer
to the mbuf to update it globally. At the end it will reach
ip_deliver() which expects a pointer to an mbuf.
OK sashan@


# 1.182 24-Oct-2021 tobhe

Remove 'struct tdb_crypto' allocations from esp_input() and esp_output().
This was needed to pass arguments to the callback function, but is no longer
necessary after the API makeover.

ok bluhm@


# 1.181 24-Oct-2021 tobhe

Remove crp_etype and return errors directly from crypto_invoke()

ok patrick@


# 1.180 24-Oct-2021 bluhm

Pass the error of the IPsec callback to the caller. The dropped
counter is handled there.
OK tobhe@


# 1.179 23-Oct-2021 bluhm

There is an m_pullup() down in AH input. As it may free or change
the mbuf, the callers must be careful. Although there is no bug,
use the common pattern to handle this. Pass down an mbuf pointer
mp and let m_pullup() update the pointer in all callers.
It looks like the tcp signature functions should not be called.
Avoid an mbuf leak and return an error.
OK mvs@


# 1.178 23-Oct-2021 tobhe

Retire asynchronous crypto API as it is no longer required by any driver and
adds unnecessary complexity. Dedicated crypto offloading devices are not common
anymore. Modern CPU crypto acceleration works synchronously, eliminating the need
for callbacks.

Replace all occurrences of crypto_dispatch() with crypto_invoke(), which is
blocking and only returns after the operation has completed or an error occured.
Invoke callback functions directly from the consumer (e.g. IPsec, softraid)
instead of relying on the crypto driver to call crypto_done().

ok bluhm@ mvs@ patrick@


# 1.177 22-Oct-2021 bluhm

Make error handling in IPsec consistent. Pass errors to the callers.
OK tobhe@


# 1.176 21-Oct-2021 tobhe

Remove code to run crypto operations in a task queue. The code was
not reachable because all callers had set the CRYPTO_F_NOQUEUE flag.

ok patrick@ mvs@ bluhm@


# 1.175 21-Oct-2021 tobhe

Remove duplicate variable ibytes, use plen instead.

ok bluhm@


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.186 08-Nov-2021 tobhe

Use plen consistently.

ok patrick@


# 1.185 04-Nov-2021 tobhe

The authenticator is removed elsewhere.

ok patrick@


# 1.184 24-Oct-2021 tobhe

Merge esp_input_cb() intp esp_input().

ok bluhm@


# 1.183 24-Oct-2021 bluhm

There are more m_pullup() in IPsec input. Pass down the pointer
to the mbuf to update it globally. At the end it will reach
ip_deliver() which expects a pointer to an mbuf.
OK sashan@


# 1.182 24-Oct-2021 tobhe

Remove 'struct tdb_crypto' allocations from esp_input() and esp_output().
This was needed to pass arguments to the callback function, but is no longer
necessary after the API makeover.

ok bluhm@


# 1.181 24-Oct-2021 tobhe

Remove crp_etype and return errors directly from crypto_invoke()

ok patrick@


# 1.180 24-Oct-2021 bluhm

Pass the error of the IPsec callback to the caller. The dropped
counter is handled there.
OK tobhe@


# 1.179 23-Oct-2021 bluhm

There is an m_pullup() down in AH input. As it may free or change
the mbuf, the callers must be careful. Although there is no bug,
use the common pattern to handle this. Pass down an mbuf pointer
mp and let m_pullup() update the pointer in all callers.
It looks like the tcp signature functions should not be called.
Avoid an mbuf leak and return an error.
OK mvs@


# 1.178 23-Oct-2021 tobhe

Retire asynchronous crypto API as it is no longer required by any driver and
adds unnecessary complexity. Dedicated crypto offloading devices are not common
anymore. Modern CPU crypto acceleration works synchronously, eliminating the need
for callbacks.

Replace all occurrences of crypto_dispatch() with crypto_invoke(), which is
blocking and only returns after the operation has completed or an error occured.
Invoke callback functions directly from the consumer (e.g. IPsec, softraid)
instead of relying on the crypto driver to call crypto_done().

ok bluhm@ mvs@ patrick@


# 1.177 22-Oct-2021 bluhm

Make error handling in IPsec consistent. Pass errors to the callers.
OK tobhe@


# 1.176 21-Oct-2021 tobhe

Remove code to run crypto operations in a task queue. The code was
not reachable because all callers had set the CRYPTO_F_NOQUEUE flag.

ok patrick@ mvs@ bluhm@


# 1.175 21-Oct-2021 tobhe

Remove duplicate variable ibytes, use plen instead.

ok bluhm@


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.185 04-Nov-2021 tobhe

The authenticator is removed elsewhere.

ok patrick@


# 1.184 24-Oct-2021 tobhe

Merge esp_input_cb() intp esp_input().

ok bluhm@


# 1.183 24-Oct-2021 bluhm

There are more m_pullup() in IPsec input. Pass down the pointer
to the mbuf to update it globally. At the end it will reach
ip_deliver() which expects a pointer to an mbuf.
OK sashan@


# 1.182 24-Oct-2021 tobhe

Remove 'struct tdb_crypto' allocations from esp_input() and esp_output().
This was needed to pass arguments to the callback function, but is no longer
necessary after the API makeover.

ok bluhm@


# 1.181 24-Oct-2021 tobhe

Remove crp_etype and return errors directly from crypto_invoke()

ok patrick@


# 1.180 24-Oct-2021 bluhm

Pass the error of the IPsec callback to the caller. The dropped
counter is handled there.
OK tobhe@


# 1.179 23-Oct-2021 bluhm

There is an m_pullup() down in AH input. As it may free or change
the mbuf, the callers must be careful. Although there is no bug,
use the common pattern to handle this. Pass down an mbuf pointer
mp and let m_pullup() update the pointer in all callers.
It looks like the tcp signature functions should not be called.
Avoid an mbuf leak and return an error.
OK mvs@


# 1.178 23-Oct-2021 tobhe

Retire asynchronous crypto API as it is no longer required by any driver and
adds unnecessary complexity. Dedicated crypto offloading devices are not common
anymore. Modern CPU crypto acceleration works synchronously, eliminating the need
for callbacks.

Replace all occurrences of crypto_dispatch() with crypto_invoke(), which is
blocking and only returns after the operation has completed or an error occured.
Invoke callback functions directly from the consumer (e.g. IPsec, softraid)
instead of relying on the crypto driver to call crypto_done().

ok bluhm@ mvs@ patrick@


# 1.177 22-Oct-2021 bluhm

Make error handling in IPsec consistent. Pass errors to the callers.
OK tobhe@


# 1.176 21-Oct-2021 tobhe

Remove code to run crypto operations in a task queue. The code was
not reachable because all callers had set the CRYPTO_F_NOQUEUE flag.

ok patrick@ mvs@ bluhm@


# 1.175 21-Oct-2021 tobhe

Remove duplicate variable ibytes, use plen instead.

ok bluhm@


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.184 24-Oct-2021 tobhe

Merge esp_input_cb() intp esp_input().

ok bluhm@


# 1.183 24-Oct-2021 bluhm

There are more m_pullup() in IPsec input. Pass down the pointer
to the mbuf to update it globally. At the end it will reach
ip_deliver() which expects a pointer to an mbuf.
OK sashan@


# 1.182 24-Oct-2021 tobhe

Remove 'struct tdb_crypto' allocations from esp_input() and esp_output().
This was needed to pass arguments to the callback function, but is no longer
necessary after the API makeover.

ok bluhm@


# 1.181 24-Oct-2021 tobhe

Remove crp_etype and return errors directly from crypto_invoke()

ok patrick@


# 1.180 24-Oct-2021 bluhm

Pass the error of the IPsec callback to the caller. The dropped
counter is handled there.
OK tobhe@


# 1.179 23-Oct-2021 bluhm

There is an m_pullup() down in AH input. As it may free or change
the mbuf, the callers must be careful. Although there is no bug,
use the common pattern to handle this. Pass down an mbuf pointer
mp and let m_pullup() update the pointer in all callers.
It looks like the tcp signature functions should not be called.
Avoid an mbuf leak and return an error.
OK mvs@


# 1.178 23-Oct-2021 tobhe

Retire asynchronous crypto API as it is no longer required by any driver and
adds unnecessary complexity. Dedicated crypto offloading devices are not common
anymore. Modern CPU crypto acceleration works synchronously, eliminating the need
for callbacks.

Replace all occurrences of crypto_dispatch() with crypto_invoke(), which is
blocking and only returns after the operation has completed or an error occured.
Invoke callback functions directly from the consumer (e.g. IPsec, softraid)
instead of relying on the crypto driver to call crypto_done().

ok bluhm@ mvs@ patrick@


# 1.177 22-Oct-2021 bluhm

Make error handling in IPsec consistent. Pass errors to the callers.
OK tobhe@


# 1.176 21-Oct-2021 tobhe

Remove code to run crypto operations in a task queue. The code was
not reachable because all callers had set the CRYPTO_F_NOQUEUE flag.

ok patrick@ mvs@ bluhm@


# 1.175 21-Oct-2021 tobhe

Remove duplicate variable ibytes, use plen instead.

ok bluhm@


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.180 24-Oct-2021 bluhm

Pass the error of the IPsec callback to the caller. The dropped
counter is handled there.
OK tobhe@


# 1.179 23-Oct-2021 bluhm

There is an m_pullup() down in AH input. As it may free or change
the mbuf, the callers must be careful. Although there is no bug,
use the common pattern to handle this. Pass down an mbuf pointer
mp and let m_pullup() update the pointer in all callers.
It looks like the tcp signature functions should not be called.
Avoid an mbuf leak and return an error.
OK mvs@


# 1.178 23-Oct-2021 tobhe

Retire asynchronous crypto API as it is no longer required by any driver and
adds unnecessary complexity. Dedicated crypto offloading devices are not common
anymore. Modern CPU crypto acceleration works synchronously, eliminating the need
for callbacks.

Replace all occurrences of crypto_dispatch() with crypto_invoke(), which is
blocking and only returns after the operation has completed or an error occured.
Invoke callback functions directly from the consumer (e.g. IPsec, softraid)
instead of relying on the crypto driver to call crypto_done().

ok bluhm@ mvs@ patrick@


# 1.177 22-Oct-2021 bluhm

Make error handling in IPsec consistent. Pass errors to the callers.
OK tobhe@


# 1.176 21-Oct-2021 tobhe

Remove code to run crypto operations in a task queue. The code was
not reachable because all callers had set the CRYPTO_F_NOQUEUE flag.

ok patrick@ mvs@ bluhm@


# 1.175 21-Oct-2021 tobhe

Remove duplicate variable ibytes, use plen instead.

ok bluhm@


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.177 22-Oct-2021 bluhm

Make error handling in IPsec consistent. Pass errors to the callers.
OK tobhe@


# 1.176 21-Oct-2021 tobhe

Remove code to run crypto operations in a task queue. The code was
not reachable because all callers had set the CRYPTO_F_NOQUEUE flag.

ok patrick@ mvs@ bluhm@


# 1.175 21-Oct-2021 tobhe

Remove duplicate variable ibytes, use plen instead.

ok bluhm@


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.176 21-Oct-2021 tobhe

Remove code to run crypto operations in a task queue. The code was
not reachable because all callers had set the CRYPTO_F_NOQUEUE flag.

ok patrick@ mvs@ bluhm@


# 1.175 21-Oct-2021 tobhe

Remove duplicate variable ibytes, use plen instead.

ok bluhm@


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.175 21-Oct-2021 tobhe

Remove duplicate variable ibytes, use plen instead.

ok bluhm@


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.174 13-Oct-2021 bluhm

The function crypto_dispatch() never returns an error. Make it
void and remove error handling in the callers.
OK patrick@ mvs@


# 1.173 13-Oct-2021 bluhm

The function ipip_output() was registered as .xf_output() xform
function. But was is never called via this pointer. It would have
immediatley crashed as mp is always NULL when called via .xf_output().
Do not set .xf_output to ipip_output. This allows to pass only the
parameters which are actually needed and the control flow is clearer.
OK mpi@


Revision tags: OPENBSD_7_0_BASE
# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.172 27-Jul-2021 mvs

Revert "Use per-CPU counters for tunnel descriptor block" diff.

Panic reported by Hrvoje Popovski.


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.171 26-Jul-2021 mvs

Use per-CPU counters for tunnel descriptor block (tdb) statistics.
'tdb_data' struct became unused and was removed.

ok bluhm@


# 1.170 26-Jul-2021 bluhm

Do not queue crypto operations for IPsec. The packet entries in
task queues were unlimited and could overflow during havy traffic.
Even if we still use hardware drivers that sleep, softnet task
instead of soft interrupt can handle this now. Without queues net
lock is inherited and kernel lock is only needed once per packet.
This results in less lock contention and faster IPsec.
Also protect tdb drop counters with net lock and avoid a leak in
crypto dispatch error handling.
intense testing Hrvoje Popovski; OK mpi@


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.169 18-Jul-2021 bluhm

The IPsec authentication before decryption used a different replay
counter than after decryption. This could result in "esp_input_cb:
authentication failed for packet in SA" errors. As we run crypto
operations async, thousands of packets are stored in the crypto
task. During the queueing the replay counter of the tdb can change.
Then the higher 32 bits may increment although the lower 32 bits
did not wrap.
checkreplaywindow() must be called twice per packet with the same
replay counter. Store the value in struct tdb_crypto while dangling
in the task queue and doing crypto operations.
tested by Hrvoje Popovski; joint work with tobhe@


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.168 16-Jul-2021 bluhm

Improve comments in IPsec replay window calculation.
OK tobhe@


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.167 08-Jul-2021 bluhm

The xformsw array never changes. Declare struct xformsw constant
and map data read only.
OK deraadt@ mvs@ mpi@


# 1.166 08-Jul-2021 bluhm

Debug printfs in encdebug were inconsistent, some missing newlines
produced ugly output. Move the function name and the newline into
the DPRINTF macro. This simplifies the debug statements.
OK tobhe@


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.165 08-Jul-2021 bluhm

The properties of the crypto algorithms never change. Declare them
constant. Then they are mapped as read only.
OK deraadt@ dlg@


# 1.164 07-Jul-2021 bluhm

Fix whitespaces in IPsec code.


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.163 18-Jun-2021 bluhm

The crypto(9) framework used by IPsec runs on a kernel task that
is protected by kernel lock. There were crashes in swcr_authenc()
when it was accessing swcr_sessions. As a quick fix, protect all
calls from network stack to crypto with kernel lock. This also
covers the rekeying case that is called from pfkey via tdb_init().
OK mvs@


Revision tags: OPENBSD_6_9_BASE
# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.162 25-Feb-2021 dlg

we don't have to cast to caddr_t when calling m_copydata anymore.

the first cut of this diff was made with coccinelle using this spatch:

@rule@
type caddr_t;
expression m, off, len, cp;
@@
-m_copydata(m, off, len, (caddr_t)cp)
+m_copydata(m, off, len, cp)

i had fix it's opinionated idea of formatting by hand though, so
i'm not sure it was worth it.

ok deraadt@ bluhm@


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.161 18-Dec-2020 tobhe

Make sure the first packet of an SA has sequence number 1 (as described in
RFC 4302 and RFC 4303). It seems this was changed by accident when support
for 64 bit sequence numbers was added.

ok bluhm@ patrick@


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.160 16-Dec-2020 tobhe

Use ESP sequence number as IV for AES-CTR, AES-GCM and Chacha20.
This eliminates the risk for IV reuse because of random collisions
and increases performance a little.

ok patrick@ markus@


Revision tags: OPENBSD_6_6_BASE OPENBSD_6_7_BASE OPENBSD_6_8_BASE
# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.159 30-Sep-2019 dlg

remove the "copy function" argument to bpf_mtap_hdr.

it was previously (ab)used by pflog, which has since been fixed.
apart from that nothing else used it, so we can trim the cruft.

ok kn@ claudio@ visa@
visa@ also made sure i fixed ipw(4) so i386 won't break.


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.158 28-Aug-2018 mpi

Add per-TDB counters and a new SADB extension to export them to
userland.

Inputs from markus@, ok sthen@


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.157 12-Jul-2018 mpi

Introduce ipsec_output_cb() to merge duplicate code and account for
dropped packets in the output path.

While here fix a memory leak when compression is not needed w/ IPcomp.

ok markus@


# 1.156 11-Jul-2018 mpi

Convert AH & IPcomp to ipsec_input_cb() and count drops on input.

ok markus@


# 1.155 10-Jul-2018 mpi

Introduce new IPsec (per-CPU) statistics and refactor ESP input
callbacks to be able to count dropped packet.

Having more generic statistics will help troubleshooting problems
with specific tunnels. Per-TDB counters are coming once all the
refactoring bits are in.

ok markus@


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.154 09-May-2018 bluhm

Cleanup IPsec ESP error handling with consistent goto drop.
with and OK markus@


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.153 02-May-2018 bluhm

Do not assume that mbufs within a chain do not have M_PKTHDR set.
This could happen during fragment reassembly. Better check if we
are dealing with the first mbuf of the chain.
m_adj() changes the length of the mbuf, obviously. So when using
this length to calulate the amount of adjustment, do not calculate
it again after m_adj() with wrong input. Use a temporary variable
to save the value.
from Maxime Villard, NetBSD; OK markus@ claudio@


Revision tags: OPENBSD_6_3_BASE
# 1.152 08-Nov-2017 visa

branches: 1.152.2;
Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

branches: 1.150.4;
Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz


# 1.152 08-Nov-2017 visa

Make {ah,esp,ipcomp}stat use percpu counters.

OK bluhm@, mpi@


# 1.151 06-Nov-2017 mpi

Use %s and __func__ in DPRINTF() to reduce false positive with grep(1).

ok kettenis@, dhill@, visa@, jca@


Revision tags: OPENBSD_6_2_BASE
# 1.150 11-Aug-2017 mpi

Remove NET_LOCK()'s argument.

Tested by Hrvoje Popovski, ok bluhm@


# 1.149 30-May-2017 deraadt

add sizes to free() calls


# 1.148 02-May-2017 mikeb

Switch OCF and IPsec over to the new AES

ok djm


# 1.147 06-Apr-2017 dhill

Convert bcopy to memcpy where the memory does not overlap, otherwise,
use memmove. While here, change some previous conversions to a simple
assignment.

ok deraadt@


Revision tags: OPENBSD_6_1_BASE
# 1.146 07-Feb-2017 bluhm

IPsec packets could be dropped unaccounted if output after crypto
failed. Add a counter for that case.
OK dhill@


# 1.145 07-Feb-2017 patrick

Reduce the per-packet allocation costs for crypto operations (cryptop)
by pre-allocating two cryptodesc objects and storing them in an array
instead of a linked list. If more than two cryptodesc objects are
required use mallocarray to fetch them. Adapt the drivers to the new
API.

This change results in one pool-get per ESP packet instead of three.
It also simplifies softraid crypto where more cryptodesc objects are
allocated than used.

From, with and ok markus@, ok bluhm@
"looks sane" mpi@


# 1.144 07-Feb-2017 bluhm

The return code of crp_callback is never checked, so it is not
useful to propagate the error. When an error occurs in an asynchronous
network path, incrementing a counter is the right thing. There are
four places where an error is not accounted, just add a comment for
now.
OK mpi@ visa@


# 1.143 09-Jan-2017 mpi

Grab the NET_LOCK() in various callbacks.

Fix an assert reported by Hrvoje Popovski.

ok visa@, mikeb@


# 1.142 24-Dec-2016 mpi

Grab the NET_LOCK() before calling ipsp_process_done() as it ends up
in ip_output().

Found the hardway by and ok kettenis@


# 1.141 19-Sep-2016 tedu

convert bcopy to memcpy. from david hill.


# 1.140 13-Sep-2016 markus

avoid extensive mbuf allocation for IPsec by replacing m_inject(4)
with m_makespace(4) from freebsd; ok mpi@, bluhm@, mikeb@, dlg@


# 1.139 18-Aug-2016 dlg

fix panics caused by replacing m_copym2 with m_dup_pkt.

m_copym2 is fine duplicating an arbitrary chain of mbufs, while
m_dup_pkt wants to dup a packet with proper headers in the first
mbuf. ipsec copied the tail of an mbuf if any of the clusters are
shared or readonly, and swapped that tail with the result of m_copym2.

m_dup_pkt panics cos of that.

this makes ipsec duplicate the whole packet if any of the chain is
readonly.

found by naddy@ and mlarkin@
this fix is from visa@ who told me to commit it cos he's afk (sleeping)
tested by naddy@


# 1.138 15-Aug-2016 dlg

replace the last uses of m_copym2 with m_dup_pkt.

ok mpi@ visa@


Revision tags: OPENBSD_6_0_BASE
# 1.137 07-Mar-2016 naddy

Sync no-argument function declaration and definition by adding (void).
ok mpi@ millert@


Revision tags: OPENBSD_5_9_BASE
# 1.136 09-Dec-2015 naddy

Remove plain DES encryption from IPsec.

DES is insecure since brute force attacks are practical due to its
short key length.

This removes support for DES-CBC encryption in ESP and in IKE main
and quick mode from the kernel, isakmpd(8), ipsecctl(8), and iked(8).

ok mikeb@


# 1.135 03-Nov-2015 mikeb

Plumb Chacha20-Poly1305 into the IPsec/ESP and PF_KEY frameworks

ok naddy


Revision tags: OPENBSD_5_8_BASE
# 1.134 15-Jul-2015 deraadt

m_freem() can handle NULL, do not check for this condition beforehands.
ok stsp mpi


# 1.133 15-Jun-2015 mikeb

No need for an extra local variable; no functional change.


# 1.132 15-Jun-2015 mikeb

Use proper argument type for crp_callback functions; no functional change.


# 1.131 17-Apr-2015 mikeb

Stubs and support code for NIC-enabled IPsec bite the dust.
No objection from reyk@, OK markus, hshoexer


# 1.130 14-Apr-2015 mikeb

make ipsp_address thread safe; ok mpi


Revision tags: OPENBSD_5_7_BASE
# 1.129 19-Dec-2014 tedu

unifdef INET in net code as a precursor to removing the pretend option.
long live the one true internet.
ok henning mikeb


# 1.128 05-Dec-2014 mpi

Explicitly include <net/if_var.h> instead of pulling it in <net/if.h>.

ok mikeb@, krw@, bluhm@, tedu@


# 1.127 18-Nov-2014 tedu

move arc4random prototype to systm.h. more appropriate for most code
to include that than rdnvar.h. ok deraadt dlg


Revision tags: OPENBSD_5_6_BASE
# 1.126 22-Jul-2014 mpi

Fewer <netinet/in_systm.h> !


# 1.125 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.124 09-Jul-2014 henning

bpf code surgery / shuffling / simplification.
the various bpf_mtap_* are very similiar, they differ in what (and to some
extent how) they prepend something, and what copy function they pass to
bpf_catchpacket.
use an internal _bpf_mtap as "backend" for bpf_mtap and friends.
extend bpf_mtap_hdr so that it covers all common cases:
if dlen is 0, nothing gets prepended.
copy function can be given, if NULL the default bpf_mcopy is used.
adjust the existing bpf_mtap_hdr users to pass a NULL ptr for the copy fn.
re-implement bpf_mtap_af as simple wrapper for bpf_mtap_hdr.
re-implement bpf_mtap_ether using bpf_map_hdr
re-implement bpf_mtap_pflog as trivial bpf_mtap_hdr wrapper
ok bluhm benno


Revision tags: OPENBSD_5_5_BASE
# 1.123 09-Jan-2014 tedu

bzero/bcmp -> memset/memcmp. ok matthew


Revision tags: OPENBSD_5_4_BASE
# 1.122 11-Apr-2013 mpi

Remove the extern keyword from function declarations, document
sysctl declarations, move variables and functions used in only
one place in their corresponding file. No functional change.

No objection from markus@, ok mikeb@


Revision tags: OPENBSD_5_3_BASE
# 1.121 14-Feb-2013 mikeb

Merge of an original work by markus@ and gerhard@ to increase
the anti-replay window size to 2100 entries; plus small ESN
related improvements. ok markus


# 1.120 18-Oct-2012 markus

simplify checkreplaywindow() API; make call/return code handling consistent
ok mikeb@


# 1.119 20-Sep-2012 blambert

spltdb() was really just #define'd to be splsoftnet(); replace the former
with the latter

no change in md5 checksum of generated files

ok claudio@ henning@


# 1.118 18-Sep-2012 markus

remove the SADB_X_SAFLAGS_{HALFIV,RANDOMPADDING,NOREPLAY} pfkey-API (not set
anywhere) as well as the matching TDBF_{HALFIV,RANDOMPADDING,NOREPLAY} code.
ok mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.117 29-Jun-2012 mikeb

Add support for the Extended (64-bit) Sequence Number as defined
in RFC4302 and RFC4303. Right now only software crypto engine is
capable of doing it.

Replay check was rewritten to implement algorithm described in the
Appendix A of RFC4303 and the window size was increased to 64.

Tested against OpenBSD, Linux (strongswan) and Windows.

No objection from the usual suspects.


Revision tags: OPENBSD_4_9_BASE OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.116 11-Jan-2011 deraadt

for key material that is being being discarded, convert bzero() to
explicit_bzero() where required
ok markus mikeb


# 1.115 21-Dec-2010 markus

don't leak mbuf if padding failes; ok mikeb@


# 1.114 06-Oct-2010 mikeb

Retire Skipjack

There's not much use for the declassified cipher from the 80's
with a questionable license these days. According to the FIPS
drafts, Skipjack reaches its EOL in December 2010.

The libc portion will be removed after the ports hackathon.

djm and thib agree, no objections from deraadt
Thanks to jsg for digging up FIPS drafts.


# 1.113 23-Sep-2010 mikeb

remove m_pad in favor of m_inject as it's equivalent to m_inject
with an offset equal to the actual data length.

ok henning blambert


# 1.112 22-Sep-2010 mikeb

Support for AES-GCM-16 and ENCR_NULL_AUTH_AES_GMAC in ESP as per
RFC 4106 and 4543.

Authentication hash key is set to be the same as an encryption key.

The length that is specified for the authentication hash descriptor
denotes the the length of Additional Authentication Data (AAD).
The encryption transformation descriptor length denotes the length
of the payload (to be encrypted and authenticated).

ENCR_NULL_AUTH_AES_GMAC treats all input as AAD, thus the encryption
length is set to zero.

This also fixes padding for stream ciphers, so that payload will
be 4-byte aligned.


Revision tags: OPENBSD_4_8_BASE
# 1.111 20-Jul-2010 matthew

Switch some obvious network stack MAC comparisons from bcmp() to
timingsafe_bcmp().

ok deraadt@; committed over WPA.


# 1.110 09-Jul-2010 reyk

Add support for using IPsec in multiple rdomains.

This allows to run isakmpd/iked/ipsecctl in multiple rdomains
independently (with "route exec"); the kernel will pickup the rdomain
from the process context of the pfkey socket and load the flows and
SAs into the matching rdomain encap routing table. The network stack
also needs to pass the rdomain to the ipsec stack to lookup the
correct rdomain that belongs to an interface/mbuf/... You can now run
individual IPsec configs per rdomain or create IPsec VPNs between
multiple rdomains on the same machine ;). Note that a primary enc(4)
in addition to enc0 interface is required per rdomain, eg. enc1 rdomain 1.

Test by some people, mostly on existing "rdomain 0" setups. Was in
snaps for some days and people didn't complain.

ok claudio@ naddy@


# 1.109 02-Jul-2010 blambert

m_copyback can fail to allocate memory, but is a void fucntion so gymnastics
are required to detect that.

Change the function to take a wait argument (used in nfs server, but
M_NOWAIT everywhere else for now) and to return an error

ok claudio@ henning@ krw@


# 1.108 01-Jul-2010 reyk

Allow to specify an alternative enc(4) interface for an SA. All
traffic for this SA will appear on the specified enc interface instead
of enc0 and can be filtered and monitored separately. This will allow
to group individual ipsec policies to virtual interfaces and
simplifies monitoring and pf filtering with many ipsec policies a lot.

This diff includes the following changes:
- Store the enc interface unit (default 0) in the TDB of an SA and pass
it to the enc_getif() lookup when running the bpf or pf_test() handlers.
- Add the pfkey SADB_X_EXT_TAP extension to communicate the encX
interface unit for a specified SA between userland and kernel.
- Update enc(4) again to use an allocate array instead of the TAILQ to
lookup the matching enc interface in enc_getif() quickly.

Discussed with many, tested by a few, will need more testing & review.

ok deraadt@


# 1.107 29-Jun-2010 reyk

Replace enc(4) with a new implementation as a cloner device. We still
create enc0 by default, but it is possible to add additional enc
interfaces. This will be used later to allow alternative encs per
policy or to have an enc per rdomain when IPsec becomes rdomain-aware.

manpage bits ok jmc@
input from henning@ deraadt@ toby@ naddy@
ok henning@ claudio@


Revision tags: OPENBSD_4_7_BASE
# 1.106 10-Jan-2010 markus

Fix two bugs in IPsec/HMAC-SHA2:
(1) use correct (message) block size of 128 byte (instead of 64
bytes) for HMAC-SHA512/384 (RFC4634).
(2) RFC4868 specifies that HMAC-SHA-{256,384,512} is truncated to
nnn/2 bits, while we still use 96 bits. 96 bits have been
specified in draft-ietf-ipsec-ciph-sha-256-00 while
draft-ietf-ipsec-ciph-sha-256-01 changed it to 128 bits.

WARNING: this change makes IPsec with SHA-256 (the default)
incompatible with older OpenBSD versions and other IPsec-implementations
that share this bug.

ok+tests naddy, fries; requested by reyk/deraadt


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.105 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.104 19-Nov-2007 mpf

Remove the #define ENCDEBUG that slipped through somehow.
OK hshoexer@


# 1.103 17-Oct-2007 hshoexer

Convert MALLOC/FREE to malloc/free.

ok gilles@


# 1.102 06-Oct-2007 krw

Oops. Forgot to do FREE -> free when I did MALLOC -> malloc.


# 1.101 03-Oct-2007 krw

MALLOC+bzero -> malloc+M_ZERO.

In ip_esp.c all allocated memory is now zero'd in the
"malloc(sizeof(*tc) + alen ..." case. The +alen memory was not
initialized by the bzero() call. Noticed by chl@.

"Looks good" art@ "seems ok" chl@


Revision tags: OPENBSD_4_1_BASE OPENBSD_4_2_BASE
# 1.100 15-Dec-2006 otto

make enc(4) count; ok markus@ henning@ deraadt@


# 1.99 21-Sep-2006 otto

ugly trailing ws; from bret dot lambert at gmail


Revision tags: OPENBSD_4_0_BASE
# 1.98 28-May-2006 mcbride

Only preemptively increase the replay counter for outbound TDBs.

Another ipsec failover fix from nathanael at polymorpheus dot com.

ok hshoexer@


# 1.97 25-Mar-2006 djm

allow bpf(4) to ignore packets based on their direction (inbound or
outbound), using a new BIOCSDIRFILT ioctl;
guidance, feedback and ok canacar@


Revision tags: OPENBSD_3_9_BASE
# 1.96 20-Dec-2005 markus

use M_READONLY when trying to find out whether we have to copy
the mbuf before encryption. otherwise mbufs with M_EXT but w/o M_CLUSTER
get modified; ok hshoexer


Revision tags: OPENBSD_3_8_BASE
# 1.95 05-Aug-2005 markus

don't panic for SADB_ADD w/o enc/auth, with and ok hshoexer@


# 1.94 02-Aug-2005 djm

use arc4random for random packet padding (largely acedemic because it is
deprecated anyway); ok hshoexer@


# 1.93 31-Jul-2005 pascoe

Introduce bpf_mtap_af and bpf_mtap_hdr to be used when passing a mbuf chain
to bpf with either an address family or other header added.

These helpers only allocate a much smaller struct m_hdr on the stack when
needed, rather than leaving 256 byte struct mbufs on the stack in deep
call paths. Also removes a fair bit of duplicated code.

commit now, tune after deraadt@


# 1.92 28-May-2005 ho

Add SA replay counter synchronization to pfsync(4). Required for IPsec
failover gateways. ok mcbride@, "looks good" hshoexer@


# 1.91 27-May-2005 markus

comment out unused PACKET_TAG_IPSEC_IN_CRYPTO_DONE code; ok hshoexer


# 1.90 25-May-2005 markus

AESCTR support for ESP (RFC 3686); ok hshoexer


# 1.89 10-May-2005 markus

support NULL encryption for ESP; ok hshoexer, ho


Revision tags: OPENBSD_3_5_BASE OPENBSD_3_6_BASE OPENBSD_3_7_BASE SMP_SYNC_A SMP_SYNC_B
# 1.88 10-Dec-2003 itojun

de-register. deraadt ok


Revision tags: OPENBSD_3_4_BASE
# 1.87 14-Aug-2003 jason

m_copyback()'s 4th arg is const void *, nuke (caddr_t) casts.


# 1.86 24-Jul-2003 itojun

conform to RFC2367 on SADB_xx naming (local name must be prefixed with
SADB_X_xx)


# 1.85 24-Jul-2003 itojun

hmac-sha2-{256,384,512} support in AH/ESP auth. markus ok


# 1.84 09-Jul-2003 markus

fix whitespace


Revision tags: UBC_SYNC_A
# 1.83 03-May-2003 itojun

just as a safety measure, set m_flags to 0 for mbufs allocated on stack.
dhartmei ok


# 1.82 02-Apr-2003 millert

o sanity check mbuf earlier.
o return errno, not NULL.
o add some missing error values
o proper crypto_freereq() in ip_ipcomp.c
From Patrick Latifi; OK angelos@


# 1.81 31-Mar-2003 millert

Avoid using FREEd data when we get a crypto error; Patrick Latifi
Also move the session ID reset into the crp_etype == EAGAIN case
(noticed by angelos@). OK jason@ and angelos@


Revision tags: OPENBSD_3_3_BASE
# 1.80 28-Feb-2003 jason

Based on several comments from tedu:
- two variables 'err' and 'error', whacked
- missing initialization in the error path for the case where an SA expired
while off in crypto land.
- a small bit of knf.


# 1.79 21-Feb-2003 tedu

kill unused variables

ok jason@


# 1.78 12-Feb-2003 jason

Remove commons; inspired by netbsd.


# 1.77 01-Feb-2003 dhartmei

m_pad() is expected to have free'd the mbuf if it returns NULL, so
free it in one (rare) error condition. ok angelos@


# 1.76 07-Nov-2002 ho

Check for invalid payload lengths also for NULL enc. markus@, angelos@ ok.


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.75 30-Jul-2002 jason

branches: 1.75.2;
Be sure to check the integrity verifier for packets that didn't have it done
in hardware; from angelos


# 1.74 05-Jul-2002 angelos

Free crp_opaque only after we've determined we're not going to
re-submit it. From sam@errno.com


# 1.73 18-Jun-2002 angelos

KNF


# 1.72 18-Jun-2002 angelos

Initialize mo to NULL, for good measure -- sam@errno.com


# 1.71 18-Jun-2002 angelos

Same as with ip_ah.c (fix unreachable reference-after-free)


# 1.70 31-May-2002 angelos

Fix a DoS attack whereby an attacker could cause the replay counter to
advance with unauthenticated packets, thereby causing valid packets to
be discarded as replays. This has been sitting in my tree for a while,
and I've forgotten who it was that pointed out the problem.


Revision tags: OPENBSD_3_0_BASE OPENBSD_3_1_BASE UBC_BASE
# 1.69 26-Jun-2001 angelos

branches: 1.69.4; 1.69.6;
KNF


# 1.68 25-Jun-2001 angelos

Copyright.


# 1.67 23-Jun-2001 deraadt

merge crypto/crypto{dev,}.h to crypto/cryptodev.h, to avoid name conflicts inside OpenSSL codebase


# 1.66 13-Jun-2001 angelos

Use blocksize, not ivmask


# 1.65 08-Jun-2001 angelos

Trim include files.


# 1.64 05-Jun-2001 angelos

Add a few DPRINTF()'s


# 1.63 01-Jun-2001 angelos

The IPsec-aware NIC cards don't pass the ICV for later verification
by the stack; that means, if we have a tag it means the ICV was
successfully verified and we don't need to do anything else. As well,
we don't need any other status information from the NIC.


# 1.62 30-May-2001 angelos

Update to match prototypes.


# 1.61 30-May-2001 angelos

Handle TDBF_SKIPCRYPTO on output, and PACKET_TAG_IPSEC_IN_CRYPTO_DONE
on input.


# 1.60 27-May-2001 angelos

Pass a NULL packet tag for now to ipsp_common_input_cb().


# 1.59 17-May-2001 provos

convert mbuf and cluster allocation to pool, mostly from NetBSD
okay art@ miod@


# 1.58 13-May-2001 deraadt

initial cut at /dev/crypto support. takes original mbuf "try, and discard
if we fail" semantics and extends to two varients of data movement: mbuf,
or an iovec style block.


# 1.57 12-May-2001 angelos

Move bzero() after test for correct allocation (jj@wabbitt.org)


Revision tags: OPENBSD_2_9_BASE
# 1.56 14-Apr-2001 angelos

Minor changes, preparing for real socket-attached TDBs; also, more
information will be stored in the TDB. ok ho@ provos@


# 1.55 06-Apr-2001 csapuntz

Move offsetof define into sys/param.h


# 1.54 28-Mar-2001 angelos

Allow tdbi's to appear in mbufs throughout the stack; this allows
security properties of the packets to be pushed up to the application
(not done yet). Eventually, this will be turned into a packet
attributes framework.

Make sure tdbi's are free'd/cleared properly whenever drivers (or NFS)
does weird things with mbufs.


# 1.53 23-Mar-2001 angelos

Fix slow mbuf leak.


# 1.52 15-Mar-2001 mickey

convert SA expirations to the new timeouts.
simplifies expirations handling a lot.
tdb_exp_timeout and tdb_soft_timeout are made
consistant throughout the code to be a relative time offsets,
just like first_use timeouts.
tested on singlehost isakmpd setup.
lots of dangling spaces and tabs removed.
angelos@ ok


# 1.51 17-Nov-2000 angelos

*HMAC96->*HMAC


Revision tags: OPENBSD_2_8_BASE
# 1.50 09-Oct-2000 angelos

AES support.


# 1.49 19-Sep-2000 angelos

Lots and lots of changes.


# 1.48 18-Jun-2000 angelos

Use M_NOWAIT instead of M_DONTWAIT in MALLOC() (even though they're
defined to be the same in mbuf.h)


# 1.47 18-Jun-2000 angelos

The callbacks need to set the appropriate spl level now.


# 1.46 15-Jun-2000 angelos

What was the offending payload length?


# 1.45 14-Jun-2000 angelos

Initialize tc_ptr to zero if authentication is not used.


# 1.44 06-Jun-2000 angelos

Get rid of tdb_ref, keep indirect pointer to TDB.


# 1.43 01-Jun-2000 angelos

Check for invalid TDBs right away in the callbacks.


# 1.42 15-May-2000 angelos

Fix sanity check that caused really short packets (ICMPs with less
than 8 bytes of payload) to be dropped. Did not affect TCP/UDP packets
and most ICMP packets.


Revision tags: OPENBSD_2_7_BASE
# 1.41 25-Apr-2000 jason

when fixing up the header, copy from the right sized datatype (fixes IPsec
on big-endian machines)


# 1.40 06-Apr-2000 deraadt

only call get_random_bytes() once in m_pad()


# 1.39 30-Mar-2000 angelos

Only allocate space for a copy of the authenticator if authentication
is in use.


# 1.38 29-Mar-2000 angelos

Note to self: test before committing.


# 1.37 29-Mar-2000 angelos

Conform to crypto framework changes for IVs.


# 1.36 28-Mar-2000 angelos

Allow authentication-only ESP (must have broken it in the previous
round of commits).


# 1.35 25-Mar-2000 angelos

Fix typo causing crash if ESP was used with only authentication or
encryption (not both). Problem noted by jason@openbsd.org


# 1.34 21-Mar-2000 angelos

Fix casting so it compiles on alphas (testing by janjaap@stack.nl,
closing pr #1150)


# 1.33 17-Mar-2000 angelos

Cryptographic services framework, and software "device driver". The
idea is to support various cryptographic hardware accelerators (which
may be (detachable) cards, secondary/tertiary/etc processors,
software crypto, etc). Supports session migration between crypto
devices. What it doesn't (yet) support:
- multiple instances of the same algorithm used in the same session
- use of multiple crypto drivers in the same session
- asymmetric crypto

No support for a userland device yet.

IPsec code path modified to allow for asynchronous cryptography
(callbacks used in both input and output processing). Some unrelated
code simplification done in the process (especially for AH).

Development of this code kindly supported by Network Security
Technologies (NSTI). The code was writen mostly in Greece, and is
being committed from Montreal.


Revision tags: SMP_BASE
# 1.32 07-Feb-2000 itojun

branches: 1.32.2;
fix include file path related to ip6.


# 1.31 27-Jan-2000 angelos

Merge "old" and "new" ESP and AH in two files (one for each).
Fix a couple of buglets with ingress flow deletion.
tcpdump on enc0 should now show all outgoing packets *before* being
processed, and all incoming packets *after* being processed.

Good to be in Canada (land of the free commits).


# 1.30 09-Dec-1999 angelos

Ok, no more IPsec for OpenBSD...I've had enough with it.


# 1.29 09-Dec-1999 angelos

IPv6 support should now be complete (well, we need the right hooks in
ip6_input())


Revision tags: kame_19991208
# 1.28 07-Dec-1999 angelos

New ah_new_input(), protocol-independent processing (still lacking
IPv6-specific protocol header processing).


# 1.27 06-Dec-1999 angelos

New ESP code that's v4 and v6 friendly.


# 1.26 04-Nov-1999 ho

gettdb() should be at spltdb().


# 1.25 29-Oct-1999 angelos

Support multiple enc interfaces.


Revision tags: OPENBSD_2_6_BASE
# 1.24 05-Jul-1999 deraadt

remove bogus entry from if_enc address list; and rename enc_softc to encif


# 1.23 16-May-1999 niklas

spltdb introduced, protection for tdb lists and related structures, so
they won't disappear behind our back by an expiration. Cleanup expiration
logic too.


# 1.22 14-May-1999 niklas

A new scalable IPsec SA expiration model.


Revision tags: OPENBSD_2_5_BASE
# 1.21 11-Apr-1999 niklas

Introduce net.inet.{ah,esp}.enable sysctl controls that are off by default.
If you are going to use either of AH or ESP or both, enable these in
/etc/sysctl.conf. Also correct the IPSec debugging sysctl code, it is now
named net.inet.ip.encdebug. Some corrected function signatures too.


# 1.20 09-Apr-1999 niklas

Make the tdbi handling more robust, removes a panic case


# 1.19 27-Mar-1999 provos

add SADB_X_BINDSA to pfkey allowing incoming SAs to refer to an outgoing
SA to be used, use this SA in ip_output if available. allow mobile road
warriors for bind SAs with wildcard dst and src addresses. check IPSEC
AUTH and ESP level when receiving packets, drop them if protection is
insufficient. add stats to show dropped packets because of insufficient
IPSEC protection. -- phew. this was all done in canada. dugsong and linh
provided the ride and company.


# 1.18 24-Feb-1999 angelos

Update copyright; remove a few annoying debugging printfs.

Btw, OpenBSD hit 25000 commits a couple commits ago.


# 1.17 24-Feb-1999 angelos

Remove encap.h include; saner debugging printfs; fix buglets; work with
pfkeyv2.


Revision tags: OPENBSD_2_4_BASE
# 1.16 10-Jun-1998 provos

make the packets which were successfully processed by IPSec available to
bpf via the enc0 interface, using linktype DLT_ENC.


# 1.15 24-May-1998 provos

avoid source address spoofing for mutual hostile hosts which have SAs to
us, reported by Craig Metz <cmetz@inner.net>.


# 1.14 18-May-1998 provos

first step to the setsockopt/getsockopt interface as described in
draft-mcdonald-simple-ipsec-api, kernel notifies (EMT_REQUESTSA) signal
userland key management applications when security services are requested.
this is only for outgoing connections at the moment, incoming packets
are not yet checked against the selected socket policy.


Revision tags: OPENBSD_2_3_BASE
# 1.13 04-Nov-1997 provos

make it easier to add additional transforms. add blowfish and cast
encryption. some more info for kernfs/ipsec.


Revision tags: OPENBSD_2_2_BASE
# 1.12 02-Oct-1997 deraadt

conditional error logging


# 1.11 28-Sep-1997 deraadt

log() needs a \n


# 1.10 27-Jul-1997 niklas

expiration messages, fixes, updates, all sorts of things


# 1.9 18-Jul-1997 provos

enablespi/disablespi in encap + print spi's in hostorder


# 1.8 11-Jul-1997 provos

put old esp/ah and new esp/ah in different files.
generalised way of handling transforms.


# 1.7 01-Jul-1997 provos

major restructuring


# 1.6 25-Jun-1997 provos

hard and soft limits for SPI's per absolute timer, relative since establish,
relative since first use timers, packet and byte counters. notify key mgmt
on soft limits. key mgmt can now specify limits. new encap messages:
EMT_RESERVESPI, EMT_ENABLESPI, EMT_DISABLESPI


# 1.5 21-Jun-1997 deraadt

u_int32_t changes, need testing


# 1.4 20-Jun-1997 provos

ah-sha1 + esp-3des + indentation


Revision tags: OPENBSD_2_1_BASE
# 1.3 26-Feb-1997 deraadt

count input/output packets for esp


# 1.2 24-Feb-1997 niklas

OpenBSD tags + some prototyping police


# 1.1 20-Feb-1997 deraadt

IPSEC package by John Ioannidis and Angelos D. Keromytis. Written in
Greece. From ftp.funet.fi:/pub/unix/security/net/ip/BSDipsec.tar.gz