Commit Graph

473 Commits

Author SHA1 Message Date
Robert Wing
91d388119a tcpmd5: return ENOENT when security association not found
Return ENOENT from tcp_ipsec_input() when a security association is not
found. This allows callers of TCP_MD5_INPUT() to differentiate between a
security association not found and receiving a bad signature.

Also return ENOENT from tcp_ipsec_output() for consistency.

Reviewed by:	ae
Sponsored by:   nepustil.net
Sponsored by:   Klara Inc.
Differential Revision:	https://reviews.freebsd.org/D33226
2022-01-08 16:31:17 -09:00
Gleb Smirnoff
9880323a99 netipsec: use SYSINIT(9) instead of dom_init/dom_destroy
While here, use just static initializer for key_cb.

Differential revision:	https://reviews.freebsd.org/D33539
2022-01-03 10:15:21 -08:00
Gleb Smirnoff
89128ff3e4 protocols: init with standard SYSINIT(9) or VNET_SYSINIT
The historical BSD network stack loop that rolls over domains and
over protocols has no advantages over more modern SYSINIT(9).
While doing the sweep, split global and per-VNET initializers.

Getting rid of pr_init allows to achieve several things:
o Get rid of ifdef's that protect against double foo_init() when
  both INET and INET6 are compiled in.
o Isolate initializers statically to the module they init.
o Makes code easier to understand and maintain.

Reviewed by:		melifaro
Differential revision:	https://reviews.freebsd.org/D33537
2022-01-03 10:15:21 -08:00
John Baldwin
246982c196 crypto: Consistently use AES instead of Rijndael128 for the AES-CBC cipher.
Reviewed by:	markj
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D33486
2021-12-16 13:47:27 -08:00
Wenfeng Liu
509f1a0f40 ipsec: fix a logic error in key_do_getnewspi 2021-12-14 19:30:42 +00:00
Robert Wing
fc21aafe5f ipsec: fix a panic with INVARIANTS
When adding an SPD entry that already exists, a refcount wraparound
panic is encountered. This was caused from dropping a reference on the
wrong security policy.

Fixes:          4920e38fec ("ipsec: fix race condition in key.c")
Reviewed by:	wma
Sponsored by:   Klara Inc.
Differential Revision:	https://reviews.freebsd.org/D33100
2021-12-03 14:22:23 -09:00
Mark Johnston
44775b163b netinet: Remove unneeded mb_unmapped_to_ext() calls
in_cksum_skip() now handles unmapped mbufs on platforms where they're
permitted.

Reviewed by:	glebius, jhb
MFC after:	1 week
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D33097
2021-11-24 13:31:16 -05:00
Mark Johnston
756bb50b6a sctp: Remove now-unneeded mb_unmapped_to_ext() calls
sctp_delayed_checksum() now handles unmapped mbufs, thanks to m_apply().

No functional change intended.

Reviewed by:	tuexen
MFC after:	2 weeks
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D32942
2021-11-16 13:38:09 -05:00
Mateusz Guzik
84c048822e ipsec: make sure the lock allocated in key_newsav does not false-share
Reviewed by:	ae
Sponsored by:	Rubicon Communications, LLC ("Netgate")
Differential Revision:	https://reviews.freebsd.org/D32828
2021-11-14 20:17:35 +00:00
Mateusz Guzik
e469b16d0b ipsec: fix edge case detection in key_getnewspid
Same comparison problem as in key_do_getnewspi.

Reviewed by:	ae
Sponsored by:	Rubicon Communications, LLC ("Netgate")
Differential Revision:	https://reviews.freebsd.org/D32827
2021-11-14 20:17:34 +00:00
Mateusz Guzik
10ea195fa2 ipsec: add a lock encompassing SPI allocation
SPIs get allocated and inserted in separate steps. Prior to the change
there was nothing preventing 2 differnet threads from ending up with the
same one.

PR:		258849
Reported by:	Herbie.Robinson@stratus.com
Reviewed by:	ae
Sponsored by:	Rubicon Communications, LLC ("Netgate")
Differential Revision:	https://reviews.freebsd.org/D32826
2021-11-03 19:51:40 +00:00
Mateusz Guzik
626bd0970a ipsec: fix edge case detection in key_do_getnewspi
The 'count' variable would end up being -1 post loop, while the
following condition would check for 0 instead.

