Commit Graph

233 Commits

Author SHA1 Message Date
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
Rebecca Cran
3283511248 Make private functions static.
PR:		kern/43611
Submitted by:	Matt Emmerton <matt at gsicomp.on.ca>
Reviewed by:	kib
MFC after:	3 days
2011-02-21 16:21:43 +00:00
Konstantin Belousov
17ca6d98e1 Remove DEBUG sections.
MFC after:	3 days
2010-11-27 15:41:44 +00:00
Konstantin Belousov
3e07b6217f MFaesni r215427:
Only save FPU context when not executing in the context of the crypto
thread.

Tested by:	Mike Tancsa
MFC after:	1 week
2010-11-26 14:35:20 +00:00
Konstantin Belousov
1563ee36b9 Only save FPU context when not executing in the context of the crypto
thread.

Tested by:	Mike Tancsa
2010-11-17 16:17:15 +00:00
Dimitry Andric
235610273e Change two missed instances of 'retq' in aeskeys_i386.S to 'retl', which
makes it possible to assemble this file with gas from newer binutils.

Reviewed by:	kib
2010-10-13 17:55:53 +00:00
Pawel Jakub Dawidek
c979bd5e06 Fix two copy&paste bugs.
MFC after:	2 weeks
2010-09-25 10:32:52 +00:00
Pawel Jakub Dawidek
ac970319ff Add support for CRYPTO_AES_XTS.
MFC after:	1 week
2010-09-23 11:57:25 +00:00
Pawel Jakub Dawidek
30bd3bb07b Add support for CRD_F_KEY_EXPLICIT flag.
MFC after:	1 week
2010-09-23 11:46:53 +00:00
Pawel Jakub Dawidek
745eb0ccb6 Simplify code a bit.
MFC after:	1 week
2010-09-23 11:26:38 +00:00
Konstantin Belousov
5f270659fd Crypto(4) driver for AESNI.
The aeskeys_{amd64,i386}.S content was mostly obtained from OpenBSD,
no objections to the license from core.

Hardware provided by:	Sentex Communications
Tested by:	fabient, pho (previous versions)
MFC after:	1 month
2010-07-23 11:00:46 +00:00
Konstantin Belousov
04c49e68de Use the fpu_kern_enter() interface to properly separate usermode FPU
context from in-kernel execution of padlock instructions and to handle
spurious FPUDNA exceptions that sometime are raised when doing padlock
calculations.

Globally mark crypto(9) kthread as using FPU.

Reviewed by:	pjd
Hardware provided by:	Sentex Communications
Tested by:	  pho
PR:    amd64/135014
MFC after:    1 month
2010-06-05 16:00:53 +00:00
VANHULLEBUS Yvan
081b9301bf Changed to M_NOWAIT when reallocing psc_buf in padlock_sha_update(),
as we already hold the non sleepable crypto_driver_mutex.

Approved by:	gnn(mentor)
Obtained from:	NETASQ
MFC after:	2 weeks
2009-05-27 09:52:12 +00:00
Warner Losh
a4958494e8 identify routine takes driver_t *, not device_t *. 2009-02-05 19:30:28 +00:00
Jung-uk Kim
9045c73682 Connect padlock(4) to amd64 build for VIA Nano processors. 2009-01-12 19:23:46 +00:00
Alexander Motin
f2831a952d Avoid 256 integer divisions per rc4_init() call. Replace it with using
separate index variable.

It gives more then double rc4_init() performance increase on tested i386 P4.
It also gives about 15% speedup to PPTP VPN with stateless MPPE encryption
(by ng_mppc) which calls rc4_init() for every packet.
2008-12-16 13:58:37 +00:00
Philip Paeps
2bc989be4f Fix a potential NULL-pointer dereference in padlock(4).
Spotted by:	Coverity (via pjd)
MFC after:	1 week
2008-11-17 19:00:36 +00:00
Pawel Jakub Dawidek
b5207ec64a Simplify session selection/allocation. 2008-08-09 20:01:01 +00:00
Pawel Jakub Dawidek
ec7993f8b0 - Fix freeing session on newsession failure.
- Update copyright years.
2008-08-09 19:48:59 +00:00
Pawel Jakub Dawidek
f422e90330 Implify sessions freeing loop. 2008-08-09 19:47:19 +00:00
Pawel Jakub Dawidek
a05071e803 We don't have to drop a lock around malloc(M_NOWAIT). 2008-08-09 19:45:43 +00:00