Commit graph

353 commits

Author SHA1 Message Date
Jung-uk Kim c3c73b4f0a Merge OpenSSL 1.1.1i. 2020-12-09 02:05:14 +00:00
Conrad Meyer 78599c32ef Add CFI start/end proc directives to arm64, i386, and ppc
Follow-up to r353959 and r368070: do the same for other architectures.

arm32 already seems to use its own .fnstart/.fnend directives, which
appear to be ARM-specific variants of the same thing.  Likewise, MIPS
uses .frame directives.

Reviewed by:	arichardson
Differential Revision:	https://reviews.freebsd.org/D27387
2020-12-05 00:33:28 +00:00
Mitchell Horne 22bd0c9731 ossl: port to arm64
Enable in-kernel acceleration of SHA1 and SHA2 operations on arm64 by adding
support for the ossl(4) crypto driver. This uses OpenSSL's assembly routines
under the hood, which will detect and use SHA intrinsics if they are
supported by the CPU.

Reviewed by:	jhb
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D27390
2020-12-04 21:12:17 +00:00
Mitchell Horne fd86ae6800 ossl: split out x86 bits to x86/ossl_cpuid.c
Make room for adding arm64 support to this driver by moving the
x86-specific feature parsing to a separate file.

Reviewed by:	jhb
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D27388
2020-12-04 20:54:20 +00:00
John Baldwin 195105254f Check cipher key lengths during probesession.
OCF drivers in general should perform as many session parameter checks
as possible during probesession rather than when creating a new
session.  I got this wrong for aesni(4) in r359374.  In addition,
aesni(4) was performing the check for digest-only requests and failing
to create digest-only sessions as a result.

Reported by:	jkim
Tested by:	jkim
Sponsored by:	Chelsio Communications
2020-11-05 23:31:58 +00:00
John Baldwin 9038e6a1e4 Replace some K&R function definitions with ANSI C.
Reviewed by:	markj
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D27062
2020-11-03 22:32:30 +00:00
John Baldwin d3d79e968b Consistently use C99 fixed-width types in the in-kernel crypto code.
Reviewed by:	markj
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D27061
2020-11-03 22:27:54 +00:00
Jung-uk Kim 7cda7375e6 Add a new CCP device ID found on my Ryzen 5 3600XT.
MFC after:	1 week
2020-10-22 17:46:55 +00:00
Oleksandr Tymoshenko d2112ab098 [armv8crypto] Fix cryptodev probe logic in armv8crypto
Add missing break to prevent falling through to the default case statement
and returning EINVAL for all session configs.

Sponsored by:	Ampere Computing
Submitted by:	Klara, Inc.
2020-10-22 04:49:14 +00:00
John Baldwin ba610be90a Add a kernel crypto driver using assembly routines from OpenSSL.
Currently, this supports SHA1 and SHA2-{224,256,384,512} both as plain
hashes and in HMAC mode on both amd64 and i386.  It uses the SHA
intrinsics when present similar to aesni(4), but uses SSE/AVX
instructions when they are not.

Note that some files from OpenSSL that normally wrap the assembly
routines have been adapted to export methods usable by 'struct
auth_xform' as is used by existing software crypto routines.

Reviewed by:	gallatin, jkim, delphij, gnn
Sponsored by:	Netflix
Differential Revision:	https://reviews.freebsd.org/D26821
2020-10-20 17:50:18 +00:00
John Baldwin bc3d569800 Move generated OpenSSL assembly routines into the kernel sources.
Sponsored by:	Netflix
2020-10-20 17:00:43 +00:00
Marcin Wojtas efac54cb2f Add support for ESN in AES-NI crypto driver
This patch adds support for IPsec ESN (Extended Sequence Numbers) in
encrypt and authenticate mode (eg. AES-CBC and SHA256) and combined mode
(eg. AES-GCM).

For the encrypt and authenticate 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 combined modes the high-order 32 bits of the sequence number
[e.g.  RFC 4106, Chapter 5 AAD Construction] are part of crp_aad
(prepared by netipsec layer in case of ESN support enabled), therefore
non visible diff around combined modes.

Submitted by:           Grzegorz Jaszczyk <jaz@semihalf.com>
                        Patryk Duda <pdk@semihalf.com>
Reviewed by:            jhb
Differential revision:  https://reviews.freebsd.org/D22365
Obtained from:          Semihalf
Sponsored by:           Stormshield
2020-10-16 11:21:56 +00:00
Adrian Chadd 58958a74f2 [skein] Fix compile issue with unknown symbol SKEIN_ASM_UNROLL1024
Weirdly, I needed to sprinkle more parens here to get gcc-as in 6.4
to correctly generate things.

Without them, I'd get an unknown variable reference to SKEIN_ASM_UNROLL1024.

This at least links now, but I haven't run any test cases against it.
It may be worthwhile doing it in case gcc-as demands we liberally sprinkle
more brackets around variables in .if statements.

Thanks to ed for the suggestion of just sprinkling more brackets to
see if that helped.

Reviewed by:	emaste
2020-10-14 20:55:31 +00:00
Adrian Chadd cffe0e0f9d [skein] Fix compilation on gnu assembler with gcc-6 and gcc-9
For some reason I don't want to really understand, the following
happens with gnu as.