PR:		258849
Reported by:	Herbie.Robinson@stratus.com
Reviewed by:	ae
Sponsored by:	Rubicon Communications, LLC ("Netgate")
Differential Revision:	https://reviews.freebsd.org/D32826
2021-11-03 19:51:40 +00:00
Wojciech Macek
8deba29c0a ipsec: fix typo part2 2021-09-27 07:46:56 +02:00
Wojciech Macek
c27214f0af ipsec: fix typo in comment 2021-09-27 07:45:33 +02:00
Bartlomiej Grzesik
9dfc8606eb ipsec: Add support for PMTUD for IPv6 tunnels
Discard and send ICMPv6 Packet Too Big to sender when we try to encapsulate
and forward a packet which total length exceeds the PMTU.
Logic is based on the IPv4 implementation.
Common code was moved to a separate function.

Differential revision:	https://reviews.freebsd.org/D31771
Obtained from:		Semihalf
Sponsored by:		Stormshield
2021-09-24 10:27:21 +02:00
Bartlomiej Grzesik
b4220bf387 ipsec: If no PMTU in hostcache assume it's equal to link's MTU
If we fail to find to PMTU in hostcache, we assume it's equal
to link's MTU.

This patch prevents packets larger then link's MTU to be dropped
silently if there is no PMTU in hostcache.

Differential revision:	https://reviews.freebsd.org/D31770
Obtained from:		Semihalf
Sponsored by:		Stormshield
2021-09-24 10:25:53 +02:00
Bartlomiej Grzesik
4f3376951d ipsec: Add PMTUD support for IPsec IPv4 over IPv6 tunnel
Add support for checking PMTU for IPv4 packets encapsulated in IPv6 tunnels.

Differential revision:	https://reviews.freebsd.org/D31769
Sponsored by:		Stormshield
Obtained from:		Semihalf
2021-09-24 10:17:11 +02:00
Mateusz Guzik
590d0715b3 ipsec: enter epoch before calling into ipsec_run_hhooks
pfil_run_hooks which eventually can get called asserts on it.

Reviewed by:	ae
Sponsored by:	Rubicon Communications, LLC ("Netgate")
Differential Revision: https://reviews.freebsd.org/D32007
2021-09-21 17:02:41 +00:00
Mark Johnston
10eb2a2bde ipsec: Validate the protocol identifier in ipsec4_ctlinput()
key_allocsa() expects to handle only IPSec protocols and has an
assertion to this effect.  However, ipsec4_ctlinput() has to handle
messages from ICMP unreachable packets and was not validating the
protocol number.  In practice such a packet would simply fail to match
any SADB entries and would thus be ignored.

Reported by:	syzbot+6a9ef6fcfadb9f3877fe@syzkaller.appspotmail.com
Reviewed by:	ae
MFC after:	1 week
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D31890
2021-09-10 09:09:00 -04:00
Wojciech Macek
4920e38fec ipsec: fix race condition in key.c
Small patch that fixes a race condition in sys/netipsec/key.c

Obtained from:		Stormshield
Differential revision:	https://reviews.freebsd.org/D31271
2021-08-13 12:52:38 +02:00
Kornel Duleba
a16771de4c ipsec: Return error code if no matching SA was found
If we matched SP to a packet, but no associated SA was found
ipsec4_allocsa will return NULL while setting error=0.
This resulted in use after free and potential kernel panic.
Return EINPROGRESS if the case described above instead.

Obtained from:		Semihalf
Sponsored by:		Stormshield
Differential revision:	https://reviews.freebsd.org/D30994
2021-08-13 09:35:08 +02:00
Kornel Duleba
6b66194bcb ipsec: Check PMTU before sending a frame.
If an encapsulated frame is going to have DF bit set check its desitnitions'
PMTU and if it won't fit drop it and:

Generate ICMP 3/4 message if the packet was to be forwarded.
Return EMSGSIZE error otherwise.

Obtained from:		Semihalf
Sponsored by:		Stormshield
Differential revision:	https://reviews.freebsd.org/D30993
2021-08-13 09:22:24 +02:00
Konstantin Belousov
8b000bf5bc netipsec/key.c: Use ANSI C definition for key_random()
Sponsored by:	NVIDIA Networking
MFC after:	3 days
2021-08-10 03:46:24 +03:00
Konstantin Belousov
fd4751b389 netipsec/keydb.h: fix typo
Sponsored by:	NVIDIA Networking
MFC after:	3 days
2021-08-10 03:45:36 +03:00
Wojciech Macek
d9d59bb1af ipsec: Handle ICMP NEEDFRAG message.
It will be needed for upcoming PMTU implementation in ipsec.
    For now simply create/update an entry in tcp hostcache when needed.
    The code is based on https://people.freebsd.org/~ae/ipsec_transport_mode_ctlinput.diff

Authored by: 		Kornel Duleba <mindal@semihalf.com>
Differential revision: 	https://reviews.freebsd.org/D30992
Reviewed by: 		tuxen
Sponsored by: 		Stormshield
Obtained from:	 	Semihalf
2021-08-09 12:01:46 +02:00
Roy Marples
7045b1603b socket: Implement SO_RERROR
SO_RERROR indicates that receive buffer overflows should be handled as
errors. Historically receive buffer overflows have been ignored and
programs could not tell if they missed messages or messages had been
truncated because of overflows. Since programs historically do not
expect to get receive overflow errors, this behavior is not the
default.

This is really really important for programs that use route(4) to keep
in sync with the system. If we loose a message then we need to reload
the full system state, otherwise the behaviour from that point is
undefined and can lead to chasing bogus bug reports.

Reviewed by:	philip (network), kbowling (transport), gbe (manpages)
MFC after:	2 weeks
Differential Revision:	https://reviews.freebsd.org/D26652
2021-07-28 09:35:09 -07:00
Mateusz Guzik
e0893890eb ipsec: globalize lft zone and zero out buffers at allocation time
Creation of a zone is expensive and there is no need to have one for
every vnet. Moreover, this wastes memory as these separate zones
cannot use the same per-cpu caches. Finally, this is a step towards
replacing the custom zone with pcpu-16.

Two counter_u64_zero calls induce back-to-back IPIs to zero everything
out. Instead, pass the M_ZERO flag to let uma just iterate all buffers.
The counter(9) API abstraction is already violated by not using
counter_u64_alloc.

Reviewed by:	ae
Sponsored by:	Rubicon Communications, LLC ("Netgate")
Differential Revision:	https://reviews.freebsd.org/D30916
2021-06-28 08:14:26 +00:00
Mark Johnston
f161d294b9 Add missing sockaddr length and family validation to various protocols
Several protocol methods take a sockaddr as input.  In some cases the
sockaddr lengths were not being validated, or were validated after some
out-of-bounds accesses could occur.  Add requisite checking to various
protocol entry points, and convert some existing checks to assertions
where appropriate.

Reported by:	syzkaller+KASAN
Reviewed by:	tuexen, melifaro
MFC after:	2 weeks
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D29519
2021-05-03 13:35:19 -04:00
Alexander V. Chernikov
924d1c9a05 Revert "SO_RERROR indicates that receive buffer overflows should be handled as errors."
Wrong version of the change was pushed inadvertenly.

This reverts commit 4a01b854ca.
2021-02-08 22:32:32 +00:00
Alexander V. Chernikov
4a01b854ca SO_RERROR indicates that receive buffer overflows should be handled as errors.
Historically receive buffer overflows have been ignored and programs
could not tell if they missed messages or messages had been truncated
because of overflows. Since programs historically do not expect to get
receive overflow errors, this behavior is not the default.

This is really really important for programs that use route(4) to keep in sync
with the system. If we loose a message then we need to reload the full system
state, otherwise the behaviour from that point is undefined and can lead
to chasing bogus bug reports.
2021-02-08 21:42:20 +00:00
Mark Johnston
68f6800ce0 opencrypto: Introduce crypto_dispatch_async()
Currently, OpenCrypto consumers can request asynchronous dispatch by
setting a flag in the cryptop.  (Currently only IPSec may do this.)   I
think this is a bit confusing: we (conditionally) set cryptop flags to
request async dispatch, and then crypto_dispatch() immediately examines
those flags to see if the consumer wants async dispatch. The flag names
are also confusing since they don't specify what "async" applies to:
dispatch or completion.