/home/adrian/git/freebsd/src/sys/crypto/skein/amd64/skein_block_asm.S: Assembler messages:
/home/adrian/git/freebsd/src/sys/crypto/skein/amd64/skein_block_asm.S:466: Error: found '(', expected: ')'
/home/adrian/git/freebsd/src/sys/crypto/skein/amd64/skein_block_asm.S:466: Error: junk at end of line, first unrecognized character is `('
/home/adrian/git/freebsd/src/sys/crypto/skein/amd64/skein_block_asm.S:795: Error: found '(', expected: ')'
/home/adrian/git/freebsd/src/sys/crypto/skein/amd64/skein_block_asm.S:795: Error: junk at end of line, first unrecognized character is `('
/home/adrian/git/freebsd/src/sys/crypto/skein/amd64/skein_block_asm.S:885: Error: non-constant expression in ".if" statement
/home/adrian/git/freebsd/src/sys/crypto/skein/amd64/skein_block_asm.S:885: Error: non-constant expression in ".if" statement
/home/adrian/git/freebsd/src/sys/crypto/skein/amd64/skein_block_asm.S:885: Error: non-constant expression in ".if" statement
/home/adrian/git/freebsd/src/sys/crypto/skein/amd64/skein_block_asm.S:885: Error: non-constant expression in ".if" statement
/home/adrian/git/freebsd/src/sys/crypto/skein/amd64/skein_block_asm.S:885: Error: non-constant expression in ".if" statement
/home/adrian/git/freebsd/src/sys/crypto/skein/amd64/skein_block_asm.S:885: Error: non-constant expression in ".if" statement

After an exhaustive search and experimentation at 11pm, I discovered that
putting them in parentheses fixes the compilation.

Ed pointed out that I could likely fix this in a bunch of other
locations but I'd rather leave these alone until other options
are enabled.

Tested:

* gcc-6, amd64

Reviewed by:	emaste
2020-10-14 14:29:56 +00:00
John Baldwin 4ef6ea38fc Add a <machine/fpu.h> for i386 that includes <machine/npx.h>.
arm64 has a similar wrapper.  This permits defining <machine/fpu.h> as
the standard header for fpu_kern_*.

Reviewed by:	kib
Sponsored by:	Netflix
Differential Revision:	https://reviews.freebsd.org/D26753
2020-10-13 17:26:12 +00:00
Ed Maste 36972ee3e0 libmd: fix assembly optimized skein implementation
The assembly implementation incorrectly used logical AND instead of
bitwise AND. Fix, and re-enable in libmd.

Submitted by:	Yang Zhong <yzhong@freebsdfoundation.org>
Reviewed by:	cem (earlier)
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D26614
2020-10-01 21:05:50 +00:00
John Baldwin 895c98cc29 Don't return errors from the cryptodev_process() method.
The cryptodev_process() method should either return 0 if it has
completed a request, or ERESTART to defer the request until later.  If
a request encounters an error, the error should be reported via
crp_etype before completing the request via crypto_done().

Fix a few more drivers noticed by asomers@ similar to the fix in
r365389.  This is an old bug, but went unnoticed since crypto requests
did not start failing as a normal part of operation until digest
verification was introduced which can fail requests with EBADMSG.

PR:		247986
Reported by:	asomers
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D26361
2020-09-08 22:41:35 +00:00
Alan Somers dbc973ca7a padlock(4): fix instapanics with geli authentication
cryptodev_process implementations are supposed to return 0

PR:		247986
Submitted by:	jhb
MFC after:	1 week
2020-09-06 19:25:31 +00:00
Alan Somers e6f6d0c9bc crypto(9): add CRYPTO_BUF_VMPAGE
crypto(9) functions can now be used on buffers composed of an array of
vm_page_t structures, such as those stored in an unmapped struct bio.  It
requires the running to kernel to support the direct memory map, so not all
architectures can use it.

Reviewed by:	markj, kib, jhb, mjg, mat, bcr (manpages)
MFC after:	1 week
Sponsored by:	Axcient
Differential Revision:	https://reviews.freebsd.org/D25671
2020-08-26 02:37:42 +00:00
Alan Somers b4fef8d068 padlock: fix Via Padlock with 192-bit keys
It's been broken since a typo in r359374

Reviewed by:	jhb
MFC after:	2 weeks
Sponsored by:	Axcient
Differential Revision:	https://reviews.freebsd.org/D25710
2020-07-20 16:12:14 +00:00
Conrad Meyer c74a3041f0 Add domain policy allocation for amd64 fpu_kern_ctx
Like other types of allocation, fpu_kern_ctx are frequently allocated per-cpu.
Provide the API and sketch some example consumers.

fpu_kern_alloc_ctx_domain() preferentially allocates memory from the
provided domain, and falls back to other domains if that one is empty
(DOMAINSET_PREF(domain) policy).

Maybe it makes more sense to just shove one of these in the DPCPU area
sooner or later -- left for future work.

Reviewed by:	markj
Differential Revision:	https://reviews.freebsd.org/D22053
2020-07-03 14:54:46 +00:00
John Baldwin b172f23dd7 Use zfree() instead of bzero() and free().
These bzero's should have been explicit_bzero's.

Reviewed by:	cem, delphij
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D25437
2020-06-25 20:20:22 +00:00
John Baldwin 4a711b8d04 Use zfree() instead of explicit_bzero() and free().
In addition to reducing lines of code, this also ensures that the full
allocation is always zeroed avoiding possible bugs with incorrect
lengths passed to explicit_bzero().

Suggested by:	cem
Reviewed by:	cem, delphij
Approved by:	csprng (cem)
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D25435
2020-06-25 20:17:34 +00:00
John Baldwin 604b021795 Add support for requests with separate AAD to aesni(4).
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D25289
2020-06-22 23:22:13 +00:00
John Baldwin b0b2161ce4 Fix AES-CCM requests with an AAD size smaller than a single block.
The amount to copy for the first block is the minimum of the size of
the AAD region or the remaining space in the first block.

Reported by:	cryptocheck -z
MFC after:	2 weeks
Sponsored by:	Netflix
Differential Revision:	https://reviews.freebsd.org/D25140
2020-06-12 21:33:02 +00:00
John Baldwin 9b6b2f8608 Adjust crypto_apply function callbacks for OCF.
- crypto_apply() is only used for reading a buffer to compute a
  digest, so change the data pointer to a const pointer.

- To better match m_apply(), change the data pointer type to void *
  and the length from uint16_t to u_int.  The length field in
  particular matters as none of the apply logic was splitting requests
  larger than UINT16_MAX.

- Adjust the auth_xform Update callback to match the function
  prototype passed to crypto_apply() and crypto_apply_buf().  This
  removes the needs for casts when using the Update callback.

- Change the Reinit and Setkey callbacks to also use a u_int length
  instead of uint16_t.

- Update auth transforms for the changes.  While here, use C99
  initializers for auth_hash structures and avoid casts on callbacks.

Reviewed by:	cem
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D25171
2020-06-10 21:18:19 +00:00
John Baldwin a3d565a118 Add a crypto capability flag for accelerated software drivers.
Use this in GELI to print out a different message when accelerated
software such as AESNI is used vs plain software crypto.

While here, simplify the logic in GELI a bit for determing which type
of crypto driver was chosen the first time by examining the
capabilities of the matched driver after a single call to
crypto_newsession rather than making separate calls with different
flags.

Reviewed by:	delphij
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D25126
2020-06-09 22:26:07 +00:00
John Baldwin cea399ec0e Mark padlock(4) and cryptocteon(4) as software drivers.
Both already return the accelerated software priority from
cryptodev_probesession.

Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D25125
2020-06-09 22:19:36 +00:00
Ed Maste 24ed6f550a Rename skein_block_asm.s to .S and assemble using Clang IAS
Comparing the object files produced by GNU as 2.17.50 and Clang IAS
shows many immaterial changes in strtab etc., and one material change
in .text:

   1bac:  4c 8b 4f 18             mov    0x18(%rdi),%r9
   1bb0:  eb 0e                   jmp    1bc0 <Skein1024_block_loop>
-  1bb2:  66 66 2e 0f 1f 84 00    data16 nopw %cs:0x0(%rax,%rax,1)
-  1bb9:  00 00 00 00
-  1bbd:  0f 1f 00                nopl   (%rax)
+  1bb2:  66 2e 0f 1f 84 00 00    nopw   %cs:0x0(%rax,%rax,1)
+  1bb9:  00 00 00
+  1bbc:  0f 1f 40 00             nopl   0x0(%rax)

 0000000000001bc0 <Skein1024_block_loop>:
 Skein1024_block_loop():
   1bc0:  4c 8b 47 10             mov    0x10(%rdi),%r8
   1bc4:  4c 03 85 c0 00 00 00    add    0xc0(%rbp),%r8

That is, GNU as and Clang's integrated assembler use different multi-
byte NOPs for alignment (GNU as emits an 11 byte NOP + a 3 byte NOP,
while Clang IAS emits a 10 byte NOP + a 4 byte NOP).

Dependency cleanup hacks are not required, because we do not create
.depend files from GNU as.

Reviewed by:	allanjude, arichardson, cem, tsoome
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D8434
2020-06-06 00:35:41 +00:00
Ed Maste 16c0b6eef9 skein_block_asm.S: use #ifdef not .ifdef, for Clang IAS
Clang IAS does not support the --defsym argument, and

.ifndef SKEIN_USE_ASM

gets turned into

.ifndef 1792

by the preprocessor, which results in

error: expected identifier after '.ifdef'
.ifndef 1792
        ^

Use #ifdef instead, which still works with GNU as.

Reviewed by:	cem
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D25154
2020-06-05 18:37:04 +00:00
Alex Richardson 7de010f2ee Allow assembling skein_block_asm.s with clang
GNU as seems to allow macro arguments without the '\' but clang is more
strict in that regard.
This change makes the source code compatible with LLVM's but does not yet
change the build system or rename it to .S.

The new code assembles identically with GNU as 2.17.50.

Reviewed By:	emaste
Differential Revision: https://reviews.freebsd.org/D25143
2020-06-05 13:54:13 +00:00
John Baldwin 66f2e4b620 Explicitly zero on-stack IVs, tags, and HMAC keys.
Reviewed by:	delphij
Sponsored by:	Netflix
Differential Revision:	https://reviews.freebsd.org/D25057
2020-06-03 22:15:11 +00:00
Marcin Wojtas ccbaa67d8b Change return types of hash update functions in SHA-NI
r359374 introduced crypto_apply function which takes as argument a function pointer
that is expected to return an int, however aesni hash update functions
return void.
Because of that the function pointer passed was simply cast with
its return value changed.
This resulted in undefined behavior, in particular when mbuf is used, (ipsec)
m_apply checks return value of function pointer passed to it
and in our case bogusly fails after calculating hash of the first mbuf
in chain.
Fix it by changing signatures of sha update routines in aesni and
dropping the casts.

Submitted by: Kornel Duleba
Reviewed by: jhb, cem
Obtained from: Semihalf
Sponsored by: Stormshield
Differential Revision: https://reviews.freebsd.org/D25030
2020-05-28 09:13:20 +00:00
John Baldwin a639f9379b Support separate output buffers for aesni(4).
The backend routines aesni(4) call for specific encryption modes all
expect virtually contiguous input/output buffers.  If the existing
output buffer is virtually contiguous, always write to the output
buffer directly from the mode-specific routines.  If the output buffer
is not contiguous, then a temporary buffer is allocated whose output
is then copied to the output buffer.  If the input buffer is not
contiguous, then the existing buffer used to hold the input is also
used to hold temporary output.

Sponsored by:	Netflix
Differential Revision:	https://reviews.freebsd.org/D24545
2020-05-25 22:30:44 +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 016fc6ddb3 Remove a workaround for GCM requests with an empty payload.
This was copied from ccr(4) (which does require the workaround), but
is reportedly not needed for ccp(4).

Discussed with:	cem
Sponsored by:	Netflix
2020-05-22 20:52:36 +00:00
John Baldwin 723d87648e Improve support for stream ciphers in the software encryption interface.
Add a 'native_blocksize' member to 'struct enc_xform' that ciphers can
use if they support a partial final block.  This is particular useful
for stream ciphers, but can also apply to other ciphers.  cryptosoft
will only pass in native blocks to the encrypt and decrypt hooks.  For
the final partial block, 'struct enc_xform' now has new
encrypt_last/decrypt_last hooks which accept the length of the final
block.  The multi_block methods are also retired.

Mark AES-ICM (AES-CTR) as a stream cipher.  This has some interesting
effects on IPsec in that FreeBSD can now properly receive all packets
sent by Linux when using AES-CTR, but FreeBSD can no longer
interoperate with OpenBSD and older verisons of FreeBSD which assume
AES-CTR packets have a payload padded to a 16-byte boundary.  Kornel
has offered to work on a patch to add a compatiblity sysctl to enforce
additional padding for AES-CTR in esp_output to permit compatibility
with OpenBSD and older versions of FreeBSD.

AES-XTS continues to use a block size of a single AES block length.
It is possible to adjust it to support partial final blocks by
implementing cipher text stealing via encrypt_last/decrypt_last hooks,
but I have not done so.

Reviewed by:	cem (earlier version)
Tested by:	Kornel Dulęba <mindal@semihalf.com> (AES-CTR with IPsec)
Sponsored by:	Netflix
Differential Revision:	https://reviews.freebsd.org/D24906
2020-05-22 16:29:09 +00:00
John Baldwin 3e9470482a Various cleanups to the software encryption transform interface.
- Consistently use 'void *' for key schedules / key contexts instead
  of a mix of 'caddr_t', 'uint8_t *', and 'void *'.

- Add a ctxsize member to enc_xform similar to what auth transforms use
  and require callers to malloc/zfree the context.  The setkey callback
  now supplies the caller-allocated context pointer and the zerokey
  callback is removed.  Callers now always use zfree() to ensure
  key contexts are zeroed.

- Consistently use C99 initializers for all statically-initialized
  instances of 'struct enc_xform'.

- Change the encrypt and decrypt functions to accept separate in and
  out buffer pointers.  Almost all of the backend crypto functions
  already supported separate input and output buffers and this makes
  it simpler to support separate buffers in OCF.

- Remove xform_userland.h shim to permit transforms to be compiled in
  userland.  Transforms no longer call malloc/free directly.

Reviewed by:	cem (earlier version)
Sponsored by:	Netflix
Differential Revision:	https://reviews.freebsd.org/D24855
2020-05-20 21:21:01 +00:00
John Baldwin 63823cac92 Remove MD5 HMAC from OCF.
There are no in-kernel consumers.

Reviewed by:	cem
Relnotes:	yes
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D24775
2020-05-11 22:08:08 +00:00
John Baldwin 32075647ef Remove support for the Blowfish algorithm from OCF.
It no longer has any in-kernel consumers.

Reviewed by:	cem
Relnotes:	yes
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D24772
2020-05-11 21:24:05 +00:00
Andriy Gapon a481fc9129 ccp: add a new hardware ID, found on AMD Ryzen 3 3200U
pciconf reports the device as:
Family 17h (Models 10h-1fh) Platform Security Processor

dmesg:
ccp0: <AMD CCP-5a> mem 0xfe500000-0xfe5fffff,0xfe68c000-0xfe68dfff at device 0.2 on pci4
crypto: assign ccp0 driver id 1, flags 0x1000000

MFC after:	1 week
2020-04-24 10:20:54 +00:00
John Baldwin 29fe41ddd7 Retire the CRYPTO_F_IV_GENERATE flag.
The sole in-tree user of this flag has been retired, so remove this
complexity from all drivers.  While here, add a helper routine drivers
can use to read the current request's IV into a local buffer.  Use
this routine to replace duplicated code in nearly all drivers.

Reviewed by:	cem
Sponsored by:	Netflix
Differential Revision:	https://reviews.freebsd.org/D24450
2020-04-20 22:24:49 +00:00
John Baldwin f91ab858cf Use crypto_contiguous_subsegment().
This driver used a home-rolled version that predated the function and
didn't support mbufs.
2020-04-15 21:05:38 +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
Pawel Biernacki 7029da5c36 Mark more nodes as CTLFLAG_MPSAFE or CTLFLAG_NEEDGIANT (17 of many)
r357614 added CTLFLAG_NEEDGIANT to make it easier to find nodes that are
still not MPSAFE (or already are but aren’t properly marked).
Use it in preparation for a general review of all nodes.

This is non-functional change that adds annotations to SYSCTL_NODE and
SYSCTL_PROC nodes using one of the soon-to-be-required flags.

Mark all obvious cases as MPSAFE.  All entries that haven't been marked
as MPSAFE before are by default marked as NEEDGIANT

Approved by:	kib (mentor, blanket)
Commented by:	kib, gallatin, melifaro
Differential Revision:	https://reviews.freebsd.org/D23718
2020-02-26 14:26:36 +00:00
Andrew Turner 88c66b953a Fix the armv8 crypto driver after r354170.
Sponsored by:	DARPA, AFRL
2019-10-30 10:41:10 +00:00
John Baldwin 87210a0c6d Stop using des_cblock * for arguments to DES functions.
This amounts to a char ** since it is a char[8] *.  Evil casts mostly
resolved the fact that what was actually passed in were plain char *.
Instead, change the DES functions to use 'unsigned char *' for keys
and for input and output buffers.

Reviewed by:	cem, imp
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D21389
2019-08-26 17:25:07 +00:00
John Baldwin 821fe3d3a4 Use 'const' for keys and IVs passed to software encryption algorithms.
Specifically, use 'const' for the key passed to the 'setkey' method
and 'const' for the 'iv' passed to the 'reinit' method.

Reviewed by:	cem
Sponsored by:	Chelsio Communications
Differential Revision:	https://reviews.freebsd.org/D21347
2019-08-22 00:02:08 +00:00
Ed Maste 8279d4b711 armv8crypto: add missing unlock for session (after r336439)
Attempts to use cryptodev (e.g. tests at /usr/src/tests/sys/opencrypto
with armv8crypto added to the module lists) were causing a panic.

Submitted by:	Greg V <greg_unrelenting.technology>
Differential Revision:	https://reviews.freebsd.org/D21012
2019-08-08 14:34:53 +00:00
Conrad Meyer 6fe286ed83 aesni(4): Fix trivial type typo
This fixes the kernel build with xtoolchain-gcc (6.4.0).

X-MFC-With:	r348268
2019-05-27 00:47:51 +00:00
Sean Eric Fagan 7cff9f3748 Add an AESNI-optimized version of the CCM/CBC cryptographic and authentication
code.  The primary client of this is probably going to be ZFS encryption.

Reviewed by:	jhb, cem
Sponsored by:	iXsystems Inc, Kithrup Enterprises
Differential Revision:	https://reviews.freebsd.org/D19298
2019-05-25 07:26:30 +00:00
Conrad Meyer e2e050c8ef Extract eventfilter declarations to sys/_eventfilter.h
This allows replacing "sys/eventfilter.h" includes with "sys/_eventfilter.h"
in other header files (e.g., sys/{bus,conf,cpu}.h) and reduces header
pollution substantially.

EVENTHANDLER_DECLARE and EVENTHANDLER_LIST_DECLAREs were moved out of .c
files into appropriate headers (e.g., sys/proc.h, powernv/opal.h).

As a side effect of reduced header pollution, many .c files and headers no
longer contain needed definitions.  The remainder of the patch addresses
adding appropriate includes to fix those files.

LOCK_DEBUG and LOCK_FILE_LINE_ARG are moved to sys/_lock.h, as required by
sys/mutex.h since r326106 (but silently protected by header pollution prior
to this change).

No functional change (intended).  Of course, any out of tree modules that
relied on header pollution for sys/eventhandler.h, sys/lock.h, or
sys/mutex.h inclusion need to be fixed.  __FreeBSD_version has been bumped.
2019-05-20 00:38:23 +00:00
Conrad Meyer 7d93ab5e35 Embedded chacha: Add 0-bit iv + 128-bit counter mode
This mode might be suitable for a Fortuna keystream primitive.

Reviewed by:	markm
Sponsored by:	Dell EMC Isilon
Differential Revision:	https://reviews.freebsd.org/D19410
2019-03-01 23:30:23 +00:00
Warner Losh 52467047aa Regularize the Netflix copyright
Use recent best practices for Copyright form at the top of
the license:
1. Remove all the All Rights Reserved clauses on our stuff. Where we
   piggybacked others, use a separate line to make things clear.
2. Use "Netflix, Inc." everywhere.
3. Use a single line for the copyright for grep friendliness.
4. Use date ranges in all places for our stuff.

Approved by: Netflix Legal (who gave me the form), adrian@ (pmc files)
2019-02-04 21:28:25 +00:00
Matt Macy ff2038a9bf Generalize AES iov optimization
Right now, aesni_cipher_alloc does a bit of special-casing
for CRYPTO_F_IOV, to not do any allocation if the first uio
is large enough for the requested size. While working on ZFS
crypto port, I ran into horrible performance because the code
uses scatter-gather, and many of the times the data to encrypt
was in the second entry. This code looks through the list, and
tries to see if there is a single uio that can contain the
requested data, and, if so, uses that.

This has a slight impact on the current consumers, in that the
check is a little more complicated for the ones that use
CRYPTO_F_IOV -- but none of them meet the criteria for testing
more than one.

Submitted by:	sef at ixsystems.com
Reviewed by:	cem@
MFC after:	3 days
Sponsored by:	iX Systems
Differential Revision:	https://reviews.freebsd.org/D18522
2018-12-13 04:40:53 +00:00
Conrad Meyer 070249043e rijndael (AES): Avoid leaking sensitive data on kernel stack
Noticed this investigating Fortuna.  Remove useless duplicate stack copies
of sensitive contents when possible, or if not possible, be sure to zero
them out when we're finished.

Approved by:	secteam (gordon)
Sponsored by:	Dell EMC Isilon
Differential Revision:	https://reviews.freebsd.org/D16935
2018-10-26 20:53:01 +00:00
Conrad Meyer f449384c4a Add explicit copyright text to trivial header
Reported by:	rgrimes
2018-10-22 01:27:11 +00:00
Conrad Meyer 987733eddf Embedded chacha: Remove some harmless dead stores in keystream mode
(From r338059.)

Sponsored by:	Dell EMC Isilon
2018-10-20 22:17:16 +00:00
Conrad Meyer 243e09430a Embedded chacha: Distinguish via dedicated macro
Set embedding expectations via CHACHA_EMBED macro rather than _KERNEL
definition.

No functional change.

Sponsored by:	Dell EMC Isilon
2018-10-20 22:14:29 +00:00
Conrad Meyer addfc6364f crypto/chacha: Split header into separate _chacha.h
Sponsored by:	Dell EMC Isilon
2018-10-20 22:12:53 +00:00
Warner Losh 329e817fcc Reapply, with minor tweaks, r338025, from the original commit:
Remove unused and easy to misuse PNP macro parameter

Inspired by r338025, just remove the element size parameter to the
MODULE_PNP_INFO macro entirely.  The 'table' parameter is now required to
have correct pointer (or array) type.  Since all invocations of the macro
already had this property and the emitted PNP data continues to include the
element size, there is no functional change.

Mostly done with the coccinelle 'spatch' tool:

  $ cat modpnpsize0.cocci
    @normaltables@
    identifier b,c;
    expression a,d,e;
    declarer MODULE_PNP_INFO;
    @@
     MODULE_PNP_INFO(a,b,c,d,
    -sizeof(d[0]),
     e);

    @singletons@
    identifier b,c,d;
    expression a;
    declarer MODULE_PNP_INFO;
    @@
     MODULE_PNP_INFO(a,b,c,&d,
    -sizeof(d),
     1);

  $ rg -l MODULE_PNP_INFO -- sys | \
    xargs spatch --in-place --sp-file modpnpsize0.cocci

(Note that coccinelle invokes diff(1) via a PATH search and expects diff to
tolerate the -B flag, which BSD diff does not.  So I had to link gdiff into
PATH as diff to use spatch.)

Tinderbox'd (-DMAKE_JUST_KERNELS).
Approved by: re (glen)
2018-09-26 17:12:14 +00:00
Warner Losh 91eeadc516 Don't load ccp automatically with devmatch
Remove the PNP info for the moment from the driver. It's an
experimental driver (as noted in r328150). It's performance is about
1/10th that of aesni. It will often panic when used with GELI (PR
2279820).  It's not in our best interest to have such a driver be
autoloaded by default.

Approved by: re@ (rgrimes)
Reviewed By: cem@
Differential Review: https://reviews.freebsd.org/D16959
2018-08-31 01:01:16 +00:00
Xin LI c1e80940f3 Update userland arc4random() with OpenBSD's Chacha20 based arc4random().
ObsoleteFiles.inc:

    Remove manual pages for arc4random_addrandom(3) and
    arc4random_stir(3).

  contrib/ntp/lib/isc/random.c:
  contrib/ntp/sntp/libevent/evutil_rand.c:

    Eliminate in-tree usage of arc4random_addrandom().

  crypto/heimdal/lib/roken/rand.c:
  crypto/openssh/config.h:

    Eliminate in-tree usage of arc4random_stir().

  include/stdlib.h:

    Remove arc4random_stir() and arc4random_addrandom() prototypes,
    provide temporary shims for transistion period.

  lib/libc/gen/Makefile.inc:

    Hook arc4random-compat.c to build, add hint for Chacha20 source for
    kernel, and remove arc4random_addrandom(3) and arc4random_stir(3)
    links.

  lib/libc/gen/arc4random.c:

    Adopt OpenBSD arc4random.c,v 1.54 with bare minimum changes, use the
    sys/crypto/chacha20 implementation of keystream.

  lib/libc/gen/Symbol.map:

    Remove arc4random_stir and arc4random_addrandom interfaces.

  lib/libc/gen/arc4random.h:

    Adopt OpenBSD arc4random.h,v 1.4 but provide _ARC4_LOCK of our own.

  lib/libc/gen/arc4random.3:

    Adopt OpenBSD arc4random.3,v 1.35 but keep FreeBSD r114444 and
    r118247.

  lib/libc/gen/arc4random-compat.c:

    Compatibility shims for arc4random_stir and arc4random_addrandom
    functions to preserve ABI.  Log once when called but do nothing
    otherwise.

  lib/libc/gen/getentropy.c:
  lib/libc/include/libc_private.h:

    Fold __arc4_sysctl into getentropy.c (renamed to arnd_sysctl).
    Remove from libc_private.h as a result.

  sys/crypto/chacha20/chacha.c:
  sys/crypto/chacha20/chacha.h:

    Make it possible to use the kernel implementation in libc.

PR:		182610
Reviewed by:	cem, markm
Obtained from:	OpenBSD
Relnotes:	yes
Differential Revision:	https://reviews.freebsd.org/D16760
2018-08-19 17:40:50 +00:00
Conrad Meyer b8e771e97a Back out r338035 until Warner is finished churning GSoC PNP patches
I was not aware Warner was making or planning to make forward progress in
this area and have since been informed of that.

It's easy to apply/reapply when churn dies down.
2018-08-19 00:46:22 +00:00
Conrad Meyer faa319436f Remove unused and easy to misuse PNP macro parameter
Inspired by r338025, just remove the element size parameter to the
MODULE_PNP_INFO macro entirely.  The 'table' parameter is now required to
have correct pointer (or array) type.  Since all invocations of the macro
already had this property and the emitted PNP data continues to include the
element size, there is no functional change.

Mostly done with the coccinelle 'spatch' tool:

  $ cat modpnpsize0.cocci
    @normaltables@
    identifier b,c;
    expression a,d,e;
    declarer MODULE_PNP_INFO;
    @@
     MODULE_PNP_INFO(a,b,c,d,
    -sizeof(d[0]),
     e);

    @singletons@
    identifier b,c,d;
    expression a;
    declarer MODULE_PNP_INFO;
    @@
     MODULE_PNP_INFO(a,b,c,&d,
    -sizeof(d),
     1);

  $ rg -l MODULE_PNP_INFO -- sys | \
    xargs spatch --in-place --sp-file modpnpsize0.cocci

(Note that coccinelle invokes diff(1) via a PATH search and expects diff to
tolerate the -B flag, which BSD diff does not.  So I had to link gdiff into
PATH as diff to use spatch.)

Tinderbox'd (-DMAKE_JUST_KERNELS).
2018-08-19 00:22:21 +00:00
Conrad Meyer f36e41e20b Bring in compatibility glue for libsodium
The idea is untouched upstream sources live in sys/contrib/libsodium.

sys/crypto/libsodium are support routines or compatibility headers to allow
building unmodified upstream code.

This is not yet integrated into the build system, so no functional change.
2018-08-17 00:27:56 +00:00
Xin LI 66bdf50fac libmd: Always erase context in _Final method, and when doing
it, consistently use explicit_bzero().

Update manual pages to match the behavior.

Reviewed by:	pfg, allanjude, jmg
MFC after:	1 month
Differential Revision:	https://reviews.freebsd.org/D16316
2018-07-20 07:01:28 +00:00
Conrad Meyer aeb75ff3fd Remove unused variable
Reported by:	gcc
2018-07-18 04:44:11 +00:00
Conrad Meyer 2ec76e3e31 aesni(4): Add SHA2-224(-HMAC) support as well 2018-07-18 04:43:18 +00:00
Conrad Meyer d9f87e4651 aesni(4): Add sha256 plain hash support 2018-07-18 04:37:14 +00:00
Conrad Meyer e2982a3ed2 aesni(4): Abstract out hash/HMAC support
No functional change.

Verified with cryptocheck.
2018-07-18 04:29:44 +00:00
Conrad Meyer 1b0909d51a OpenCrypto: Convert sessions to opaque handles instead of integers
Track session objects in the framework, and pass handles between the
framework (OCF), consumers, and drivers.  Avoid redundancy and complexity in
individual drivers by allocating session memory in the framework and
providing it to drivers in ::newsession().

Session handles are no longer integers with information encoded in various
high bits.  Use of the CRYPTO_SESID2FOO() macros should be replaced with the
appropriate crypto_ses2foo() function on the opaque session handle.

Convert OCF drivers (in particular, cryptosoft, as well as myriad others) to
the opaque handle interface.  Discard existing session tracking as much as
possible (quick pass).  There may be additional code ripe for deletion.

Convert OCF consumers (ipsec, geom_eli, krb5, cryptodev) to handle-style
interface.  The conversion is largely mechnical.

The change is documented in crypto.9.

Inspired by
https://lists.freebsd.org/pipermail/freebsd-arch/2018-January/018835.html .

No objection from:	ae (ipsec portion)
Reported by:	jhb
2018-07-18 00:56:25 +00:00
Andrew Turner a9dc38def4 Create an empty stdint.h for arm_neon.h to include.
The armv8crypto module includes arm_neon.h for the compiler intrinsic
functions. This includes the userland stdint.h file that doesn't exist in
the kernel. Fix this by providing an empty stdint.h to be used when we
include arm_neon.h.

Sponsored by:	DARPA, AFRL
Differential Revision:	https://reviews.freebsd.org/D16254
2018-07-16 15:39:33 +00:00
Conrad Meyer 1245c6d1a5 Implement SHA2-224 submode of SHA2-256
Like SHA2-384:SHA2-512, SHA2-224 is simply a truncated SHA2-256 with a
different initial vector.  Add to round out the complete basic SHA2 family.
2018-07-09 07:24:05 +00:00
Conrad Meyer 590adc1bc2 Remove "HMAC" from <HASH>_HMAC_BLOCK_LEN macro names
The block size is a property of the underlying hash algorithm, and has
nothing to do with the HMAC construction.

No functional change.
2018-07-09 07:21:37 +00:00
Conrad Meyer e50f10b5a4 aesni(4): Fix {de,en}crypt operations that allocated a buffer
aesni(4) allocates a contiguous buffer for the data it processes if the
provided input was not already virtually contiguous, and copies the input
there.  It performs encryption or decryption in-place.

r324037 removed the logic that then copied the processed data back to the
user-provided input buffer, breaking {de,enc}crypt for mbuf chains or
iovecs with more than a single descriptor.

PR:		228094 (probably, not confirmed)
Submitted by:	Sean Fagan <kithrup AT me.com>
Reported by:	Emeric POUPON <emeric.poupon AT stormshield.eu>
X-MFC-With:	324037
Security:	could result in plaintext being output by "encrypt"
		operation
2018-06-23 18:20:17 +00:00
Conrad Meyer 7d0ffa388e aesni(4): Support CRD_F_KEY_EXPLICIT OCF mode
PR:		227788
Reported by:	eadler@
2018-06-23 17:24:19 +00:00
Matt Macy fabb4256f6 disable printing value of SKEIN_LOOP during standard out,
not useful information
2018-05-19 18:27:14 +00:00
Conrad Meyer 61590291a8 opencrypto: Integrate Chacha20 algorithm into OCF
Mostly this is a thin shim around existing code to integrate with enc_xform
and cryptosoft (+ cryptodev).

Expand the cryptodev buffer used to match that of Chacha20's native block
size as a performance enhancement for chacha20_xform_crypt_multi.
2018-03-29 04:02:50 +00:00
Conrad Meyer 2cb2ba6df8 MFV: libb2: use native calls for secure memory clearance
Drop our local patch and restore full vanilla upstream code in
contrib/libb2.

No functional change intended.  explicit_bzero() should continue to be used.

Obtained from:	libb2 b4b241a34824b51956a7866606329a065d397525
Sponsored by:	Dell EMC Isilon
2018-03-27 14:55:01 +00:00
Warner Losh b722027307 The PNP info has to follow the module definition. Move it from just
after the array to its proper location. Otherwise, the linker.hints
file has things out of order and we associated it with whatever was
the previous module.
2018-03-25 16:56:49 +00:00
Conrad Meyer 0e33efe4e4 Import Blake2 algorithms (blake2b, blake2s) from libb2
The upstream repository is on github BLAKE2/libb2.  Files landed in
sys/contrib/libb2 are the unmodified upstream files, except for one
difference:  secure_zero_memory's contents have been replaced with
explicit_bzero() only because the previous implementation broke powerpc
link.  Preferential use of explicit_bzero() is in progress upstream, so
it is anticipated we will be able to drop this diff in the future.

sys/crypto/blake2 contains the source files needed to port libb2 to our
build system, a wrapped (limited) variant of the algorithm to match the API
of our auth_transform softcrypto abstraction, incorporation into the Open
Crypto Framework (OCF) cryptosoft(4) driver, as well as an x86 SSE/AVX
accelerated OCF driver, blake2(4).

Optimized variants of blake2 are compiled for a number of x86 machines
(anything from SSE2 to AVX + XOP).  On those machines, FPU context will need
to be explicitly saved before using blake2(4)-provided algorithms directly.
Use via cryptodev / OCF saves FPU state automatically, and use via the
auth_transform softcrypto abstraction does not use FPU.

The intent of the OCF driver is mostly to enable testing in userspace via
/dev/crypto.  ATF tests are added with published KAT test vectors to
validate correctness.

Reviewed by:	jhb, markj
Obtained from:	github BLAKE2/libb2
Differential Revision:	https://reviews.freebsd.org/D14662
2018-03-21 16:18:14 +00:00
Conrad Meyer 27cb8d849f Garbage collect unused chacha20 code
Two copies of chacha20 were imported into the tree on Apr 15 2017 (r316982)
and Apr 16 2017 (r317015).  Only the latter is actually used by anything, so
just go ahead and garbage collect the unused version while it's still only
in CURRENT.

I'm not making any judgement on which implementation is better.  If I pulled
the wrong one, feel free to swap the existing implementation out and replace
it with the other code (conforming to the API that actually gets used in
randomdev, of course).  We only need one generic implementation.

Sponsored by:	Dell EMC Isilon
2018-03-16 07:11:53 +00:00
Conrad Meyer 8475a4175f aesni(4): Stylistic/comment enhancements
Improve clarity of a comment and style(9) some areas.

No functional change.

Reported by:	markj (on review of a mostly-copied driver)
Sponsored by:	Dell EMC Isilon
2018-03-15 16:17:02 +00:00
Conrad Meyer 849ce31a82 Remove unused error return from API that cannot fail
No implementation of fpu_kern_enter() can fail, and it was causing needless
error checking boilerplate and confusion. Change the return code to void to
match reality.

(This trivial change took nine days to land because of the commit hook on
sys/dev/random.  Please consider removing the hook or otherwise lowering the
bar -- secteam never seems to have free time to review patches.)

Reported by:	Lachlan McIlroy <Lachlan.McIlroy AT isilon.com>
Reviewed by:	delphij
Approved by:	secteam (delphij)
Sponsored by:	Dell EMC Isilon
Differential Revision:	https://reviews.freebsd.org/D14380
2018-02-23 20:15:19 +00:00
Conrad Meyer 9ea9c34ba5 ccp(4): Store IV in output buffer in GCM software fallback when requested
Apply r328361 to duplicate copy of ccr_gcm_soft in ccp(4).

Properly honor the lack of the CRD_F_IV_PRESENT flag in the GCM software
fallback case for encryption requests.
2018-01-27 07:41:31 +00:00
Conrad Meyer 844d9543dc Add ccp(4): experimental driver for AMD Crypto Co-Processor
* Registers TRNG source for random(4)
* Finds available queues, LSBs; allocates static objects
* Allocates a shared MSI-X for all queues.  The hardware does not have
  separate interrupts per queue.  Working interrupt mode driver.
* Computes SHA hashes, HMAC.  Passes cryptotest.py, cryptocheck tests.
* Does AES-CBC, CTR mode, and XTS.  cryptotest.py and cryptocheck pass.
* Support for "authenc" (AES + HMAC).  (SHA1 seems to result in
  "unaligned" cleartext inputs from cryptocheck -- which the engine
  cannot handle.  SHA2 seems to work fine.)
* GCM passes for block-multiple AAD, input lengths

Largely based on ccr(4), part of cxgbe(4).

Rough performance averages on AMD Ryzen 1950X (4kB buffer):
aesni:      SHA1: ~8300 Mb/s    SHA256: ~8000 Mb/s
ccp:               ~630 Mb/s    SHA256:  ~660 Mb/s  SHA512:  ~700 Mb/s
cryptosoft:       ~1800 Mb/s    SHA256: ~1800 Mb/s  SHA512: ~2700 Mb/s

As you can see, performance is poor in comparison to aesni(4) and even
cryptosoft (due to high setup cost).  At a larger buffer size (128kB),
throughput is a little better (but still worse than aesni(4)):

aesni:      SHA1:~10400 Mb/s    SHA256: ~9950 Mb/s
ccp:              ~2200 Mb/s    SHA256: ~2600 Mb/s  SHA512: ~3800 Mb/s
cryptosoft:       ~1750 Mb/s    SHA256: ~1800 Mb/s  SHA512: ~2700 Mb/s

AES performance has a similar story:

aesni:      4kB: ~11250 Mb/s    128kB: ~11250 Mb/s
ccp:               ~350 Mb/s    128kB:  ~4600 Mb/s
cryptosoft:       ~1750 Mb/s    128kB:  ~1700 Mb/s

This driver is EXPERIMENTAL.  You should verify cryptographic results on
typical and corner case inputs from your application against a known- good
implementation.

Sponsored by:	Dell EMC Isilon
Differential Revision:	https://reviews.freebsd.org/D12723
2018-01-18 22:01:30 +00:00
Dimitry Andric 64e12b4140 Revert r327340, as the workaround for rep prefixes followed by .byte
directives is no longer needed after r328090.
2018-01-17 17:14:19 +00:00
Dimitry Andric c79126f2e4 Merge ^/head r327624 through r327885. 2018-01-12 18:23:35 +00:00
Conrad Meyer 4ce147895c aesni(4): Quiesce spurious GCC 6.3.0 -Wmaybe-uninitialized warnings
Always initialize some variables GCC warns about.  They are initialized in
every path where they are used, but GCC doesn't know that.

Sponsored by:	Dell EMC Isilon
2018-01-12 06:40:58 +00:00
Dimitry Andric 2055323b2c Work around a clang 6.0.0 issue with rep prefixes followed by .byte
directives (as reported in https://bugs.llvm.org/show_bug.cgi?id=35749),
by defining the rep prefix with yet another .byte directive.

This is a temporary fix, to be reverted before merging back to head,
until upstream has a proper fix for this.
2017-12-29 12:49:24 +00:00
Pedro F. Giffuni 51369649b0 sys: further adoption of SPDX licensing ID tags.
Mainly focus on files that use BSD 3-Clause license.

The Software Package Data Exchange (SPDX) group provides a specification
to make it easier for automated tools to detect and summarize well known
opensource licenses. We are gradually adopting the specification, noting
that the tags are considered only advisory and do not, in any way,
superceed or replace the license texts.

Special thanks to Wind River for providing access to "The Duke of
Highlander" tool: an older (2014) run over FreeBSD tree was useful as a
starting point.
2017-11-20 19:43:44 +00:00
Conrad Meyer a480149062 aesni(4): CRYPTO_AES_NIST_GCM_16 mandates MAC
Remove some dead conditionals and add an assertion around behavior already
present in aesni_process().

Silence a few Coverity false positives.

CIDs:		1381571, 1381557
Sponsored by:	Dell EMC Isilon
2017-10-04 21:15:45 +00:00
Conrad Meyer 50cf4f8950 aesni(4): Fix GCC build
The GCC xmmintrin.h header brokenly includes mm_malloc.h unconditionally.
(The Clang version of xmmintrin.h only includes mm_malloc.h if not compiling
in standalone mode.)

Hack around GCC's broken header by defining the include guard macro ahead of
including xmmintrin.h.

Reported by:	lwhsu, jhb
Tested by:	lwhsu
Sponsored by:	Dell EMC Isilon
2017-09-29 19:56:09 +00:00
Conrad Meyer fe182ba1d0 aesni(4): Add support for x86 SHA intrinsics
Some x86 class CPUs have accelerated intrinsics for SHA1 and SHA256.
Provide this functionality on CPUs that support it.

This implements CRYPTO_SHA1, CRYPTO_SHA1_HMAC, and CRYPTO_SHA2_256_HMAC.

Correctness: The cryptotest.py suite in tests/sys/opencrypto has been
enhanced to verify SHA1 and SHA256 HMAC using standard NIST test vectors.
The test passes on this driver.  Additionally, jhb's cryptocheck tool has
been used to compare various random inputs against OpenSSL.  This test also
passes.

Rough performance averages on AMD Ryzen 1950X (4kB buffer):
aesni:      SHA1: ~8300 Mb/s    SHA256: ~8000 Mb/s
cryptosoft:       ~1800 Mb/s    SHA256: ~1800 Mb/s

So ~4.4-4.6x speedup depending on algorithm choice.  This is consistent with
the results the Linux folks saw for 4kB buffers.

The driver borrows SHA update code from sys/crypto sha1 and sha256.  The
intrinsic step function comes from Intel under a 3-clause BSDL.[0]  The
intel_sha_extensions_sha<foo>_intrinsic.c files were renamed and lightly
modified (added const, resolved a warning or two; included the sha_sse
header to declare the functions).

[0]: https://software.intel.com/en-us/articles/intel-sha-extensions-implementations

Reviewed by:	jhb
Sponsored by:	Dell EMC Isilon
Differential Revision:	https://reviews.freebsd.org/D12452
2017-09-26 23:12:32 +00:00
Conrad Meyer 255811d758 opencrypto: Use C99 initializers for auth_hash instances
A misordering in the Via padlock driver really strongly suggested that these
should use C99 named initializers.

No functional change.

Sponsored by:	Dell EMC Isilon
2017-09-26 17:52:52 +00:00
Conrad Meyer 3693b18840 opencrypto: Loosen restriction on HMAC key sizes
Theoretically, HMACs do not actually have any limit on key sizes.
Transforms should compact input keys larger than the HMAC block size by
using the transform (hash) on the input key.

(Short input keys are padded out with zeros to the HMAC block size.)

Still, not all FreeBSD crypto drivers that provide HMAC functionality
handle longer-than-blocksize keys appropriately, so enforce a "maximum" key
length in the crypto API for auth_hashes that previously expressed a
requirement.  (The "maximum" is the size of a single HMAC block for the
given transform.)  Unconstrained auth_hashes are left as-is.

I believe the previous hardcoded sizes were committed in the original
import of opencrypto from OpenBSD and are due to specific protocol
details of IPSec.  Note that none of the previous sizes actually matched
the appropriate HMAC block size.

The previous hardcoded sizes made the SHA tests in cryptotest.py
useless for testing FreeBSD crypto drivers; none of the NIST-KAT example
inputs had keys sized to the previous expectations.

The following drivers were audited to check that they handled keys up to
the block size of the HMAC safely:

  Software HMAC:
    * padlock(4)
    * cesa
    * glxsb
    * safe(4)
    * ubsec(4)

  Hardware accelerated HMAC:
    * ccr(4)
    * hifn(4)
    * sec(4) (Only supports up to 64 byte keys despite claiming to
      support SHA2 HMACs, but validates input key sizes)
    * cryptocteon (MIPS)
    * nlmsec (MIPS)
    * rmisec (MIPS) (Amusingly, does not appear to use key material at
      all -- presumed broken)

Reviewed by:	jhb (previous version), rlibby (previous version)
Sponsored by:	Dell EMC Isilon
Differential Revision:	https://reviews.freebsd.org/D12437
2017-09-26 16:18:10 +00:00
Conrad Meyer d616681cec aesni(4): Fix another trivial typo (aensi -> aesni)
Sponsored by:	Dell EMC Isilon
2017-09-20 18:31:36 +00:00
Conrad Meyer 81326306dd aesni(4): Fix trivial typo (AQUIRE -> ACQUIRE)
Sponsored by:	Dell EMC Isilon
2017-09-20 17:53:25 +00:00
Ryan Libby d395fd0d46 aesni: quiet -Wcast-qual
Reviewed by:	delphij
Approved by:	markj (mentor)
Sponsored by:	Dell EMC Isilon
Differential Revision:	https://reviews.freebsd.org/D12021
2017-08-16 22:54:35 +00:00
Ed Maste 3e85b721d6 Remove register keyword from sys/ and ANSIfy prototypes
A long long time ago the register keyword told the compiler to store
the corresponding variable in a CPU register, but it is not relevant
for any compiler used in the FreeBSD world today.

ANSIfy related prototypes while here.

Reviewed by:	cem, jhb
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D10193
2017-05-17 00:34:34 +00:00
Dag-Erling Smørgrav f03be66539 Fix counter increment in Salsa and ChaCha.
In my eagerness to eliminate a branch which is taken once per 2^38
bytes of keystream, I forgot that the state words are in host order.
Thus, the counter increment code worked fine on little-endian
machines, but not on big-endian ones.  Switch to a simpler (branchful)
solution.
2017-04-22 01:06:23 +00:00
Mark Murray 150890b0c6 Replace the RC4 algorithm for generating in-kernel secure random
numbers with Chacha20. Keep the API, though, as that is what the
other *BSD's have done.

Use the boot-time entropy stash (if present) to bootstrap the
in-kernel entropy source.

Reviewed by: delphij,rwatson
Approved by: so(delphij)
MFC after: 2 months
Relnotes: yes
Differential Revision: https://reviews.freebsd.org/D10048
2017-04-16 09:11:02 +00:00
Dag-Erling Smørgrav d196586a6c 3BSD-licensed implementation of the chacha20 stream cipher, intended for
use by the upcoming arc4random replacement.
2017-04-15 20:51:53 +00:00
Allan Jude ec5c0e5be9 Implement boot-time encryption key passing (keybuf)
This patch adds a general mechanism for providing encryption keys to the
kernel from the boot loader. This is intended to enable GELI support at
boot time, providing a better mechanism for passing keys to the kernel
than environment variables. It is designed to be extensible to other
applications, and can easily handle multiple encrypted volumes with
different keys.

This mechanism is currently used by the pending GELI EFI work.
Additionally, this mechanism can potentially be used to interface with
GRUB, opening up options for coreboot+GRUB configurations with completely
encrypted disks.

Another benefit over the existing system is that it does not require
re-deriving the user key from the password at each boot stage.

Most of this patch was written by Eric McCorkle. It was extended by
Allan Jude with a number of minor enhancements and extending the keybuf
feature into boot2.

GELI user keys are now derived once, in boot2, then passed to the loader,
which reuses the key, then passes it to the kernel, where the GELI module
destroys the keybuf after decrypting the volumes.

Submitted by:	Eric McCorkle <eric@metricspace.net> (Original Version)
Reviewed by:	oshogbo (earlier version), cem (earlier version)
MFC after:	3 weeks
Relnotes:	yes
Sponsored by:	ScaleEngine Inc.
Differential Revision:	https://reviews.freebsd.org/D9575
2017-04-01 05:05:22 +00:00
Yoshihiro Takahashi 2b375b4edd Remove pc98 support completely.
I thank all developers and contributors for pc98.

Relnotes:	yes
2017-01-28 02:22:15 +00:00
Ed Maste cd03a7b7ce libmd: add noexec stack annotation in skein_block_asm.s
MFC after:	1 week
Sponsored by:	The FreeBSD Foundation
2017-01-07 19:26:25 +00:00
Andrew Turner d6699d292b Add accelerated AES with using the ARMv8 crypto instructions. This is based
on the AES-NI code, and modified as needed for use on ARMv8. When loaded
the driver will check the appropriate field in the id_aa64isar0_el1
register to see if AES is supported, and if so the probe function will
signal the driver should attach.

With this I have seen up to 2000Mb/s from the cryptotest test with a single
thread on a ThunderX Pass 2.0.

Reviewed by:	imp
Obtained from:	ABT Systems Ltd
MFC after:	1 week
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D8297
2016-11-21 11:18:00 +00:00
Alan Somers 8254c3c5d3 Fix C++ includability of crypto headers with static array sizes
C99 allows array function parameters to use the static keyword for their
sizes. This tells the compiler that the parameter will have at least the
specified size, and calling code will fail to compile if that guarantee is
not met. However, this syntax is not legal in C++.

This commit reverts r300824, which worked around the problem for
sys/sys/md5.h only, and introduces a new macro: min_size(). min_size(x) can
be used in headers as a static array size, but will still compile in C++
mode.

Reviewed by:	cem, ed
MFC after:	4 weeks
Sponsored by:	Spectra Logic Corp
Differential Revision:	https://reviews.freebsd.org/D8277
2016-10-18 23:20:49 +00:00
Ed Maste de13c2427d libmd: introduce functions that operate on an fd instead of filename
Reviewed by:	allanjude, cem
MFC after:	2 months
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D8264
2016-10-17 13:47:22 +00:00
Allan Jude 2b53c51767 Fix typo in skein amd64 assembly
Sponsored by:	ScaleEngine Inc.
2016-09-08 02:38:55 +00:00
Allan Jude 0144ad3e78 Connect the SHA-512t256 and Skein hashing algorithms to ZFS
Support for the new hashing algorithms in ZFS was introduced in r289422
However it was disconnected because FreeBSD lacked implementations of
SHA-512 (truncated to 256 bits), and Skein.

These implementations were introduced in r300921 and r300966 respectively

This commit connects them to ZFS and enabled these new checksum algorithms

This new algorithms are not supported by the boot blocks, so do not use them
on your root dataset if you boot from ZFS.

Relnotes:	yes
Sponsored by:	ScaleEngine Inc.
2016-05-31 04:12:14 +00:00
Colin Percival 696c3895ae Retune SHA2 code for improved performance on CPUs with more ILP and
a preference for memory load instructions over large code footprints
with embedded immediate variables.

On amd64 CPUs from 2007-2008 there is not a significant change, but
amd64 CPUs from 2009-2010 get roughly 10% more throughput with this
code; amd64 CPUs from 2011-2012 get roughly 15% more throughput; and
AMD64 CPUs from 2013-2015 get 20-25% more throughput.  The Raspberry
Pi 2 increases its throughput by 6-8%.

Sponsored by:	Tarsnap Backup Inc.
Performance tested by:	allanjude
MFC after:	3 weeks
2016-05-29 17:26:40 +00:00
Allan Jude b468a9ff1d Import the skein hashing algorithm, based on the threefish block cipher
Connect it to userland (libmd, libcrypt, sbin/md5) and kernel (crypto.ko)

Support for skein as a ZFS checksum algorithm was introduced in r289422
but is disconnected because FreeBSD lacked a Skein implementation.

A further commit will enable it in ZFS.

Reviewed by:	cem
Sponsored by:	ScaleEngine Inc.
Differential Revision:	https://reviews.freebsd.org/D6166
2016-05-29 01:15:36 +00:00
Allan Jude 1780e40715 Implement SHA-512 truncated (224 and 256 bits)
This implements SHA-512/256, which generates a 256 bit hash by
calculating the SHA-512 then truncating the result. A different initial
value is used, making the result different from the first 256 bits of
the SHA-512 of the same input. SHA-512 is ~50% faster than SHA-256 on
64bit platforms, so the result is a faster 256 bit hash.

The main goal of this implementation is to enable support for this
faster hashing algorithm in ZFS. The feature was introduced into ZFS
in r289422, but is disconnected because SHA-512/256 support was missing.
A further commit will enable it in ZFS.

This is the follow on to r292782

Reviewed by:	cem
Sponsored by:	ScaleEngine Inc.
Differential Revision:	https://reviews.freebsd.org/D6061
2016-05-28 16:06:07 +00:00
Conrad Meyer 571ebf7685 crypto routines: Hint minimum buffer sizes to the compiler
Use the C99 'static' keyword to hint to the compiler IVs and output digest
sizes.  The keyword informs the compiler of the minimum valid size for a given
array.  Obviously not every pointer can be validated (i.e., the compiler can
produce false negative but not false positive reports).

No functional change.  No ABI change.

Sponsored by:	EMC / Isilon Storage Division
2016-05-26 19:29:29 +00:00
Conrad Meyer c564824193 aesni(4): Initialize error before use
Reported by:	Coverity
CID:		1331554
Sponsored by:	EMC / Isilon Storage Division
2016-04-20 03:05:32 +00:00
Allan Jude 2155bb238f Break up opencrypto/xform.c so it can be reused piecemeal
Keep xform.c as a meta-file including the broken out bits
existing code that includes xform.c continues to work as normal

Individual algorithms can now be reused elsewhere, including outside
of the kernel

Reviewed by:	bapt (previous version), gnn, delphij
Approved by:	secteam
MFC after:	1 week
Sponsored by:	ScaleEngine Inc.
Differential Revision:	https://reviews.freebsd.org/D4674
2015-12-30 22:43:07 +00:00
Allan Jude 7a3f5d11fb Replace sys/crypto/sha2/sha2.c with lib/libmd/sha512c.c
cperciva's libmd implementation is 5-30% faster

The same was done for SHA256 previously in r263218

cperciva's implementation was lacking SHA-384 which I implemented, validated against OpenSSL and the NIST documentation

Extend sbin/md5 to create sha384(1)

Chase dependancies on sys/crypto/sha2/sha2.{c,h} and replace them with sha512{c.c,.h}

Reviewed by:	cperciva, des, delphij
Approved by:	secteam, bapt (mentor)
MFC after:	2 weeks
Sponsored by:	ScaleEngine Inc.
Differential Revision:	https://reviews.freebsd.org/D3929
2015-12-27 17:33:59 +00:00
John-Mark Gurney e381fd293d const'ify an arg that we don't update... 2015-07-29 23:37:15 +00:00
John-Mark Gurney 2ff9c4f915 Complete the move that was started w/ r263218.. For some reason I
didn't delete the files, so that means we need to bring the changes in
r282726 to the correct files..

make tinderbox completed with this patch...
2015-07-11 03:12:34 +00:00
John-Mark Gurney 275a0a97ed upon further examination, it turns out that _unregister_all already
provides the guarantee that no threads will be in the _newsession code..
This is provided by the CRYPTODRIVER lock...  This makes the pause
unneeded...
2015-07-08 22:48:41 +00:00
John-Mark Gurney 9d38fd076e address an issue where consumers, like IPsec, can reuse the same
session in multiple threads w/o locking..  There was a single fpu
context shared per session, if multiple threads were using the session,
and both migrated away, they could corrupt each other's fpu context...

This patch adds a per cpu context and a lock to protect it...

It also tries to better address unloading of the aesni module...
The pause will be removed once the OpenCrypto Framework provides a
better method for draining callers into _newsession...

I first discovered the fpu context sharing issue w/ a flood ping over
an IPsec tunnel between two bhyve machines...  The patch in D3015
was used to verify that this fix does fix the issue...

Reviewed by:	gnn, kib (both earlier versions)
Differential Revision:        https://reviews.freebsd.org/D3016
2015-07-08 19:15:29 +00:00
John-Mark Gurney a13589bc47 unroll the loop slightly... This improves performance enough to
justify, especially for CBC performance where we can't pipeline..  I
don't happen to have my measurements handy though...

Sponsored by:	Netflix, Inc.
2015-07-07 20:31:09 +00:00
John-Mark Gurney 5a550cca9a Fix for non-random IV's when CRD_F_IV_PRESENT and CRD_F_IV_EXPLICIT
flags are not specified... This bug was introduced in r275732...

This only affects IPsec ESP only policies w/ the aesni module loaded,
other subsystems specify one or both of the flags...

Reviewed by:	gnn, delphij, eri
2015-07-06 19:30:29 +00:00
John-Mark Gurney bcc0b68477 remove _NORMAL flag which isn't suppose to be used w/ _alloc_ctx...
Reviewed by:	kib (a while ago)
2015-07-06 19:17:56 +00:00
Craig Rodrigues 800be1b6f9 In the version of gcc in the FreeBSD tree, this modification was made to
the compiler in svn r242182:

#if STDC_HOSTED
#include <mm_malloc.h>
#endif

A similar change was done to clang in the FreeBSD tree in svn r218893:

However, for external gcc toolchains, this patch is not in the compiler's header
file.

This patch to FreeBSD's aesni code allows compilation with an external
gcc toolchain.

Differential Revision: https://reviews.freebsd.org/D2285
Reviewed by:  jmg, dim
Approved by:  dim
2015-04-16 17:42:52 +00:00
John-Mark Gurney 08fca7a56b Add some new modes to OpenCrypto. These modes are AES-ICM (can be used
for counter mode), and AES-GCM.  Both of these modes have been added to
the aesni module.

Included is a set of tests to validate that the software and aesni
module calculate the correct values.  These use the NIST KAT test
vectors.  To run the test, you will need to install a soon to be
committed port, nist-kat that will install the vectors.  Using a port
is necessary as the test vectors are around 25MB.

All the man pages were updated.  I have added a new man page, crypto.7,
which includes a description of how to use each mode.  All the new modes
and some other AES modes are present.  It would be good for someone
else to go through and document the other modes.

A new ioctl was added to support AEAD modes which AES-GCM is one of them.
Without this ioctl, it is not possible to test AEAD modes from userland.

Add a timing safe bcmp for use to compare MACs.  Previously we were using
bcmp which could leak timing info and result in the ability to forge
messages.

Add a minor optimization to the aesni module so that single segment
mbufs don't get copied and instead are updated in place.  The aesni
module needs to be updated to support blocked IO so segmented mbufs
don't have to be copied.

We require that the IV be specified for all calls for both GCM and ICM.
This is to ensure proper use of these functions.

Obtained from:	p4: //depot/projects/opencrypto
Relnotes:	yes
Sponsored by:	FreeBSD Foundation
Sponsored by:	NetGate
2014-12-12 19:56:36 +00:00
Dag-Erling Smørgrav 136fae42a9 Fix gcc build: preserve const qualifier when casting input values.
Noticed by:	bz@
Submitted by:	dim@
2014-11-11 13:37:28 +00:00
Dag-Erling Smørgrav 133cdd9e13 Constify the AES code and propagate to consumers. This allows us to
update the Fortuna code to use SHAd-256 as defined in FS&K.

Approved by:	so (self)
2014-11-10 09:44:38 +00:00
Konstantin Belousov 27007c6576 Put the aesni_cipher_setup() and aesni_cipher_process() functions into
the file which is compiled with SSE disabled.  The functions set up
the FPU context for kernel, and compiler optimizations which could
lead to use of XMM registers before the fpu_kern_enter(9) is called or
after fpu_kern_leave(9), panic the machine.

Discussed with:	jmg
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2014-06-24 06:55:49 +00:00
Konstantin Belousov 633034fe0e Add FPU_KERN_KTHR flag to fpu_kern_enter(9), which avoids saving FPU
context into memory for the kernel threads which called
fpu_kern_thread(9).  This allows the fpu_kern_enter() callers to not
check for is_fpu_kern_thread() to get the optimization.

Apply the flag to padlock(4) and aesni(4).  In aesni_cipher_process(),
do not leak FPU context state on error.

Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2014-06-23 07:37:54 +00:00
Warner Losh 3bdf775801 NO_MAN= has been deprecated in favor of MAN= for some time, go ahead
and finish the job. ncurses is now the only Makefile in the tree that
uses it since it wasn't a simple mechanical change, and will be
addressed in a future commit.
2014-04-13 05:21:56 +00:00
John-Mark Gurney 8083f14fc2 replace the kernel's version w/ cperciva's implementation... In all
my tests, it is faster ~20%, even on an old IXP425 533MHz it is ~45%
faster...  This is partly due to loop unrolling, so the code size does
significantly increase...  I do plan on committing a version that
rolls up the loops again for smaller code size for embedded systems
where size is more important than absolute performance (it'll save ~6k
code)...

The kernel implementation is now shared w/ userland's libcrypt and
libmd...

We drop support for sha256 from sha2.c, so now sha2.c only contains
sha384 and sha512...

Reviewed by:	secteam@
2014-03-16 01:43:23 +00:00
John-Mark Gurney 97447ea423 copy these files from lib/libmd in preperation for moving these files
into the kernel...
2014-03-16 00:57:26 +00:00
John-Mark Gurney 9164a239ea fix broken style(9) in r258399
Pointed out by:	brd
2013-11-23 00:28:18 +00:00
John-Mark Gurney 23fc6e1652 flag that the aesni driver is sync... This means we don't waste a
context switch just to call the done callback...  On my machine, this
improves geli/gzero decrypt performance by ~27% from 550MB/sec to
~700MB/sec...

MFC after:	3 days
2013-11-20 20:25:27 +00:00
John-Mark Gurney 038ffd3e43 make it so that from/to can be missaligned as it can happen (the geli
regression manages to do it)...  We use a packed struct to coerce
gcc/clang into producing unaligned loads (there is not packed pointer
attribute, otherwise this would be easier)...

use _storeu_ and _loadu_ when using the structure is overkill...

be better at using types properly...  Since we allocate our own key
schedule and make sure it's aligned, use the __m128i type in various
arguments to functions...

clang ignores __aligned on prototypes and gcc errors on them, leave them
in comments to document that these function arguments are require to be
aligned...

about all that changes is movdqa -> movdqu from reading the diff of the
disassembly output...

Noticed by:	symbolics at gmx.com
MFC after:	3 days
2013-11-06 19:14:49 +00:00
John-Mark Gurney ff6c7bf5ca Use the fact that the AES-NI instructions can be pipelined to improve
performance... Use SSE2 instructions for calculating the XTS tweek
factor...  Let the compiler do more work and handle register allocation
by using intrinsics, now only the key schedule is in assembly...

Replace .byte hard coded instructions w/ the proper instructions now
that both clang and gcc support them...

On my machine, pulling the code to userland I saw performance go from
~150MB/sec to 2GB/sec in XTS mode.  GELI on GNOP saw a more modest
increase of about 3x due to other system overhead (geom and
opencrypto)...

These changes allow almost full disk io rate w/ geli...

Reviewed by:	-current, -security
Thanks to:	Mike Hamburg for the XTS tweek algorithm
2013-09-03 18:31:23 +00:00
Andre Oppermann bf0354c0f2 Fix const propagation issues to make GCC happy.
Submitted by:	Michael Butler <imb@protected-networks.net>
2013-07-11 16:27:11 +00:00
Andre Oppermann 6856398eab SipHash is a cryptographically strong pseudo-random function (a.k.a. keyed
hash function) optimized for speed on short messages returning a 64bit hash/
digest value.

SipHash is simpler and much faster than other secure MACs and competitive
in speed with popular non-cryptographic hash functions.  It uses a 128-bit
key without the hidden cost of a key expansion step.  SipHash iterates a
simple round function consisting of four additions, four xors, and six
rotations, interleaved with xors of message blocks for a pre-defined number
of compression and finalization rounds.  The absence of  secret load/store
addresses or secret branch conditions avoid timing attacks.  No state is
shared between messages.  Hashing is deterministic and doesn't use nonces.
It is not susceptible to length extension attacks.

Target applications include network traffic authentication, message
authentication (MAC) and hash-tables protection against hash-flooding
denial-of-service attacks.

The number of update/finalization rounds is defined during initialization:

 SipHash24_Init() for the fast and reasonable strong version.
 SipHash48_Init() for the strong version (half as fast).

SipHash usage is similar to other hash functions:

 struct SIPHASH_CTX ctx;
 char *k = "16bytes long key"
 char *s = "string";
 uint64_t h = 0;
 SipHash24_Init(&ctx);
 SipHash_SetKey(&ctx, k);
 SipHash_Update(&ctx, s, strlen(s));
 SipHash_Final(&h, &ctx);  /* or */
 h = SipHash_End(&ctx);    /* or */
 h = SipHash24(&ctx, k, s, strlen(s));

It was designed by Jean-Philippe Aumasson and Daniel J. Bernstein and
is described in the paper "SipHash: a fast short-input PRF", 2012.09.18:
 https://131002.net/siphash/siphash.pdf
 Permanent ID: b9a943a805fbfc6fde808af9fc0ecdfa

Implemented by:	andre (based on the paper)
Reviewed by:	cperciva
2013-07-11 14:18:38 +00:00
Xin LI 76a207c2b9 Sync with KAME.
MFC after:	1 month
2013-07-09 22:04:35 +00:00
Robert Millan f19122edbf Allow assert() to operate correctly when building userland code. 2013-07-09 10:27:26 +00:00
Pawel Jakub Dawidek 45b56a6ba2 When porting XTS-related code from OpenBSD I forgot to update copyright (only
OpenBSD was credited in one of two commits). Fix it.

Reported by:	Theo de Raadt <deraadt@cvs.openbsd.org>
Reviewed by:	Damien Miller <djm@mindrot.org>
2013-02-20 22:59:53 +00:00
Kevin Lo 9823d52705 Revert previous commit...
Pointyhat to:	kevlo (myself)
2012-10-10 08:36:38 +00:00
Kevin Lo a10cee30c9 Prefer NULL over 0 for pointers 2012-10-09 08:27:40 +00:00
Konstantin Belousov 8c6f8f3d5b Add support for the extended FPU states on amd64, both for native
64bit and 32bit ABIs.  As a side-effect, it enables AVX on capable
CPUs.

In particular:

- Query the CPU support for XSAVE, list of the supported extensions
  and the required size of FPU save area. The hw.use_xsave tunable is
  provided for disabling XSAVE, and hw.xsave_mask may be used to
  select the enabled extensions.

- Remove the FPU save area from PCB and dynamically allocate the
  (run-time sized) user save area on the top of the kernel stack,
  right above the PCB. Reorganize the thread0 PCB initialization to
  postpone it after BSP is queried for save area size.

- The dumppcb, stoppcbs and susppcbs now do not carry the FPU state as
  well. FPU state is only useful for suspend, where it is saved in
  dynamically allocated suspfpusave area.

- Use XSAVE and XRSTOR to save/restore FPU state, if supported and
  enabled.

- Define new mcontext_t flag _MC_HASFPXSTATE, indicating that
  mcontext_t has a valid pointer to out-of-struct extended FPU
  state. Signal handlers are supplied with stack-allocated fpu
  state. The sigreturn(2) and setcontext(2) syscall honour the flag,
  allowing the signal handlers to inspect and manipilate extended
  state in the interrupted context.

- The getcontext(2) never returns extended state, since there is no
  place in the fixed-sized mcontext_t to place variable-sized save
  area. And, since mcontext_t is embedded into ucontext_t, makes it
  impossible to fix in a reasonable way.  Instead of extending
  getcontext(2) syscall, provide a sysarch(2) facility to query
  extended FPU state.

- Add ptrace(2) support for getting and setting extended state; while
  there, implement missed PT_I386_{GET,SET}XMMREGS for 32bit binaries.

- Change fpu_kern KPI to not expose struct fpu_kern_ctx layout to
  consumers, making it opaque. Internally, struct fpu_kern_ctx now
  contains a space for the extended state. Convert in-kernel consumers
  of fpu_kern KPI both on i386 and amd64.

First version of the support for AVX was submitted by Tim Bird
<tim.bird am sony com> on behalf of Sony. This version was written
from scratch.

Tested by:	pho (previous version), Yamagi Burmeister <lists yamagi org>
MFC after:	1 month
2012-01-21 17:45:27 +00:00
Pawel Jakub Dawidek 14a0d24607 Update Copyright.
MFC after:	3 days
2011-10-27 14:15:26 +00:00
Pawel Jakub Dawidek 5fa1b35081 Improve AES-NI performance for AES-XTS:
- Operate on uint64_t types when doing XORing, etc. instead of uint8_t.
- Don't bzero() temporary block for every AES block. Do it once for entire
  data block.
- AES-NI is available only on little endian architectures. Simplify code
  that takes block number from IV.

Benchmarks:

Memory-backed md(4) device, software AES-XTS, 4kB sector:

	# dd if=/dev/md0.eli bs=1m
	59.61MB/s

Memory-backed md(4) device, old AES-NI AES-XTS, 4kB sector:

	# dd if=/dev/md0.eli bs=1m
	97.29MB/s

Memory-backed md(4) device, new AES-NI AES-XTS, 4kB sector:

	# dd if=/dev/md0.eli bs=1m
	221.26MB/s

127% performance improvement between old and new code.

Harddisk, raw speed:

	# dd if=/dev/ada0 bs=1m
	137.63MB/s

Harddisk, software AES-XTS, 4kB sector:

	# dd if=/dev/ada0.eli bs=1m
	47.83MB/s (34% of raw disk speed)

Harddisk, old AES-NI AES-XTS, 4kB sector:

	# dd if=/dev/ada0.eli bs=1m
	68.33MB/s (49% of raw disk speed)

Harddisk, new AES-NI AES-XTS, 4kB sector:

	# dd if=/dev/ada0.eli bs=1m
	108.35MB/s (78% of raw disk speed)

58% performance improvement between old and new code.

As a side-note, GELI with AES-NI using AES-CBC can achive native disk speed.

MFC after:	3 days
2011-10-27 14:07:57 +00:00
Konstantin Belousov 93ed70f9b4 Fix a bug in the result of manual assembly.
Reported by:	Stefan Grundmann <sg2342 googlemail com>
PR:	kern/155118
MFC after:	3 days
2011-03-02 14:56:58 +00:00