Add a new KPI, crypto_dispatch_async(), rather than encoding the
requested dispatch type in each cryptop. crypto_dispatch_async() falls
back to crypto_dispatch() if the session's driver provides asynchronous
dispatch. Get rid of CRYPTOP_ASYNC() and CRYPTOP_ASYNC_KEEPORDER().

Similarly, add crypto_dispatch_batch() to request processing of a tailq
of cryptops, rather than encoding the scheduling policy using cryptop
flags.  Convert GELI, the only user of this interface (disabled by
default) to use the new interface.

Add CRYPTO_SESS_SYNC(), which can be used by consumers to determine
whether crypto requests will be dispatched synchronously. This is just
a helper macro. Use it instead of looking at cap flags directly.

Fix style in crypto_done(). Also get rid of CRYPTO_RETW_EMPTY() and
just check the relevant queues directly. This could result in some
unnecessary wakeups but I think it's very uncommon to be using more than
one queue per worker in a given workload, so checking all three queues
is a waste of cycles.

Reviewed by:	jhb
Sponsored by:	Ampere Computing
Submitted by:	Klara, Inc.
MFC after:	2 weeks
Differential Revision:	https://reviews.freebsd.org/D28194
2021-02-08 09:19:19 -05:00
John Baldwin
8e9313caa6 Convert unmapped mbufs before computing checksums in IPsec.
This is similar to the logic used in ip_output() to convert mbufs
prior to computing checksums.  Unmapped mbufs can be sent when using
sendfile() over IPsec or using KTLS over IPsec.

Reported by:	Sony Arpita Das @ Chelsio QA
Reviewed by:	np
Sponsored by:	Chelsio
Differential Revision:	https://reviews.freebsd.org/D28187
2021-01-19 11:52:00 -08:00
Marcin Wojtas
ac152c14e0 Trigger soft lifetime expiration on sequence number
This patch adds 80% of UINT32_MAX limit on sequence number.
When sequence number reaches limit kernel sends SADB_EXPIRE message to
IKE daemon which is responsible to perform rekeying.

Submitted by:           Patryk Duda <pdk@semihalf.com>
Reviewed by:            ae
Differential revision:  https://reviews.freebsd.org/D22370
Obtained from:          Semihalf
Sponsored by:           Stormshield
2020-10-16 11:27:01 +00:00
Marcin Wojtas
4d36d1fd59 Add support for IPsec ESN and pass relevant information to crypto layer
Implement support for including IPsec ESN (Extended Sequence Number) to
both encrypt and authenticate mode (eg. AES-CBC and SHA256) and combined
mode (eg. AES-GCM). Both ESP and AH protocols are updated. Additionally
pass relevant information about ESN to crypto layer.

For the ETA mode the ESN is stored in separate crp_esn buffer because
the high-order 32 bits of the sequence number are appended after the
Next Header (RFC 4303).

For the AEAD modes the high-order 32 bits of the sequence number
[e.g.  RFC 4106, Chapter 5 AAD Construction] are included as part of
crp_aad (SPI + ESN (32 high order bits) + Seq nr (32 low order bits)).

Submitted by:           Grzegorz Jaszczyk <jaz@semihalf.com>
                        Patryk Duda <pdk@semihalf.com>
Reviewed by:            jhb, gnn
Differential revision:  https://reviews.freebsd.org/D22369
Obtained from:          Semihalf
Sponsored by:           Stormshield
2020-10-16 11:25:45 +00:00
Marcin Wojtas
8b7f39947c Implement anti-replay algorithm with ESN support
As RFC 4304 describes there is anti-replay algorithm responsibility
to provide appropriate value of Extended Sequence Number.

This patch introduces anti-replay algorithm with ESN support based on
RFC 4304, however to avoid performance regressions window implementation
was based on RFC 6479, which was already implemented in FreeBSD.

To keep things clean and improve code readability, implementation of window
is kept in seperate functions.

Submitted by:           Grzegorz Jaszczyk <jaz@semihalf.com>
                        Patryk Duda <pdk@semihalf.com>
Reviewed by:            jhb
Differential revision:  https://reviews.freebsd.org/D22367
Obtained from:          Semihalf
Sponsored by:           Stormshield
2020-10-16 11:24:12 +00:00
Mateusz Guzik
662c13053f net: clean up empty lines in .c and .h files 2020-09-01 21:19:14 +00:00
John Baldwin
dae61c9d09 Simplify IPsec transform-specific teardown.
- Rename from the teardown callback from 'zeroize' to 'cleanup' since
  this no longer zeroes keys.

- Change the callback return type to void.  Nothing checked the return
  value and it was always zero.

- Don't have esp call into ah since it no longer needs to depend on
  this to clear the auth key.  Instead, both are now private and
  self-contained.

Reviewed by:	delphij
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D25443
2020-06-25 23:59:16 +00:00
John Baldwin
f82eb2a6f0 Enter and exit the network epoch for async IPsec callbacks.
When an IPsec packet has been encrypted or decrypted, the next step in
the packet's traversal through the network stack is invoked from a
crypto worker thread, not from the original calling thread.  These
threads need to enter the network epoch before passing packets down to
IP output routines or up to transport protocols.

Reviewed by:	ae
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D25444
2020-06-25 23:57:30 +00:00
John Baldwin
20869b25cc Use zfree() to explicitly zero IPsec keys.
Reviewed by:	delphij
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D25442
2020-06-25 20:31:06 +00:00
Mark Johnston
95033af923 Add the SCTP_SUPPORT kernel option.
This is in preparation for enabling a loadable SCTP stack.  Analogous to
IPSEC/IPSEC_SUPPORT, the SCTP_SUPPORT kernel option must be configured
in order to support a loadable SCTP implementation.

Discussed with:	tuexen
MFC after:	2 weeks
Sponsored by:	The FreeBSD Foundation
2020-06-18 19:32:34 +00:00
John Baldwin
28d2a72bbf Consistently include opt_ipsec.h for consumers of <netipsec/ipsec.h>.
This fixes ipsec.ko to include all of IPSEC_DEBUG.

Reviewed by:	imp
MFC after:	2 weeks
Sponsored by:	Netflix
Differential Revision:	https://reviews.freebsd.org/D25046
2020-05-29 19:22:40 +00:00
Marcin Wojtas
b01edfb515 Fix AES-CTR compatibility issue in ipsec
r361390 decreased blocksize of AES-CTR from 16 to 1.
Because of that ESP payload is no longer aligned to 16 bytes
before being encrypted and sent.
This is a good change since RFC3686 specifies that the last block
doesn't need to be aligned.
Since FreeBSD before r361390 couldn't decrypt partial blocks encrypted
with AES-CTR we need to enforce 16 byte alignment in order to preserve
compatibility.
Add a sysctl(on by default) to control it.

Submitted by: Kornel Duleba <mindal@semihalf.com>
Reviewed by: jhb
Obtained from: Semihalf
Sponsored by: Stormshield
Differential Revision: https://reviews.freebsd.org/D24999
2020-05-26 14:16:26 +00:00
John Baldwin
9c0e3d3a53 Add support for optional separate output buffers to in-kernel crypto.
Some crypto consumers such as GELI and KTLS for file-backed sendfile
need to store their output in a separate buffer from the input.
Currently these consumers copy the contents of the input buffer into
the output buffer and queue an in-place crypto operation on the output
buffer.  Using a separate output buffer avoids this copy.

- Create a new 'struct crypto_buffer' describing a crypto buffer
  containing a type and type-specific fields.  crp_ilen is gone,
  instead buffers that use a flat kernel buffer have a cb_buf_len
  field for their length.  The length of other buffer types is
  inferred from the backing store (e.g. uio_resid for a uio).
  Requests now have two such structures: crp_buf for the input buffer,
  and crp_obuf for the output buffer.

- Consumers now use helper functions (crypto_use_*,
  e.g. crypto_use_mbuf()) to configure the input buffer.  If an output
  buffer is not configured, the request still modifies the input
  buffer in-place.  A consumer uses a second set of helper functions
  (crypto_use_output_*) to configure an output buffer.

- Consumers must request support for separate output buffers when
  creating a crypto session via the CSP_F_SEPARATE_OUTPUT flag and are
  only permitted to queue a request with a separate output buffer on
  sessions with this flag set.  Existing drivers already reject
  sessions with unknown flags, so this permits drivers to be modified
  to support this extension without requiring all drivers to change.

- Several data-related functions now have matching versions that
  operate on an explicit buffer (e.g. crypto_apply_buf,
  crypto_contiguous_subsegment_buf, bus_dma_load_crp_buf).

- Most of the existing data-related functions operate on the input
  buffer.  However crypto_copyback always writes to the output buffer
  if a request uses a separate output buffer.

- For the regions in input/output buffers, the following conventions
  are followed:
  - AAD and IV are always present in input only and their
    fields are offsets into the input buffer.
  - payload is always present in both buffers.  If a request uses a
    separate output buffer, it must set a new crp_payload_start_output
    field to the offset of the payload in the output buffer.
  - digest is in the input buffer for verify operations, and in the
    output buffer for compute operations.  crp_digest_start is relative
    to the appropriate buffer.

- Add a crypto buffer cursor abstraction.  This is a more general form
  of some bits in the cryptosoft driver that tried to always use uio's.
  However, compared to the original code, this avoids rewalking the uio
  iovec array for requests with multiple vectors.  It also avoids
  allocate an iovec array for mbufs and populating it by instead walking
  the mbuf chain directly.

- Update the cryptosoft(4) driver to support separate output buffers
  making use of the cursor abstraction.

Sponsored by:	Netflix
Differential Revision:	https://reviews.freebsd.org/D24545
2020-05-25 22:12:04 +00:00
John Baldwin
897e43124e Don't pass bogus keys down for NULL algorithms.
The changes in r359374 added various sanity checks in sessions and
requests created by crypto consumers in part to permit backend drivers
to make assumptions instead of duplicating checks for various edge
cases.  One of the new checks was to reject sessions which provide a
pointer to a key while claiming the key is zero bits long.

IPsec ESP tripped over this as it passes along whatever key is
provided for NULL, including a pointer to a zero-length key when an
empty string ("") is used with setkey(8).  One option would be to
teach the IPsec key layer to not allocate keys of zero length, but I
went with a simpler fix of just not passing any keys down and always
using a key length of zero for NULL algorithms.

PR:		245832
Reported by:	CI
2020-05-02 01:00:29 +00:00
John Baldwin
16aabb761c Remove support for IPsec algorithms deprecated in r348205 and r360202.
Examples of depecrated algorithms in manual pages and sample configs
are updated where relevant.  I removed the one example of combining
ESP and AH (vs using a cipher and auth in ESP) as RFC 8221 says this
combination is NOT RECOMMENDED.

Specifically, this removes support for the following ciphers:
- des-cbc
- 3des-cbc
- blowfish-cbc
- cast128-cbc
- des-deriv
- des-32iv
- camellia-cbc

This also removes support for the following authentication algorithms:
- hmac-md5
- keyed-md5
- keyed-sha1
- hmac-ripemd160

Reviewed by:	cem, gnn (older verisons)
Relnotes:	yes
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D24342
2020-05-02 00:06:58 +00:00
John Baldwin
69a3eb6223 Fix name of 3DES cipher in deprecation warning.
Submitted by:	cem
MFC after:	1 week
2020-04-22 21:03:24 +00:00
John Baldwin
e27a9ad8e6 Deprecate 3des support in IPsec for FreeBSD 13.
RFC 8221 does not outright ban 3des as the algorithms deprecated for
13 in r348205, but it is listed as a SHOULD NOT and will likely be a
MUST NOT by the time 13 ships.

Discussed with:	bjk
MFC after:	1 week
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D24341
2020-04-22 19:44:33 +00:00
John Baldwin
c161c46d4c Update comments about IVs used in IPsec ESP.
Add some prose and a diagram describing the layout of the cipher IV
for AES-CTR and AES-GCM and how it relates to the ESP IV stored in the
packet after the ESP header.  Also, remove an XXX comment about the
initial block counter value used for AES-CTR in esp_output as the
current code matches the RFC (and the equivalent code in esp_input
didn't have the XXX comment).

Discussed with:	cem
2020-04-20 22:57:15 +00:00
John Baldwin
8cbde41419 Generate IVs directly in esp_output.
This is the only place that uses CRYPTO_F_IV_GENERATE.  All crypto
drivers currently duplicate the same boilerplate code to handle this
case.  Doing the generation directly removes complexity from drivers.
It also simplifies support for separate input and output buffers.

Reviewed by:	cem
Sponsored by:	Netflix
Differential Revision:	https://reviews.freebsd.org/D24449
2020-04-20 22:20:26 +00:00
John Baldwin
c034143269 Refactor driver and consumer interfaces for OCF (in-kernel crypto).
- The linked list of cryptoini structures used in session
  initialization is replaced with a new flat structure: struct
  crypto_session_params.  This session includes a new mode to define
  how the other fields should be interpreted.  Available modes
  include:

  - COMPRESS (for compression/decompression)
  - CIPHER (for simply encryption/decryption)
  - DIGEST (computing and verifying digests)
  - AEAD (combined auth and encryption such as AES-GCM and AES-CCM)
  - ETA (combined auth and encryption using encrypt-then-authenticate)

  Additional modes could be added in the future (e.g. if we wanted to
  support TLS MtE for AES-CBC in the kernel we could add a new mode
  for that.  TLS modes might also affect how AAD is interpreted, etc.)

  The flat structure also includes the key lengths and algorithms as
  before.  However, code doesn't have to walk the linked list and
  switch on the algorithm to determine which key is the auth key vs
  encryption key.  The 'csp_auth_*' fields are always used for auth
  keys and settings and 'csp_cipher_*' for cipher.  (Compression
  algorithms are stored in csp_cipher_alg.)

- Drivers no longer register a list of supported algorithms.  This
  doesn't quite work when you factor in modes (e.g. a driver might
  support both AES-CBC and SHA2-256-HMAC separately but not combined
  for ETA).  Instead, a new 'crypto_probesession' method has been
  added to the kobj interface for symmteric crypto drivers.  This
  method returns a negative value on success (similar to how
  device_probe works) and the crypto framework uses this value to pick
  the "best" driver.  There are three constants for hardware
  (e.g. ccr), accelerated software (e.g. aesni), and plain software
  (cryptosoft) that give preference in that order.  One effect of this
  is that if you request only hardware when creating a new session,
  you will no longer get a session using accelerated software.
  Another effect is that the default setting to disallow software
  crypto via /dev/crypto now disables accelerated software.

  Once a driver is chosen, 'crypto_newsession' is invoked as before.

- Crypto operations are now solely described by the flat 'cryptop'
  structure.  The linked list of descriptors has been removed.

  A separate enum has been added to describe the type of data buffer
  in use instead of using CRYPTO_F_* flags to make it easier to add
  more types in the future if needed (e.g. wired userspace buffers for
  zero-copy).  It will also make it easier to re-introduce separate
  input and output buffers (in-kernel TLS would benefit from this).

  Try to make the flags related to IV handling less insane:

  - CRYPTO_F_IV_SEPARATE means that the IV is stored in the 'crp_iv'
    member of the operation structure.  If this flag is not set, the
    IV is stored in the data buffer at the 'crp_iv_start' offset.

  - CRYPTO_F_IV_GENERATE means that a random IV should be generated
    and stored into the data buffer.  This cannot be used with
    CRYPTO_F_IV_SEPARATE.

  If a consumer wants to deal with explicit vs implicit IVs, etc. it
  can always generate the IV however it needs and store partial IVs in
  the buffer and the full IV/nonce in crp_iv and set
  CRYPTO_F_IV_SEPARATE.

  The layout of the buffer is now described via fields in cryptop.
  crp_aad_start and crp_aad_length define the boundaries of any AAD.
  Previously with GCM and CCM you defined an auth crd with this range,
  but for ETA your auth crd had to span both the AAD and plaintext
  (and they had to be adjacent).

  crp_payload_start and crp_payload_length define the boundaries of
  the plaintext/ciphertext.  Modes that only do a single operation
  (COMPRESS, CIPHER, DIGEST) should only use this region and leave the
  AAD region empty.

  If a digest is present (or should be generated), it's starting
  location is marked by crp_digest_start.

  Instead of using the CRD_F_ENCRYPT flag to determine the direction
  of the operation, cryptop now includes an 'op' field defining the
  operation to perform.  For digests I've added a new VERIFY digest
  mode which assumes a digest is present in the input and fails the
  request with EBADMSG if it doesn't match the internally-computed
  digest.  GCM and CCM already assumed this, and the new AEAD mode
  requires this for decryption.  The new ETA mode now also requires
  this for decryption, so IPsec and GELI no longer do their own
  authentication verification.  Simple DIGEST operations can also do
  this, though there are no in-tree consumers.

  To eventually support some refcounting to close races, the session
  cookie is now passed to crypto_getop() and clients should no longer
  set crp_sesssion directly.

- Assymteric crypto operation structures should be allocated via
  crypto_getkreq() and freed via crypto_freekreq().  This permits the
  crypto layer to track open asym requests and close races with a
  driver trying to unregister while asym requests are in flight.

- crypto_copyback, crypto_copydata, crypto_apply, and
  crypto_contiguous_subsegment now accept the 'crp' object as the
  first parameter instead of individual members.  This makes it easier
  to deal with different buffer types in the future as well as
  separate input and output buffers.  It's also simpler for driver
  writers to use.

- bus_dmamap_load_crp() loads a DMA mapping for a crypto buffer.
  This understands the various types of buffers so that drivers that
  use DMA do not have to be aware of different buffer types.

- Helper routines now exist to build an auth context for HMAC IPAD
  and OPAD.  This reduces some duplicated work among drivers.

- Key buffers are now treated as const throughout the framework and in
  device drivers.  However, session key buffers provided when a session
  is created are expected to remain alive for the duration of the
  session.

- GCM and CCM sessions now only specify a cipher algorithm and a cipher
  key.  The redundant auth information is not needed or used.

- For cryptosoft, split up the code a bit such that the 'process'
  callback now invokes a function pointer in the session.  This
  function pointer is set based on the mode (in effect) though it
  simplifies a few edge cases that would otherwise be in the switch in
  'process'.

  It does split up GCM vs CCM which I think is more readable even if there
  is some duplication.

- I changed /dev/crypto to support GMAC requests using CRYPTO_AES_NIST_GMAC
  as an auth algorithm and updated cryptocheck to work with it.

- Combined cipher and auth sessions via /dev/crypto now always use ETA
  mode.  The COP_F_CIPHER_FIRST flag is now a no-op that is ignored.
  This was actually documented as being true in crypto(4) before, but
  the code had not implemented this before I added the CIPHER_FIRST
  flag.

- I have not yet updated /dev/crypto to be aware of explicit modes for
  sessions.  I will probably do that at some point in the future as well
  as teach it about IV/nonce and tag lengths for AEAD so we can support
  all of the NIST KAT tests for GCM and CCM.

- I've split up the exising crypto.9 manpage into several pages
  of which many are written from scratch.

- I have converted all drivers and consumers in the tree and verified
  that they compile, but I have not tested all of them.  I have tested
  the following drivers:

  - cryptosoft
  - aesni (AES only)
  - blake2
  - ccr

  and the following consumers:

  - cryptodev
  - IPsec
  - ktls_ocf
  - GELI (lightly)

  I have not tested the following:

  - ccp
  - aesni with sha
  - hifn
  - kgssapi_krb5
  - ubsec
  - padlock
  - safe
  - armv8_crypto (aarch64)
  - glxsb (i386)
  - sec (ppc)
  - cesa (armv7)
  - cryptocteon (mips64)
  - nlmsec (mips64)

Discussed with:	cem
Relnotes:	yes
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D23677
2020-03-27 18:25:23 +00:00