Compare commits

...

1816 Commits

Author SHA1 Message Date
Milan Broz
1fae09d607 Update README. 2022-01-13 10:33:46 +01:00
Milan Broz
b1ef7cc3cd Fix reencrypt mangle test for older jq. 2022-01-13 10:12:45 +01:00
Milan Broz
bc2b38991b Version 2.3.7. 2022-01-13 07:08:03 +01:00
Milan Broz
3b35e438bc Add Release Notes 2022-01-13 07:08:03 +01:00
Milan Broz
4c0ae43f3a Update LUKS2 on-disk description. 2022-01-13 07:08:03 +01:00
Ondrej Kozina
d6649293a5 Allow reencryption metadata repair from cryptsetup. 2022-01-13 07:08:03 +01:00
Ondrej Kozina
624f3220a1 Add CRYPT_REENCRYPT_REPAIR_NEEDED flag.
crypt_reencrypt_status() returns this flag if old
online-reencrypt requirement is detected and reencryption
keyslot digest is missing.

crypt_reencrypt_init_by_passphrase() with same flag applied
repairs (upgrade) reencryption metadata so that
automatic reencryption recovery during activation
is again possible and reencryption operation can be resumed
post CVE-2021-4122 fix.
2022-01-13 07:08:03 +01:00
Milan Broz
2e44267891 Add reencryption mangle test 2022-01-13 07:08:03 +01:00
Ondrej Kozina
c75d740f9a Make reencryption flag and keyslot inseparable.
LUKS2 validation code now requires reencrypt keyslot together with
online-reencryption flag or none of those.
2022-01-13 07:08:03 +01:00
Ondrej Kozina
bc26c764c6 Rename LUKS2_keyslot_reencrypt_create function.
The function never writes on-disk. Also removed validation
function call-in since it will be called later before
writing on-disk and metadata does not have to be complete
at the moment of LUKS2_keyslot_reencrypt_allocate call.
2022-01-13 07:08:03 +01:00
Ondrej Kozina
ce8aab39ca Add segments validation for reencryption.
Effective segments during LUKS2 reencryption must
match key characteristics of backup segment
(cipher, sector_size, segment type).
2022-01-13 07:08:03 +01:00
Ondrej Kozina
d0169a303d Split requirements validation from config section validation. 2022-01-13 07:08:03 +01:00
Ondrej Kozina
f83e56e43e Expose json_segment_contains_flag to internal library. 2022-01-13 07:08:03 +01:00
Ondrej Kozina
4e98b65c04 Move requirement helpers for later changes. 2022-01-13 07:08:03 +01:00
Milan Broz
d45e6788e8 Add disable-luks2 reencryption configure option.
The option --disable-luks2-reencryption completely disable
LUKS2 reencryption code.

When used, the libcryptsetup library can read metadata with
reencryption code, but all reencryption API calls and cryptsetup
reencrypt commands are disabled.

Devices with online reencryption in progress cannot be activated.

This option can cause some incompatibilities. Please use with care.
2022-01-13 07:07:37 +01:00
Milan Broz
18cb1eeeb9 Do not run reencryption recovery when not needed. 2022-01-12 20:49:34 +01:00
Milan Broz
7eeb45537a Reenc keyslot must have key_size == 1. 2022-01-12 20:49:34 +01:00
Ondrej Kozina
60addcffa6 Fix CVE-2021-4122 - LUKS2 reencryption crash recovery attack
Fix possible attacks against data confidentiality through LUKS2 online
reencryption extension crash recovery.

An attacker can modify on-disk metadata to simulate decryption in
progress with crashed (unfinished) reencryption step and persistently
decrypt part of the LUKS device.

This attack requires repeated physical access to the LUKS device but
no knowledge of user passphrases.

The decryption step is performed after a valid user activates
the device with a correct passphrase and modified metadata.
There are no visible warnings for the user that such recovery happened
(except using the luksDump command). The attack can also be reversed
afterward (simulating crashed encryption from a plaintext) with
possible modification of revealed plaintext.

The problem was caused by reusing a mechanism designed for actual
reencryption operation without reassessing the security impact for new
encryption and decryption operations. While the reencryption requires
calculating and verifying both key digests, no digest was needed to
initiate decryption recovery if the destination is plaintext (no
encryption key). Also, some metadata (like encryption cipher) is not
protected, and an attacker could change it. Note that LUKS2 protects
visible metadata only when a random change occurs. It does not protect
against intentional modification but such modification must not cause
a violation of data confidentiality.

The fix introduces additional digest protection of reencryption
metadata. The digest is calculated from known keys and critical
reencryption metadata. Now an attacker cannot create correct metadata
digest without knowledge of a passphrase for used keyslots.
For more details, see LUKS2 On-Disk Format Specification version 1.1.0.
2022-01-12 20:49:34 +01:00
Milan Broz
e71c151ebb Rename reenc_keyslot_update to reencrypt_keyslot_update. 2022-01-12 20:49:34 +01:00
Milan Broz
6f2df7cd01 Rename luks2_reenc_context to luks2_reecrypt. 2022-01-12 20:49:34 +01:00
Milan Broz
8a7f590891 Rename crypt_get/set reenc_context to luks2_reencrypt. 2022-01-12 20:49:34 +01:00
Milan Broz
7319be8dad Rename LUKS2_reenc_status to LUKS2_reencrypt_status. 2022-01-12 20:49:34 +01:00
Milan Broz
5b07968c2d Rename LUKS2_reencrypt_status to LUKS2_reencrypt_get_params to avoid confusion. 2022-01-12 20:49:34 +01:00
Milan Broz
dc0ecd4288 Use LUKS2_reencrypt prefix for function defined in luks2.h.
This should clean up prefixes a little bit.
2022-01-12 20:49:34 +01:00
Milan Broz
286784c934 Do not expose json_object in luks2.h.
Later we can use different implementation of JSON parser.
Also define structs in one place.
2022-01-12 20:49:34 +01:00
Milan Broz
4b24e8e052 Remove json_object argument from area size checks.
These functions are internal to LUKS2 implementation.
2022-01-12 20:49:34 +01:00
Milan Broz
3f217dcacf Move LUKS2 internal functions to internal header.
This is the first step to remove json_object from internal API.
2022-01-12 20:48:07 +01:00
Milan Broz
c80fce5f47 Remove obsolete AC_HEADER_STDC macro.
This should be no longer used.
We do not support systems without standard headers anyway.
2022-01-12 18:50:12 +01:00
Milan Broz
3f4ce5d2b0 Update Readme.md. 2021-05-28 12:27:08 +02:00
Milan Broz
f95336e116 Prepare version 2.3.6.
Add Release notes.
2021-05-28 11:57:08 +02:00
Yuri Chornoivan
3753614517 po: update uk.po (from translationproject.org) 2021-05-28 09:59:30 +02:00
Yuri Kozlov
5fd96b75d3 po: update ru.po (from translationproject.org) 2021-05-28 09:59:30 +02:00
Jakub Bogusz
44aac4e5a3 po: update pl.po (from translationproject.org) 2021-05-28 09:59:30 +02:00
Hiroshi Takekawa
fbea879d1e po: update ja.po (from translationproject.org) 2021-05-28 09:59:30 +02:00
Frédéric Marchal
7012d031b6 po: update fr.po (from translationproject.org) 2021-05-28 09:59:30 +02:00
Roland Illig
a7f3065f6f po: update de.po (from translationproject.org) 2021-05-28 09:59:30 +02:00
Petr Pisar
f7fabbe141 po: update cs.po (from translationproject.org) 2021-05-28 09:59:30 +02:00
Klaus Zipfel
ac9a2c08e3 Fixing incorrect offsets for data/IV with TCRYPT system-encryption with a detached header
Related: #587
2021-05-26 09:36:32 +02:00
Milan Broz
bee77b2f35 Add note about --header use in TCRYPT format to man page.
Related: #587
2021-05-24 10:46:29 +02:00
Milan Broz
2d03ba3f4d Do not use Whirlpool hash in tests (some crypto backends do not implement it). 2021-05-23 11:13:44 +02:00
Milan Broz
29e4bca24b Increase interactive expect test timeout if runing under valgrind. 2021-05-22 10:27:00 +02:00
Milan Broz
2f9b22f5ff Update cryptsetup.pot. 2021-05-21 17:42:52 +02:00
Milan Broz
bbb6739d41 Set 2.3.6-rc0 version. 2021-05-21 17:30:40 +02:00
Мирослав Николић
d0c6eeea81 po: update sr.po (from translationproject.org) 2021-05-21 17:29:45 +02:00
Antonio Ceballos
4f982e9708 po: update es.po (from translationproject.org) 2021-05-21 17:29:28 +02:00
Milan Broz
df8135dfdf Check exit value for snprintf where it makes sense. 2021-05-21 14:54:00 +02:00
Milan Broz
280c821b9b Add some fixes and workarounds for gcc-11 static analyzer.
Not everything is a real bug (false positive rate is very high here),
but the code is actually more readable.
2021-05-21 14:44:15 +02:00
Ondrej Kozina
28dd0f5c05 Avoid LUKS2 decryption without detached header.
This is temporary hotfix for stable 2.3.6 release. The full
fix that requires new API will be provided in later 2.4.0
release.

For more info see issue #614.
2021-05-21 14:27:24 +02:00
Milan Broz
c7789719d8 integritysetup: mention maximal allowed key size
The error message and man page should contain this information.
2021-05-19 19:44:56 +02:00
Milan Broz
97e709788e Fix description of maximum passphrase size. 2021-05-19 19:40:59 +02:00
Milan Broz
3dbbc005d3 Add test for longer integritysetup keys. 2021-05-19 19:40:51 +02:00
Milan Broz
e1e3430c2c devmapper: avoid truncation of table features
This patch fixes several problems:
 - some optional features for dm-verity can be larger than pre-allocated buffer
 - device paths and other strings can be allocated dynamically
 - featured options with keys in dm-integrity are not wiped on stack
 - get rid of strncat()
 - always check return code of snprintf

Related #648
2021-05-19 19:35:51 +02:00
Andrii Pravorskyi
b354cdd9ad Add a note about CRC32 and other non-cryptographic checksums 2021-05-19 13:44:28 +02:00
Milan Broz
ed24d033d4 Allow CRYPT_BUSY also a a valid check for active device.
In ideal system nothing should touch test devices, but to make tests
more robust, we should expect that something is still scanning devices
after activation. So replace all checks for CRYPT_ACTIVE to allow
also CRYPT_BUSY.

(Fixes some problems seen in #633)
2021-05-19 13:44:25 +02:00
Milan Broz
5da8f5e710 Fix broken loopaes test.
We actually try to write file in /dev because the device is deactivated.

Broken since 2018 in 8728ba08e2
2021-05-19 13:44:21 +02:00
Milan Broz
800a8a4d5d Fix libintl detection for compiled tests.
Commit 99c4e83994 was incomplete.

See #633.
2021-05-19 13:44:19 +02:00
Milan Broz
0a06947e14 Add Blake2b and Blake2s hash support for crypto backend.
We support most recent crypto algorithms, so this
is only addition of the Blake hash family.

Kernel and gcrypt crypto backend supports all variants,
OpenSSL only Blake2b-512 and Blake2s-256.

There is no useable support for NSS and Nettle yet.

Crypto backend supports kernel notation e.g. "blake2b-512"
that is translated to the library backend names.
2021-05-19 13:44:15 +02:00
Milan Broz
418d068470 Allow to use backup header for tcrypt format.
TrueCrypt/VeraCrypt supports backup header, it seems to have
the same format as normal header.

Let's use --header option here, it can be used to unlock data partition
with header backup (open and dump commands).

Fixes: #587.
2021-05-19 13:43:37 +02:00
Milan Broz
9abe126016 Set devel 2.3.x version. 2021-05-19 13:08:46 +02:00
Milan Broz
59cf9969f9 Update cryptsetup.pot. 2021-03-11 12:56:15 +01:00
Milan Broz
98ec1e314a Prepare version 2.3.5. 2021-03-11 12:56:11 +01:00
Milan Broz
a9b327c12a Update Release notes version. 2021-03-11 12:55:25 +01:00
Milan Broz
eaa93a8116 Prepare Readme for version 2.3.5. 2021-03-11 12:55:09 +01:00
Milan Broz
018494b6b3 Add note for passwdqc change to release notes. 2021-03-11 11:38:21 +01:00
Dmitry V. Levin
3d7a0f741a Update libpasswdqc support
Starting with version 2.0.0, libpasswdqc can use memory allocation
when loading configuration that contains new optional parameters.
It's therefore recommended to free all memory allocated by
passwdqc_params_load using new passwdqc_params_free function
introduced in the same version of libpasswdqc.

[slightly modified by mbroz]
2021-03-11 11:38:11 +01:00
Milan Broz
3858b1815c Add stdbool.h include. 2021-03-09 20:47:39 +01:00
Yuri Chornoivan
4eca4e8fce po: update uk.po (from translationproject.org) 2021-03-09 20:40:51 +01:00
Yuri Kozlov
39abe23e0e po: update ru.po (from translationproject.org) 2021-03-09 20:40:51 +01:00
Jakub Bogusz
80faafea48 po: update pl.po (from translationproject.org) 2021-03-09 20:40:51 +01:00
Hiroshi Takekawa
f658ea6ba4 po: update ja.po (from translationproject.org) 2021-03-09 20:40:51 +01:00
Frédéric Marchal
fa0a24f726 po: update fr.po (from translationproject.org) 2021-03-09 20:40:51 +01:00
Roland Illig
24abdf4e72 po: update de.po (from translationproject.org) 2021-03-09 20:40:51 +01:00
Petr Pisar
677572a425 po: update cs.po (from translationproject.org) 2021-03-09 20:40:51 +01:00
Milan Broz
30d6a8a8f9 Update 2.3.5 release notes.
And reformat it for strange problems with mail signature (line length).
2021-03-09 20:40:45 +01:00
Milan Broz
9fc40d35d3 Remove superfluous CONST_CAST.
It only confuses cppcheck.
2021-03-09 20:39:58 +01:00
Milan Broz
5a032abc33 Fix partial reads from TTY (interactive terminal).
Some stable kernels started to return buffer from terminal
in partial buffers of maximal size 64 bytes.

This breaks all passphrases longer than 64 characters entered
through interactive input (for all crypto formats).

(The problem is probably fixed in more recent kernels, but
the read() call can always return a partial read here.)

This patch also fixes wrong password limit, the last character
of passphrase of maximal size was never handled.
Now the maximal passphrase length is really 512 characters.

Fixes: #627.
2021-03-09 20:36:44 +01:00
Milan Broz
6df6c0a363 Update Readme.md. 2021-03-04 13:16:44 +01:00
Milan Broz
e2e57e5776 Update cryptsetup.pot. 2021-03-04 11:35:50 +01:00
Milan Broz
3d8cb44c61 Fix typo. 2021-03-04 11:27:33 +01:00
Milan Broz
05dad56f75 Add release notes for 2.3.5-rc. 2021-03-03 22:21:24 +01:00
Milan Broz
69361fec1c Add a note about FEC calculation to veritysetup manual. 2021-03-03 12:20:51 +01:00
Milan Broz
4e0398aef0 Add final list of failures to valgrind-check test target. 2021-03-03 12:11:24 +01:00
Ondrej Kozina
51ab9da665 Fix reencryption recovery tests w/ cipher_null. 2021-03-02 17:25:00 +01:00
Milan Broz
855a232403 Add disappeared device test. 2021-03-02 16:44:18 +01:00
Milan Broz
96241cea6a Check internal device functions for NULL device.
Most of these functions already works even with device=NULL.

There can be some rare situations when this call could happen,
so be safe always.
(Like initialization for a device that disappears during init.)

Also see
https://bugzilla.redhat.com/show_bug.cgi?id=1932946
2021-03-02 16:44:11 +01:00
Milan Broz
9e5c87b449 Fix allocation of volume key in LUKS1 open_key.
This function should not return allocated key on error path.

Recent patch (suspend/resume) introduced a memory leak because of this.
2021-02-26 00:16:06 +01:00
Ondrej Kozina
7d1b40a3a6 Silent error messages in tests. 2021-02-26 00:16:06 +01:00
Ondrej Kozina
969be38a7a Add error message when suspending wrong device.
In case user tries to suspend LUKS data device instead
of dm-crypt mapping.

See issue#622.
2021-02-26 00:16:06 +01:00
Ondrej Kozina
93382071a5 Fix luksResume when called on non-LUKS device. 2021-02-26 00:16:06 +01:00
Ondrej Kozina
426a8b9df0 Fix reversed condition in LUKS2 api test.
get_luks2_offsets is based on get_luks_offsets from api-test.c
but for some odd reason 'metadata_device' parameter had reversed
meaning.
2021-02-26 00:16:06 +01:00
Ondrej Kozina
83811b5ea9 Fix keyslots size overflow when device too small.
It properly failed but debug message was confusing.
Now it fails later properly with "device too small"
error message.
2021-02-26 00:16:06 +01:00
Ondrej Kozina
56a01574ff Allow LUKS resume for device with cipher_null. 2021-02-26 00:16:06 +01:00
Ondrej Kozina
c68cd0a483 Unify crypt_resume_by internal code. 2021-02-26 00:16:06 +01:00
Ondrej Kozina
b2135a75e2 Do not upload VK in keyring when data cipher is null. 2021-02-26 00:16:06 +01:00
Ondrej Kozina
91e8f5ffd9 Remove redundant check.
It can't be non-LUKS2 device at this branching.
2021-02-26 00:16:06 +01:00
Ondrej Kozina
855628f796 Add tests for cipher_null suspend/resume. 2021-02-26 00:16:06 +01:00
Milan Broz
db8ce3f818 verity: run FEC check even if root hash fails.
The error correction can fix even problem with root hash.

For now, always return fail if initial check of root hash failed.

FIXME: The FEC verify code need to be rewritten to repair only
blocks where hash is wrong and the re-check hash after recovery,
inclkuding root hash.

Now we do not check hash after FEC recovery. The Reed-Solomon
decoder can then "repair" code wrongly if parity is too damaged.

For now, the information about FEC repaired errors is only
advisory, it does not mean device is fully repaireable.
2021-02-26 00:16:05 +01:00
Milan Broz
973474503a verity: do not process hash image if it is empty. 2021-02-26 00:16:05 +01:00
Milan Broz
4e2561df6d verity: do not calculate hash offset if hash area is not used.
Sometimes device is so small that there is only root hash needed
and the hash area is not used.
2021-02-26 00:16:05 +01:00
Milan Broz
b01ec20703 veritysetup: do not increase hash image size if hash area is not used.
Do not write more than needed header if hash area is not used later.

All space in hash area is then used in FEC calculation, so it makes
no sense to add unused area.
2021-02-26 00:16:05 +01:00
Ondrej Kozina
ca1b41cf96 Extend LUKS2 reencryption tests w/ cipher_null. 2021-02-26 00:16:05 +01:00
Ondrej Kozina
7825e0d4a6 Bypass keyring activation flag if cipher is null. 2021-02-26 00:16:05 +01:00
Ondrej Kozina
c8c28cf6dd Use crypt_is_cipher_null check where possible. 2021-02-26 00:16:05 +01:00
Ondrej Kozina
fb8aa6d03b Fix default xts mode key size in reencryption.
Reencryption did not take into account adjusted xts
key size configuration option. This patch fix the
issue by using same logic as in luksFormat with xts
mode selected for data encryption.
2021-02-26 00:16:05 +01:00
Ondrej Kozina
207383782a Fix reencryption test on systems w/o keyring. 2021-02-26 00:16:05 +01:00
Ondrej Kozina
f25a1c92ec Prefer default cipher when reencrypting cipher_null device.
By default when reencrypting LUKS2 device we regenerate only
the volume key. But if the device was 'encrypted' by cipher_null
this change did not make sense. The key was always empty.

Change the behaviour so that unless user specifies --cipher
parameter on command line, we change data encryption cipher
to default when old segment cipher was cipher_null.
2021-02-26 00:16:05 +01:00
Ondrej Kozina
44a9e7aa62 Improve key handling with cipher_null in reencryption. 2021-02-26 00:16:05 +01:00
Ondrej Kozina
27eee9cfcb Add debug message for activated cipher_null device. 2021-02-26 00:16:05 +01:00
Ondrej Kozina
196477d194 Replace bogus cipher_null keyslots before reencryption.
By mistake LUKS2 allowed keyslots 'not-so-encrypted' by
cipher_null (only explicitly requested by --cipher or
--keyslot-cipher parameters). If we encounter
such old key during reencryption let's replace the cipher
for new keyslot with default LUKS2 keyslot cipher.
2021-02-26 00:16:05 +01:00
Ondrej Kozina
1e68d73bc3 Fix device comparison for dm-crypt with cipher_null.
Do not compare volume keys if segment uses cipher_null.
The key is ignored by lower layer (internal libdevmapper)
anyway.
2021-02-26 00:16:05 +01:00
Ondrej Kozina
17bb1e2fdd Do not upload vk in keyring for cipher_null segment.
It does not make sense to upload volume keys in
kernel keyring if segment cipher is cipher_null.
The real volume_key is thrown away and replaced
with empty key anyway.
2021-02-26 00:16:05 +01:00
Ondrej Kozina
ba7fd45ba6 Fix broken detection of null cipher in LUKS2.
This bug enabled to create LUKS2 keyslots encrypted by
cipher_null when explicitely requested by user. LUKS2
was never meant to allow keyslot encryption with
cipher_null. cipher_null is meant for debug purposes
only as a segment cipher.
2021-02-26 00:16:05 +01:00
Ondrej Kozina
7058b81bb6 Move cipher_null check in internal function crypt_is_cipher_null.
Also removes tools helper so that we keep check in one place.
2021-02-26 00:16:05 +01:00
Ondrej Kozina
b40018860b Add tests for various keyslot cipher null bugs. 2021-02-26 00:16:05 +01:00
Milan Broz
e97ac9f58c Get rid of off_t integers and use uint64_t.
Also move uint64 multiplication overflow check to internal library.
2021-02-26 00:16:05 +01:00
Milan Broz
75447d0d80 Fix debug message displaying required hash device size.
If located on the same device with hashes, offset must be subtracted.
(Also there could be one block more for superblock.)
2021-02-26 00:16:05 +01:00
Milan Broz
c760ae36ea Get rid of the long paramete list in FEC verity function.
Also params struct will be needed in following patch.
2021-02-26 00:16:05 +01:00
Milan Broz
dbd20776bc Fix dm-verity FEC calculation if stored in the same image with hashes.
FEC (Forward Error Correction) data should cover the whole data area,
hashes (Merkle tree) and optionally additional metadata (located after hash area).

Unfortunately, if FEC data is stored in the same file as hash, the calculation
wrongly used the whole file size thus overlaps with FEC area itself.
This produces unusable and too large FEC data.

(There is not a problem if FEC image is a separate image.)

This patch fixes the problem, introducing FEC blocks calculation as:

 -If hash device is in a separate image, metadata covers the whole rest of the image after hash area.
  (Unchanged behaviour.)

 -If hash and FEC device is in the image, metadata ends on the FEC area offset.

This should probably fix several issues reported with FEC wrong calculations.

Fixes: #554
2021-02-26 00:16:05 +01:00
Milan Broz
3ebbceaef2 Fix veritysetup exit code for bad root hash with FEC enabled.
If FEC was enabled, the error for bad root hash was replaced
by error correction (datga were ok, only root hash was wrong).

Do not run recovery test if root hash is incorrect.
2021-02-26 00:16:05 +01:00
Milan Broz
d733e4d0e8 Add a missing stdbool include. 2021-02-26 00:16:05 +01:00
Milan Broz
4d6d6edcff Backport device_is_identical() changes needed for following patch. 2021-02-26 00:13:48 +01:00
Milan Broz
1380efa1c6 Fix compat interactive test to run with valgrind too. 2021-02-08 21:43:40 +01:00
Milan Broz
bce9d695e3 Coverity workaround for tainted warnings.
Password can be any string and the function allocates
string properly, so mark it is as sanitized.
2021-02-07 20:05:03 +01:00
Milan Broz
bea6e0da74 Fix an error path memory leak. 2021-02-07 20:02:20 +01:00
Vojtech Trefny
e064406f85 bitlk: Fix parsing startup key metadata
This fixes multiple issues found by coverity in the startup key
code and also makes the parsing less complicated -- we don't need
to loop through all metadata entries in the BEK file if we are
expecting only one metadata entry of a specific type.
2021-02-07 20:02:20 +01:00
Milan Broz
3d58f480ee Avoid "output may be truncated" gcc warnings.
These are false positives and gcc internal detection of this
pattern seems to be broken again.

In this path we must avoid memcpy the whole buffer, it can contain
some bytes after null char, so use MIN/strlen here.
2021-02-07 20:02:20 +01:00
Milan Broz
660edf7959 Remove WARNING from the debug message. 2021-02-07 20:02:20 +01:00
Milan Broz
312efd8582 Remove redundant EOL in the previous patch. 2021-02-07 20:02:20 +01:00
Milan Broz
ec657332c6 Rephrase lockinging dir warning and move it to debug level.
System should later provide safe transition to tempdir configuration.
2021-02-07 20:02:20 +01:00
Milan Broz
e123263975 Fix LUKS1 repair code.
We cannot trust possibly broken keyslots metadata here through LUKS_keyslots_offset().
Expect first keyslot is aligned, if not, then manual repair is neccessary.

(This situation happen if partition table signarture overwrites slot 4 area).

Also, if keyslot order is different, current repair code does not work properly
(this can happen only with downconverting LUKS2 device).
2021-02-07 20:02:20 +01:00
Milan Broz
e8f2bb4a1a Disable alternative backends in CI build for now.
These will run in release time only.
2021-02-07 20:02:20 +01:00
Ondrej Kozina
6e71e2d6ed Fix crypt_keyslot_change_by_passphrase tokens bug.
crypt_keyslot_change_by_passphrase broke token references
to keyslots while existing keyslot id was different from
new keyslot id.
2021-02-07 20:02:20 +01:00
Ondrej Kozina
2f6698d1a7 Test crypt_keyslot_change_by_passphrase does not break tokens. 2021-02-07 20:02:12 +01:00
Milan Broz
d20929194f Fix previous commit error condition.
This hints actually failed even if return code was OK.
2021-02-07 20:00:16 +01:00
Milan Broz
0a6f89cfa6 Fix dm-integrity HMAC recalculation problem.
This patch adds support for Linux kernel (since version 5.11) dm-integrity
fixes that disables integrity recalculation if keyed algorithms (HMAC) is used.

Original dm-integrity superblock version <=4 is recalculation offset
field not protected by HMAC. An attacker can move this pointer and force
the kernel to recalculate the data area, ignoring original HMAC tags.

N.B. dm-integrity was not intended to protect against intentional changes.
Better use authenticated encryption (AEAD) in combination with dm-crypt.
It is designed to protect against random data corruption caused by hardware
or storage medium faults.

Despite that, we try to keep the system secure if keyed algorithms are used.

There are two possible keyed algorithms in dm-integrity - algorithm used
to protect journal and superblock (--journal-integrity) and algorithms
for protecting data (--integrity).
The dm-integrity superblock is guarded by --journal-integrity, so if you want
to protect data with HMAC, you should always also use HMAC for --journal-integrity.
The keys are independent. If HMAC is used for data but not for the journal,
recalculation is disabled by default.

For new kernel dm-integrity, the HMAC option also uses salt in superblock
to avoid an easy way to distinguish that the HMAC key is the same for two devices
(if data are the same).

The new HMAC and superblock are enabled automatically if the kernel supports it
(you can see superblock version 5 and fix_hmac flag in dump command).

If you need to use (insecure) backward compatibility, then two new integritysetup
options are introduced:

 Use --integrity-legacy-recalc (instead of --integrity-recalc) to allow recalculation
 on legacy devices.

 Use --integrity-legacy-hmac in format action to force old insecure version
 format (with HMAC).

Libcryptsetup API also introduces flags
  CRYPT_COMPAT_LEGACY_INTEGRITY_HMAC and
  CRYPT_COMPAT_LEGACY_INTEGRITY_RECALC
to set these through crypt_set_compatibility() call.
2021-02-07 19:58:49 +01:00
Milan Broz
c74f17c6e7 Fix copy & paste typo in integrity test. 2021-02-07 19:52:32 +01:00
Ondrej Kozina
616dd5a304 Allow bitlk tests to run with valgrind. 2021-02-07 17:37:18 +01:00
Ondrej Kozina
79442539c7 Remove bogus valgrind suppressions. 2021-02-07 17:37:06 +01:00
Ondrej Kozina
92b24fd758 Fix popt string related memory leaks.
All POPT_ARG_STRING pointers must be free'd manually
in calling application. This is unfortunately not documented
well behaviour of popt and we were having memory leaks due to
it.
2021-02-07 17:36:56 +01:00
Ondrej Kozina
4a43a2773a Add utilities cleanup routine. 2021-02-07 17:36:47 +01:00
Ondrej Kozina
74c943c352 Drop unreachable code and useless conditions.
integrity_alg variable can not be NULL.
2021-02-07 17:36:38 +01:00
Ondrej Kozina
bc49c83ace Remove const from all opt_ string declarations.
Those variables contain pointers to dynamically alocated memory.
2021-02-07 17:36:24 +01:00
Ondrej Kozina
ed28583f17 Do not pass constant strings to option string variables.
This is part of effort to eliminate all memory leaks related
to options parsing in popt but for that to work we must avoid
passing constant strings to free().
2021-02-07 17:36:10 +01:00
Ondrej Kozina
5345a73ca0 Group all string options variables together. 2021-02-07 17:35:23 +01:00
Ondrej Kozina
36f424ce71 Properly prefix all popt variables in veritysetup. 2021-02-07 17:28:09 +01:00
Milan Broz
a757d84b91 Update Copyright year. 2021-02-07 16:09:13 +01:00
Luca Boccassi
255464b0ae verity: fix strncpy boundary check compiler warning
lib/verity/verity.c: In function ‘VERITY_write_sb’:
lib/verity/verity.c:200:2: warning: ‘strncpy’ specified bound 32 equals destination size [-Wstringop-truncation]
  strncpy(algorithm, params->hash_name, sizeof(sb.algorithm));
2021-02-07 16:09:13 +01:00
Luca Boccassi
4c350f4d72 verity: improve crypt_activate_by_signed_key debug log
Check if a signature is actually available before logging that the
volume is being activated with a signed key.
2021-02-07 16:09:13 +01:00
Ondrej Kozina
7cca38632f Add pedantic check for key helpers arguments. 2021-02-07 16:09:13 +01:00
Lars Wendler
d8bbfb118b cryptsetup.8: Fix no_write_workqueue option name
It's called --perf-no_write_workqueue

Signed-off-by: Lars Wendler <polynomial-c@gentoo.org>
2021-02-07 16:09:13 +01:00
Arno Wagner
178bc9ee39 Update FAQ: Clarified statement about block sizes in 5.16 2021-02-07 16:09:13 +01:00
Milan Broz
7d4d1baaa7 Fix some formatting and typos in man page. 2021-02-07 16:09:13 +01:00
Milan Broz
f82c1bf90f Remove obsolete tpm-luks project link from FAQ. 2021-02-07 16:09:13 +01:00
Milan Broz
8d856d4e17 Add lore.kernel.org list archive link. 2021-02-07 16:09:13 +01:00
Samanta Navarro
fb49d9630d lib: always clear size in crypt_safe_free
Writing into allocated memory right before calling free can be optimized
away by smart compilers. To prevent this, a volatile access must be
performed. This happens already in crypt_safe_memzero.

It was difficult to provoke GCC to remove the assignment, but I was able
to find a way to prove the theory:

* Build cryptsetup with: CFLAGS="-flto -O3 -g" ./configure --enable-static
* Create main.c:

#include <libcryptsetup.h>

int
main(void) {
        char *x = crypt_safe_alloc(64);
        crypt_safe_free(x);
        return 0;
}

* Build the program with: gcc -O3 -flto -static -o main main.c -lcryptsetup
* Disassemble: objdump -d main

My output on an amd64 system is:

0000000000401670 <main>:
  401670:       41 54                   push   %r12
  401672:       bf f0 03 00 00          mov    $0x3f0,%edi
  401677:       55                      push   %rbp
  401678:       48 83 ec 08             sub    $0x8,%rsp
  40167c:       e8 ff 4d 01 00          callq  416480 <__libc_malloc>
  401681:       48 85 c0                test   %rax,%rax
  401684:       74 2f                   je     4016b5 <main+0x45>
  401686:       48 c7 00 e8 03 00 00    movq   $0x3e8,(%rax)
  40168d:       4c 8d 60 08             lea    0x8(%rax),%r12
  401691:       48 89 c5                mov    %rax,%rbp
  401694:       be e8 03 00 00          mov    $0x3e8,%esi
  401699:       4c 89 e7                mov    %r12,%rdi
  40169c:       e8 4f 76 01 00          callq  418cf0 <explicit_bzero>
  4016a1:       48 8b 75 00             mov    0x0(%rbp),%rsi
  4016a5:       4c 89 e7                mov    %r12,%rdi
  4016a8:       e8 43 76 01 00          callq  418cf0 <explicit_bzero>
  4016ad:       48 89 ef                mov    %rbp,%rdi
  4016b0:       e8 3b 54 01 00          callq  416af0 <__free>
  4016b5:       48 83 c4 08             add    $0x8,%rsp
  4016b9:       31 c0                   xor    %eax,%eax
  4016bb:       5d                      pop    %rbp
  4016bc:       41 5c                   pop    %r12
  4016be:       c3                      retq
  4016bf:       90                      nop

You can see that the memory allocation and explicit_bzero calls were not
optimized away. But the size assignment disappeared.

Compiling without -O3 or without -flto does not inline the calls and
keeps the assignment. Also the shared library shipped with my
distribution has the assignment.
2021-02-07 16:09:13 +01:00
Samanta Navarro
7866e71d6f Fix typos.
Typos found with codespell.
2021-02-07 16:09:13 +01:00
Samanta Navarro
d2ee949d88 lib: fix utils_safe_memory function comments. 2021-02-07 16:09:13 +01:00
Ondrej Kozina
3a29cbbf5d Add missing translation anotation. 2021-02-07 16:09:13 +01:00
Milan Broz
51bf5435f9 Enable Travis test for GOST crypto in VeraCrypt (install GOST external kernel crypto modules). 2021-02-07 16:09:13 +01:00
Vojtech Trefny
505effe085 bitlk: Fix key sizes for BITLK encryption types
It makes more sense to return "real" key sizes, e.g. 256 bit for
AES-XTS 128 and 256/512 bit for AES-CBC with Elephant which has
a separate key for the Elephant mode.
2021-02-07 16:09:12 +01:00
Vojtech Trefny
82f8fb653c bitlk: Allow running bitlk_metadata_free with NULL 2021-02-07 16:09:12 +01:00
Joerg Kastning
829a2379a1 Update cryptsetup.8
* Improved information about calling luksFormat on devices.
2021-02-07 16:09:12 +01:00
Joerg Kastning
b5894ce1ab Update cryptsetup.8
* Rename "BASIC COMMANDS" to "BASIC ACTIONS"
 * Changed a sentence saying that luksFormat would work on unmapped luks containers, only.
 * Insert 6 examples of using cryptsetup for luks containers
2021-02-07 16:09:12 +01:00
lixiaokeng
1bc6caceb1 lib: fix memory leak in crypt_pbkdf_check
There is a memory leak when PBKDF2_temp > UINT32_MAX. Here,
we change return to goto out to free key.

Signed-off-by: Lixiaokeng <lixiaokeng@huawei.com>
Signed-off-by: Linfeilong <linfeilong@huawei.com>
2021-02-07 16:09:12 +01:00
lixiaokeng
78f33946f1 lib: fix potential segfault in LUKS2_token_buffer_free
The value of h may be NULL. Check it vefore visiting its
memeber to avoid segfault.

Signed-off-by: Lixiaokeng <lixiaokeng@huawei.com>
Signed-off-by: Linfeilong <linfeilong@huawei.com>
2021-02-07 16:09:12 +01:00
lixiaokeng
0d90efac88 lib: fix potential segfault in _crypt_cipher_crypt
The value of header may be NULL. Check it to avoid
segfault.

Signed-off-by: Lixiaokeng <lixiaokeng@huawei.com>
Signed-off-by: Linfeilong <linfeilong@huawei.com>
2021-02-07 16:09:12 +01:00
lixiaokeng
82490aaaa3 lib: fix potential segfault in _keyslot_repair
The value of vk may be NULL in _keyslot_repair. It will
be dereferenced in LUKS_generate_phdr. Check it to avoid
segfault.

Signed-off-by: Lixiaokeng <lixiaokeng@huawei.com>
Signed-off-by: Linfeilong <linfeilong@huawei.com>
2021-02-07 16:09:12 +01:00
lixiaokeng
782f4c5029 lib: check return value of malloc in BITLK_read_sb
The return value of malloc vmk and params->fvek is not
checked. Here we add checking.

Signed-off-by: Lixiaokeng <lixiaokeng@huawei.com>
Signed-off-by: Linfeilong <linfeilong@huawei.com>
2021-02-07 16:09:12 +01:00
Ondrej Kozina
d63d399c17 Fix cryptsetup resize using LUKS2 tokens.
Fix a bug where cryptsetup needlessly asked for passphrase
even though volume key was already unlocked via LUKS2 token.

Fixes: #601.
2021-02-07 16:09:12 +01:00
dofrupisla
745c75b5b0 Fix typo 2021-02-07 16:09:12 +01:00
Samanta Navarro
1d615cf6dd fix typo in manual page 2021-02-07 16:09:12 +01:00
Vojtech Trefny
7f0ddcbed4 bitlk: Show better error when trying to open an NTFS device
Both BitLocker version 1 and NTFS have the same bootcode eb 52 90
so when trying to open an NTFS device user will get error message
saying that BitLocker version 1 is not supported. This patch
switches to check the superblock first to inform user that the
device is not a BITLK device.
2021-02-07 16:09:12 +01:00
Vojtech Trefny
efa7c4574c bitlk: Fix test image for startup key
We zero data parts of the test images to make them as small as
possible and for the latest startup key image I deleted bigger
portion of the NTFS header by accident which caused older blkid
on CentOS/RHEL 6 to not identify the NTFS filesystem on the
cleartext device.
2021-02-07 16:09:12 +01:00
Milan Broz
e2b4479543 bitlk: Fix a compiler warning. 2021-02-07 16:09:12 +01:00
Vojtech Trefny
7c23bdb868 bitlk: Add support for startup key protected VMKs (keyslots)
Fixes: #588
2021-02-07 16:09:12 +01:00
Vojtech Trefny
fa5d46592e bitlk: Try all keyslots even if some checks fails for passphrase
We can't easily distinguish between a passphrase and other
protectors like recovery passphrase or startup key during
activation so we can't stop when attempted passphrase activation
fails because a binary startup key can't be conveted to UTF-16
during KDF.
2021-02-07 16:09:12 +01:00
Joe Richey
e5e09d889b Include correct type definition in .h files
Right now, cryptsetup makes an attempt to include the correct
definitions in all of its header files, allowing the headers to
compile regardless of the context in which they are included.

A few files were missed, this change fixes them by adding the minimal
set of #includes needed to get them to compile.

Signed-off-by: Joe Richey <joerichey@google.com>
2021-02-07 16:09:12 +01:00
Milan Broz
7dbd007ac1 Print a visible error if requesting resize on unsupported format.
Fixes: #571.
2021-02-07 16:09:12 +01:00
Ondrej Kozina
dbb80e41c7 Do not print opt_io_size warning needlessly.
In fallback path min_io_size and opt_io_size could be
same and the warning was confusing.
2021-02-07 16:09:12 +01:00
Milan Broz
33cc4739da Print warning if msgfmt utility from gettext is missing.
User have to install gettext package or manually disable translation
using --disable-nls.

Also remove links to GNU packages ftp, all of these should by provided
by native distro packaging systems.

Fixes: #591.
2021-02-07 16:09:12 +01:00
Milan Broz
5518198f97 Always store dm-verity hash algorithm in superblock in lowercase.
Fixes: #586.
2021-02-07 16:09:12 +01:00
Milan Broz
1a81925764 Fix disaplay of dm-integrity recalculating sector in dump command.
Fixes: #578.
2021-02-07 16:09:12 +01:00
Milan Broz
15df5904f2 Fix a memleak in blockwise test. 2021-02-07 16:09:12 +01:00
Milan Broz
07a06f2f40 Set 2.3.5-rc0 version. 2021-02-07 16:09:12 +01:00
Мирослав Николић
fd94f036c1 po: update sr.po (from translationproject.org) 2021-02-07 16:09:12 +01:00
Мирослав Николић
03607db1f8 po: update sr.po (from translationproject.org) 2021-02-07 16:09:12 +01:00
Josef Andersson
c2fcc7aebd po: update sv.po (from translationproject.org) 2021-02-07 16:09:12 +01:00
Josef Andersson
8dbb72e296 po: update sv.po (from translationproject.org) 2021-02-07 16:09:12 +01:00
Antonio Ceballos
513e88fd77 po: update es.po (from translationproject.org) 2021-02-07 16:09:12 +01:00
Antonio Ceballos
8360a85169 po: update es.po (from translationproject.org) 2021-02-07 16:09:12 +01:00
Roland Illig
b56a450a31 po: update de.po (from translationproject.org) 2021-02-07 16:09:12 +01:00
Milan Broz
569b485d02 Update Readme.md. 2020-09-03 20:45:35 +02:00
Milan Broz
bd888e30a6 Prepare version 2.3.4. 2020-09-03 19:11:40 +02:00
Milan Broz
b86c51afeb Add stable version release notes. 2020-09-03 19:10:45 +02:00
Yuri Chornoivan
56f47d3899 po: update uk.po (from translationproject.org) 2020-09-03 16:37:27 +02:00
Yuri Kozlov
284672c081 po: update ru.po (from translationproject.org) 2020-09-03 16:37:18 +02:00
Jakub Bogusz
6f6b54a5fd po: update pl.po (from translationproject.org) 2020-09-03 16:37:07 +02:00
Hiroshi Takekawa
154c344115 po: update ja.po (from translationproject.org) 2020-09-03 16:36:58 +02:00
Frédéric Marchal
cccb7780ec po: update fr.po (from translationproject.org) 2020-09-03 16:36:48 +02:00
Petr Pisar
aa762d5cc1 po: update cs.po (from translationproject.org) 2020-09-03 16:36:38 +02:00
Milan Broz
68cc46fc22 Update cryptsetup.pot. 2020-08-27 23:29:51 +02:00
Milan Broz
06bd23d120 Remove a gcc warning. 2020-08-27 21:24:37 +02:00
Ondrej Kozina
2f4990868e Explicitly terminate cipher strings during down conversion. 2020-08-27 14:18:17 +02:00
Ondrej Kozina
03213ac230 Fix posible buffer overflows in LUKS conversion.
cipher[31] and cipher_mode[31] buffers were passed to
crypt_parse_name_and_mode() routine where sscanf(s, "%31[^-]-%31s",
cipher, cipher_mode) was called.

In corner case it could cause terminating 0 byte written beyond
respective arrays.
2020-08-27 14:17:58 +02:00
Ondrej Kozina
fb1b287773 Add test for LUKS2 segments validation code fix. 2020-08-27 14:17:38 +02:00
Ondrej Kozina
7ceaf3f313 Simplify validation code a bit.
Keep it simple. If there's not enough memory we can't validate
segments. The LUKS2 specification does not recommend to continue
processing LUKS2 metadata if it can not be properly validated.
2020-08-27 14:17:29 +02:00
Ondrej Kozina
3f20b04e42 Avoid needlessly large allocations in LUKS2 validation code.
In case LUKS2 backup segment creates gap in between last regular
segment and backup segment report invalid metadata imediately. We stop
on first error so there's no need to allocate large memory on heap
(we may ran with mlock(MCL_FUTURE) set).

Example:
- total segments count is 3
- regular segments have keys "0" and "1"
- first backup segment has key "42"
2020-08-27 14:17:20 +02:00
Milan Broz
82e6ca7202 Set devel 2.3.x version. 2020-08-26 15:45:20 +02:00
Milan Broz
8a170d0e80 Build branch v2.3.x in Travis. 2020-08-26 15:44:51 +02:00
Milan Broz
72be05c817 Fix error message in previous commit. 2020-08-26 15:41:48 +02:00
Milan Broz
b79ccb782b Ignore optimal-io if not aligned to minimal page size
This values is bogus on some systems and causes wrong alignment
for data area. Just ignore it there.

Fixes: #585.
2020-08-26 15:41:44 +02:00
Milan Broz
9c8c636ece Print a warning if API test generates too long log. 2020-08-26 15:41:35 +02:00
Tobias Stoeckmann
63a5bd5ef6 Fixed some typos.
The large text block happened due to reformat. It's just addition
of "the" in front of problem, i.e. "If this is _the_ problem, ..."
2020-08-26 15:41:29 +02:00
Tobias Stoeckmann
e75f5de2ed Check segment gaps regardless of heap space.
Segments are validated in hdr_validate_segments. Gaps in segment keys
are detected when collecting offsets. But if an invalid segment is very
large, larger than count, it could happen that cryptsetup is unable to
allocate enough memory, not giving a clue about what actually is the
problem.

Therefore check for gaps even if not enough memory is available. This
gives much more information with debug output enabled.

Obviously cryptsetup still fails if segments are perfectly fine but not
enough RAM available. But at that stage, the user knows that it's the
fault of the system, not of an invalid segment.
2020-08-26 15:41:24 +02:00
Milan Broz
6df1a69430 Add some descriptive output to device test - performance flags. 2020-08-26 15:40:23 +02:00
Milan Broz
e7ca35091c Add no_read/write_wrokqueue to dm-crypt options.
These performance options, introduced in kernel 5.9, configures
dm-crypt to bypass read or write workqueues and run encryption
synchronously.

Also support persistent storage of these flags for LUKS2.
2020-08-26 15:39:26 +02:00
Milan Broz
03ecfe3478 Support panic_on_corruption option form dm-verity.
The panic_on_corruption switch is available since kernel 5.9 (dm-verity 1.7.0).
2020-08-26 15:26:01 +02:00
Ondrej Kozina
f5bf9ef9fa Add test for reencryption with --master-key-file argument. 2020-08-26 14:10:23 +02:00
Ondrej Kozina
f61eb8b427 Add API test for reencryption with specific new key. 2020-08-26 14:09:55 +02:00
Ingo Franzki
a4f78e1c98 Support online reencryption for PAES cipher.
Signed-off-by: Ingo Franzki <ifranzki@linux.ibm.com>

(With few adjustments by Ondrej Kozina)
2020-08-26 14:03:32 +02:00
Vojtech Trefny
d1c3ad2703 bitlk: Set sector size to 512 when unknown/zero
Fixes: #584
2020-08-26 13:57:48 +02:00
Milan Broz
d7279eeda1 Use Ubuntu 20.04 in Travis CI builds. 2020-08-26 13:57:16 +02:00
Milan Broz
9c2d918474 libdevmapper: always return EEXIST if a task fails because the device already exists
Allows concurrent opens to return a usable error instead of EINVAL
2020-08-26 13:55:59 +02:00
Milan Broz
16aec64d1b Fix a problem in integritysetup if a hash algorithm has dash in the name.
If users want to use blake2b/blake2s, the kernel algorithm name
includes dash - like "blake2s-256".

Because we use dash as a separator, this patch adds an exception
for this case.

Fixes: #581.
2020-08-26 13:54:53 +02:00
Milan Broz
04d2ff7689 tcrypt: Support activation of devices with a larger sector.
TrueCrypt/VeraCrypt always use 512-bytes sector for encryption,
but for devices with a larger native sector it stores this value in header.

This patch allows activating of such devices, basically ignoring
the mentioned sector size in header (it only must be multiple
of 512-bytes sector).

Fixes: #580.
2020-08-26 13:54:34 +02:00
Milan Broz
0cd7cac03f Fix crypto backend to properly handle ECB mode.
Despite it should be never used, it should still work :)

Bug introduced in version 2.3.2.
2020-08-26 13:53:55 +02:00
Milan Broz
b2c1ec2f83 Use the most recent image in travis.yml. 2020-08-26 13:53:42 +02:00
Ondrej Kozina
a15008d876 Do not create excessively large headers.
When creating LUKS2 header with specified --offset much larger
then LUKS2 header size we needlessly also wipe (allocate up to
--offset) much larger file than needed.
2020-08-26 13:52:57 +02:00
Francesco Turco
ac535923e0 fix capitalization 2020-08-26 13:52:16 +02:00
Francesco Turco
f695e155ec fix typos 2020-08-26 13:52:08 +02:00
Francesco Turco
9412d9a0f1 use HTTPS for URLs 2020-08-26 13:51:22 +02:00
Vojtech Trefny
57eba0d6f5 bitlk: Fix reading key data size in the decrypted key material
We've assumed that first 4 bytes of the decrypted key data is the
size of the key + metadata. Looks like this isn't true and only
first two bytes contain the size and the other two bytes are
unknown data, possibly related to reencryption and/or passphrase
change.

Fixes: #575
2020-08-26 13:50:39 +02:00
Milan Broz
4a9862a666 Add option for large IV to storage wrapper.
Also implement some test vectors and use the same limits
as in dm-crypt (IV offset alignnment).
2020-08-26 13:49:54 +02:00
Milan Broz
74e94e7bdd Prepare version 2.3.3. 2020-05-28 11:26:27 +02:00
Milan Broz
72cd628357 Update cryptsetup.pot. 2020-05-24 23:37:31 +02:00
Yuri Chornoivan
45367e4a34 po: update uk.po (from translationproject.org) 2020-05-24 23:22:15 +02:00
Yuri Kozlov
7d76831250 po: update ru.po (from translationproject.org) 2020-05-24 23:22:15 +02:00
Jakub Bogusz
d2ff3fc2ee po: update pl.po (from translationproject.org) 2020-05-24 23:22:15 +02:00
Hiroshi Takekawa
537b8454a4 po: update ja.po (from translationproject.org) 2020-05-24 23:22:15 +02:00
Frédéric Marchal
a7c71b90b1 po: update fr.po (from translationproject.org) 2020-05-24 23:22:15 +02:00
Antonio Ceballos
e0be3deb3a po: update es.po (from translationproject.org) 2020-05-24 23:22:15 +02:00
Roland Illig
5490476d84 po: update de.po (from translationproject.org) 2020-05-24 23:22:15 +02:00
Petr Pisar
90865eb887 po: update cs.po (from translationproject.org) 2020-05-24 23:22:15 +02:00
Milan Broz
157f71d78e Add IV vector tests.
This test checks IV wrapper implemented in userspace.
2020-05-24 23:19:46 +02:00
Milan Broz
176fee54e4 Require both keyslot cipher ane key size options.
If not specified together, cryptsetup silently fail.
2020-05-15 22:07:52 +02:00
Milan Broz
61f4363ed7 Implement EBOIV in userspace storage wrapper.
The EBOIV initialization vector is intended to be used
internally with BitLocker devices (for CBC mode).
It can be used in some specific cases for other devices.

This patch adds userspace implementation duplicating
the same EBOIV as the dm-crypt kernel.

Fixes: #562
2020-05-15 17:33:06 +02:00
Vojtech Trefny
86cc67e081 bitlk: Fix memory leak when freeing bitlk_fvek structure 2020-05-15 17:15:07 +02:00
Milan Broz
dcc9888350 Update pot file. 2020-05-15 10:56:36 +02:00
Мирослав Николић
6af6a424b4 po: update sr.po (from translationproject.org) 2020-05-15 10:44:11 +02:00
Milan Broz
e1ceb63023 Set devel version. 2020-05-15 10:43:52 +02:00
Milan Broz
4eb7193a27 Support large IV count option for plain device
The iv_large_sector option is supported in dm-crypt since introduction
of larger sectors encryption.
It counts Initialization Vector (IV) in larger sector size (if set) instead
of 512 bytes sectors.

This option does not have any performance or security impact, but it can be
used for accessing incompatible existing disk images from other systems.
(It is used internally in BitLocker compatibily code).

This patch allows it to be used for plain type device, so users
can manually map foreign disk images.
Only open action with plain device and sector size > 512 bytes is supported.
2020-05-15 10:37:33 +02:00
Arno Wagner
e6ff3b37a4 sync with wiki 2020-05-12 17:21:49 +02:00
Milan Broz
c3e095969f Skip 4k Bitlk images (some older systems cannot activate them). 2020-05-07 09:15:45 +02:00
Vojtěch Trefný
2e345a1059 bitlk: Fix working with 4k sector devices
We need to use the iv_large_sectors flag and correct sector size
for the crypt segments for these devices. Used sector size is
read from the device header. This commit also adds two new test
images with 4k sectors.

Fixes: #557
2020-05-06 21:20:26 +02:00
Milan Broz
e759ebe0bd Better explain --persistent option for flag removals.
Also fix a error message that was not displayed
properly for the persistent discard flag incompatibility.

Fixes: #558.
2020-05-02 17:09:59 +02:00
Milan Broz
533b874590 Update Readme.md. 2020-04-30 17:12:37 +02:00
Milan Broz
780ebb4680 Version 2.3.2. 2020-04-30 16:56:53 +02:00
Yuri Chornoivan
02a579af59 po: update uk.po (from translationproject.org) 2020-04-29 08:49:39 +02:00
Yuri Kozlov
9bcf1c4b8d po: update ru.po (from translationproject.org) 2020-04-29 08:49:39 +02:00
Jakub Bogusz
dec9b4f7c7 po: update pl.po (from translationproject.org) 2020-04-29 08:49:39 +02:00
Hiroshi Takekawa
4701842829 po: update ja.po (from translationproject.org) 2020-04-29 08:49:39 +02:00
Frédéric Marchal
488b4bdbe8 po: update fr.po (from translationproject.org) 2020-04-29 08:49:39 +02:00
Antonio Ceballos
c8d886b422 po: update es.po (from translationproject.org) 2020-04-29 08:49:39 +02:00
Roland Illig
a83bbd2e92 po: update de.po (from translationproject.org) 2020-04-29 08:49:39 +02:00
Petr Pisar
c3a47cb72f po: update cs.po (from translationproject.org) 2020-04-29 08:49:39 +02:00
Ondrej Kozina
0971e55d4d Fix gcc warning in unbound key dump. 2020-04-29 08:49:25 +02:00
Ondrej Kozina
6f45c7a8ac Drop duplicit check on --refresh option. 2020-04-29 08:49:04 +02:00
Arno Wagner
c567d852a5 Sync to wiki (added 10.9) 2020-04-28 15:28:49 +02:00
Arno Wagner
0b38128e21 sync to Wiki 2020-04-27 16:27:50 +02:00
Arno Wagner
b9daa8b2ee Fixes to 6.10, should state situation with LUKS2
accurately now.
2020-04-26 18:56:28 +02:00
Arno Wagner
878c7173c3 typo 2020-04-26 18:34:59 +02:00
Arno Wagner
f69b980dcf Sync to Wiki Version.
Rework to differentiate LUKS1 from LUKS2 and
info for LUKS2 added.
2020-04-26 18:22:25 +02:00
Milan Broz
33378792ca Prepare rc0 for version 2.3.2. 2020-04-17 10:48:04 +02:00
Milan Broz
c7a2b4d5e3 Fix a line break in veritysetup man page. 2020-04-16 15:33:25 +02:00
Milan Broz
4a077fc2c9 Rephrase warning a little bit. 2020-04-16 15:30:35 +02:00
Ondrej Kozina
f309ec21d7 Allow dump of LUKS2 unbound keyslot.
Adds option to dump content of LUKS2 unbound keyslot
in to a file:

'cryptsetup luksDump --unbound --master-key-file /file -S 12 /dev/luks2'

or to terminal:

'cryptsetup luksDump --unbound -S 12 /dev/luks2'

Parameters -S (specific keyslot) is mandatory with --unbound.

Fixes: #549
2020-04-16 15:29:24 +02:00
Milan Broz
e261cf7481 Add issue templates.
(Note: default is in project setting as a copy of Bug.md)
2020-04-15 18:06:07 +02:00
Milan Broz
fa8390b23e Remove redundant EOL in some usage messages.
With recent changes in log wrapper these messages were forgotten to fix.
2020-04-15 13:14:13 +02:00
Milan Broz
af89858d47 Use fsync explicitly for the device check in cryptsetup-reencrypt.
With direct-io removal in previous patch we should ensure the header
change hits the real device immediatelly.
2020-04-15 13:10:36 +02:00
Ondrej Kozina
e6a3569743 Avoid name clash with newer json-c library.
This is partial revert of previous commit and also
fixes wrong decision to name our internal helpers with
json_object prefix.
2020-04-14 17:24:57 +02:00
Björn Esser
604abec333 Add support for upcoming json-c 0.14.0.
* TRUE/FALSE are not defined anymore.  1 and 0 are used instead.
  * json_object_get_uint64() and json_object_new_uint64() are part
    of the upstream API now.
2020-04-13 14:25:18 +02:00
Milan Broz
790666ffb0 Add support for allow_discrads for dm-integrity.
Kernel 5.7 adds support for optional discard/TRIM operation
for dm-integrity (available only for internal hash, not for LUKS2
with integrity).

This patch adds support for the new option.
2020-04-09 00:03:42 +02:00
Milan Broz
c9f6ccff9f Ignore not relevant TOCTOU warning in previous commit. 2020-04-03 13:30:54 +02:00
Milan Broz
02b3f42500 Fix open flags in cryptsetup-reencrypt header access check.
We should not use O_DIRECT, it does not work tin in-memory fs.

Also never use O_EXCL on regular files, it is undedfined according
to open() documentation.

Fixes: #529.
2020-04-03 12:59:50 +02:00
Vojtěch Trefný
e10724accb bitlk: Correctly free memory in passphrase_to_utf16
Fixes: #547
2020-04-01 08:02:09 +02:00
Milan Broz
5b68dec43a Adjust IV size in cipher benchmark.
The IV size for benchmark can be autodetected (for known ciphers).
For other algorithms user still can specify own values.
2020-03-23 18:46:59 +01:00
Milan Broz
9d13da0050 Set devel version. 2020-03-23 18:46:28 +01:00
Ondrej Kozina
1e94425279 Remove unused parameter from crypto_backend_init. 2020-03-20 11:32:57 +01:00
Milan Broz
fc48f9bc08 Workaround for verity FEC test.
Threre asre some situatiuoins when randomized image is nor repairable
by FEC data. Let's use completely deterministic image creation (fixed salt and uuid).

FIXME: The FEC Reed-Solomon code is doing something strange here, this
kind of erasure should be always repairable.
2020-03-19 10:14:45 +01:00
Milan Broz
2eb25910a1 Fix Veracrypt compatible support for longer passphrases.
Previous fix for longer passhphrases increased maximal
passphrase length even if it was not needed, for example
if used with SHA256 hash in combination with keyfiles.

This patch tries to fix the problem, so some older volumes
can be opened again.

Also some test images are added for regression testing.

Fixes: #542.
2020-03-16 17:09:41 +01:00
Milan Broz
1dab341b33 Update Readme.md. 2020-03-12 09:59:00 +01:00
Milan Broz
1f7ed87e6c Prepare version 2.3.1. 2020-03-12 09:39:20 +01:00
Milan Broz
c59ea422cc Add 2.3.1 release notes. 2020-03-10 16:03:53 +01:00
Ondrej Kozina
0bcb71f742 Add experimental warning in bitlk man section. 2020-03-10 12:26:26 +01:00
Yuri Chornoivan
7e38a3386e po: update uk.po (from translationproject.org) 2020-03-09 08:18:30 +01:00
Jakub Bogusz
c25b5ef215 po: update pl.po (from translationproject.org) 2020-03-09 08:18:30 +01:00
Hiroshi Takekawa
72fb507de2 po: update ja.po (from translationproject.org) 2020-03-09 08:18:30 +01:00
Frédéric Marchal
45c4c95b98 po: update fr.po (from translationproject.org) 2020-03-09 08:18:30 +01:00
Antonio Ceballos
e8861d1043 po: update es.po (from translationproject.org) 2020-03-09 08:18:30 +01:00
Roland Illig
c48fcb743b po: update de.po (from translationproject.org) 2020-03-09 08:18:30 +01:00
Joe Hansen
d5d732ddf4 po: update da.po (from translationproject.org) 2020-03-09 08:18:29 +01:00
Petr Pisar
f83bd5cdf6 po: update cs.po (from translationproject.org) 2020-03-09 08:18:29 +01:00
Milan Broz
76c87c628f Update cryptsetup.pot. 2020-03-09 08:18:16 +01:00
Milan Broz
fa125a354d Set version to 2.3.1-rc0. 2020-03-08 10:56:09 +01:00
Aaron Rogers
f184b54796 Improve hexdigest printing for large key-size 2020-03-01 16:17:27 +01:00
Vojtěch Trefný
75925fb2f7 bitlk: Strip extra newline from potential recovery keys
There might be a trailing newline added by the text editor when
the recovery passphrase was passed using the '--key-file' option
so we'll remove it before trying to use the passphrase.
2020-03-01 16:11:42 +01:00
Antonio Ceballos
b780228ade po: update es.po (from translationproject.org) 2020-03-01 16:07:42 +01:00
Ondrej Kozina
91c012eff0 Do not wipe device with no integrity profile.
With '--integrity none' we performed useless full
device wipe.

Fixes: #539.
2020-02-27 16:23:06 +01:00
Milan Broz
05d45c6948 Check for dm_device_get_name.
And fail dependency scan if not available.

Currently this call uses syfs DM extensions, these are
usually not available anyway on such old systems.
2020-02-21 12:13:04 +01:00
Milan Broz
a2c13fbc48 Used CLOCK_MONOTONIC in benchmark on ancient systems. 2020-02-21 10:42:47 +01:00
Milan Broz
16c7aab99b Fix some (ancient) compiler warnings. 2020-02-21 10:30:39 +01:00
Milan Broz
0cf5e309a0 Print warning if running without O_CLOEXEC. 2020-02-21 10:23:07 +01:00
Milan Broz
b5fbd682f2 Move fcntl.h to internal defines and check for O_CLOEXEC. 2020-02-21 10:10:11 +01:00
Milan Broz
90e04b0046 Remove O_CLOEXEC from block utils.
It is not needed here, used only in utilities.
2020-02-21 10:09:09 +01:00
Milan Broz
329f6562c2 Add autoconf check for O_CLOEXEC. 2020-02-21 10:08:17 +01:00
Milan Broz
852bad1ef4 Fix acompiler warning with --disable-blkid. 2020-02-21 08:28:55 +01:00
Henrik Grimler
aa44a61ab2 lib/Makemodule.am: convert some spaces to tabs 2020-02-21 08:25:41 +01:00
Milan Broz
3e237cb490 Detect separate libiconv library.
This patch should fix compilation issues on distributions with
iconv implemented in a separate library (instead libc internally).
2020-02-21 08:20:14 +01:00
Milan Broz
7b206fb13d Workaround for dm-integrity kernel table bug.
Some kernels show invalid dm-integrity table if suberblock
contains "recalculate" bit.

We can workaround that by setting recalculate option in table
(kernel uses bits from superblock anyway), so the table displayed
is always correct.

Fixes: #538
2020-02-20 14:19:57 +01:00
Milan Broz
8f7e898341 Print error message if LUKS1 keyslot cannot be processed.
If crypto backend is missing support for hash algorithms used
in PBKDF2 during slot derivatiom the fail was not visible.

Print at least error message to user in this case.

Fixes: #536
2020-02-20 14:19:53 +01:00
Ondrej Kozina
7499d9f245 Return -EINVAL when validation fails.
LUKS2_hdr_validate() returns positive integer on error. Replace returned
value with negative errno instead so that failed upconversion stops
sooner. It failed anyway but debug messages were misleading.
2020-02-19 11:18:46 +01:00
Ondrej Kozina
ba6e6f051a Properly align LUKS2 keyslots area on conversion.
If LUKS1 payload offset (data offset) is not aligned to
4KiB we create unaligned keyslots area in LUKS2 metadata
during upconversion. Unaligned keyslots area is not valid
from LUKS2 perspective. Fix it by properly aligning future
keyslots area and also check if LUKS1 keyslots area fit
in the new one.

Fixes: #534.
2020-02-17 22:19:39 +01:00
Ondrej Kozina
d4f4dfb54f Validate LUKS2 in-before moving keyslots on conversion.
During LUKS2 upconversion we moved binary keyslots area before
validating future LUKS2 header. If later LUKS2 validation failed
for some reason keyslots were already moved to new offsets and
LUKS1 offsets were therefore invalid. Following effort to unlock
such device failed because keyslots were efectively corrupted.

See issue #534.
2020-02-17 22:18:58 +01:00
Ondrej Kozina
3e7dedaf99 Minor code cleanup. 2020-02-17 22:18:36 +01:00
Milan Broz
f18cd7ae81 tcrypt: Suport VeraCrypt 128 bytes passwords
VeraCrypt now allows passwords of maximal length 128 bytes
(compared to legacy TrueCrypt where it was limited by 64 bytes).

This patch implements support for such a passphrases for TCRYPT format.

The whole extension seems to be quite dubious, the original TCRYPT
passphrase limit was IMO because of internal block length in PBKDF2
(SHA1/SH256 block size is 64 bytes), this patch make sense for SHA512
where the block size is 128 bytes.

Another strange thing is enlarging keyfile pool according to real
entered password size.

Fixes: #532.
2020-02-17 22:08:47 +01:00
Milan Broz
0ae4fcf8eb Update Readme.md. 2020-02-02 17:37:24 +01:00
Milan Broz
d3d1e30c7c Prepare version 2.3.0. 2020-02-02 16:58:29 +01:00
Ondrej Kozina
47d0cf495d Fail crypt_keyslot_get_pbkdf for inactive LUKS1 keyslot.
With LUKS1 we returned pbkdf values even for inactive keyslot.
Only iterations count was wrong. Remaining values are not
specific keyslot bound with LUKS1.

Fixes: #528.
2020-01-31 13:52:38 +01:00
Ondrej Kozina
2e883f9d91 Fix misleading hint in integritysetup man page.
--journal-crypt example values are not accepted by
crurrent integritysetup.

Fixes: #510.
2020-01-30 17:58:54 +01:00
Vojtech Trefny
af0c30e3ea bitlk: Add a test image for the EOW format
The image was created by pausing the encryption in progress.
2020-01-30 09:57:43 +01:00
Vojtech Trefny
da5a35356a bitlk: Remove unused constant 2020-01-30 09:57:43 +01:00
Vojtech Trefny
d98cc3bb6c bitlk: Do not allow activation of EOW and unknown devices
We currently do not support these BITLK devices.
2020-01-30 09:57:43 +01:00
Vojtech Trefny
9697f17b9d bitlk: Do not allow to activate devices in an unknown state
According to Dislocker, two unknown numbers in the FVE metadata
indicate "state" of the BITLK device. We were able to identify
only one of the states and we shouldn't allow activating devices
in other states for now.
2020-01-30 09:57:43 +01:00
Vojtech Trefny
ce3a9d172d bitlk: Fix reading metadata entries total length
FVE metadata header contains size of the header itself + size of
the metadata entries so we need to take this value and substract
48 (length of the FVE metadata header).
2020-01-30 09:57:39 +01:00
Yuri Kozlov
4448ddc488 po: update ru.po (from translationproject.org) 2020-01-26 10:15:41 +01:00
Yuri Chornoivan
b77d3c66ae po: update uk.po (from translationproject.org) 2020-01-17 14:34:16 +01:00
Jakub Bogusz
2debdfead5 po: update pl.po (from translationproject.org) 2020-01-17 14:34:16 +01:00
Benno Schulenberg
b168c65fa1 po: update nl.po (from translationproject.org) 2020-01-17 14:34:16 +01:00
Hiroshi Takekawa
2b46d171db po: update ja.po (from translationproject.org) 2020-01-17 14:34:16 +01:00
Frédéric Marchal
64c131d132 po: update fr.po (from translationproject.org) 2020-01-17 14:34:16 +01:00
Roland Illig
678a251858 po: update de.po (from translationproject.org) 2020-01-17 14:34:16 +01:00
Petr Pisar
bf9d2f6cb0 po: update cs.po (from translationproject.org) 2020-01-17 14:34:16 +01:00
Vojtěch Trefný
61f5dcb11e Return correct data offset for BITLK in crypt_get_data_offset
First part of the encrypted data will be always directly after
the header.

Fixes: #518
2020-01-17 14:02:12 +01:00
Milan Broz
e4387d2bd1 Update Readme.md. 2020-01-12 12:48:19 +01:00
Milan Broz
48906f354e Remove EOL in debug message. 2020-01-12 12:30:36 +01:00
Milan Broz
1ddc098e43 Prepare version 2.3.0-rc0. 2020-01-12 12:14:27 +01:00
Milan Broz
165e6c234c Fix some error and debug messages.
Use BITLK as format name.

Avoid using doesn't -> does not.
2020-01-11 22:10:59 +01:00
Milan Broz
1be631f43f Add status flag for verity device with signature.
This patch adds CRYPT_VERITY_ROOT_HASH_SIGNATURE flag to verity info.

Veritysetup status now display "with signature" if an active
device was activated with root hash signature.
2020-01-11 19:57:39 +01:00
Vojtěch Trefný
f5f34c2f50 bitlk: Add recovery passphrases for Elephant test images 2020-01-08 09:23:06 +01:00
Vojtěch Trefný
33f3619e98 bitlk: Update testing images for AES-CBC with Elephant
Images now contain valid NTFS filesystem after opening and the
test data also contain sha256sum of the opened device.
2020-01-05 17:09:16 +01:00
Vojtěch Trefný
3720b66d00 bitlk: Fix getting FVEK for AES-CBC 128 bit with Elephant
For this 128 bit Elephant the key data is 512 bit (2 * 156 bit,
same as for 256 bit Elephant) so we need to adjust reading the
key to not include the empty "parts" of the key.
2020-01-05 17:07:15 +01:00
Milan Broz
864bbc5472 Fix string leak in BITLK attribute name handling. 2020-01-03 13:44:57 +01:00
Milan Broz
080566a1fd Update copyright year. 2020-01-03 13:04:55 +01:00
Milan Broz
d9766037a3 Fix some extended compiler warnings. 2020-01-03 12:29:49 +01:00
Milan Broz
02821adc47 Fix a signed/unsigned comparison compiler warning. 2020-01-03 11:26:44 +01:00
Milan Broz
7b08fd4b7d Remove undeeded version test for BITLK compat tests.
Otherwise it starts failing with dm-crypt version bump.
2020-01-03 10:23:28 +01:00
Milan Broz
0505c70be2 Implement BITLK status info.
Cryptsetup status <device> should print info about active device.

Also fix mistake in BITLK volume key size (should return bytes, not bits).
2020-01-03 10:14:47 +01:00
Jaskaran Khurana
f247038e65 Add --root-hash-signature parameter to veritysetup
Optional parameter root hash signature is added that can be added to
veritysetup.

The signature file is opened and the signature is added to the keyring.

The kernel will use the signature to validate the roothash.

Usage: veritysetup open <data_device> name <hash_device> <root_hash> --root-hash-signature=<roothash_p7_sig_file>

Signed-off-by: Jaskaran Khurana <jaskarankhurana@linux.microsoft.com>
Signed-off-by: Luca Boccassi <luca.boccassi@microsoft.com>

[Original patch rewritten by Milan Broz]
2020-01-02 13:08:21 +01:00
jbit
d7667e9e6e bitlk: Support for name strings in VMK metadata 2020-01-02 08:54:19 +00:00
Luca Boccassi
188cb114af Add support for verity in crypt_volume_key_get and use it in status
Other APIs use the root hash in place of keys when using verity
devices, so do the same for crypt_volume_key_get to allow users
to retrieve the root hash of an active verity device.
Use it in veritysetup status to print the root hash.

[Patch slightly modified by Milan Broz]
2019-12-31 21:44:50 +01:00
Milan Broz
35c49ababf Fix some compiler warnings. 2019-12-31 17:49:38 +01:00
Ondrej Kozina
faafe09bd0 Use crypt_volume_key_next where appropriate. 2019-12-31 17:37:33 +01:00
Milan Broz
a0e87c9420 Calculate hash integrity size instead of requiring an explicit tag size.
When integritysetup formats a device with hash or HMAC integrity checksums,
it requires explicitly tag size entry from a user (or default value).

This leads to confusion and shortened tags.

This patch calculates tag size according to real hash output, and
if tag size is specified, it warns if these values differ.

Fixes: #492.
2019-12-31 17:37:33 +01:00
Milan Broz
d9d39f1812 po: update pot file 2019-12-31 12:36:39 +01:00
Milan Broz
82af225742 Add bitlk compat test to distro tar. 2019-12-31 12:30:44 +01:00
Milan Broz
919f4df1a7 Remove wip-bitlocker branch from CI. 2019-12-31 12:20:06 +01:00
Milan Broz
71a1698bf2 Add bitlk.c to translation. 2019-12-31 11:16:01 +01:00
Milan Broz
a987dd95b8 Remove unused bitlk params structure. 2019-12-30 21:57:42 +01:00
Milan Broz
ab6ab8e65c Fix BITLK command aliases descriptions. 2019-12-30 21:53:06 +01:00
Milan Broz
3b28d66410 Add BitLocker man page extentsion. 2019-12-30 21:53:06 +01:00
Milan Broz
eee46ef2f4 Detect support for BitLocker EBOIV and Elephant diffuser.
If kernel is missing support, print a more friendly error.
2019-12-30 21:53:06 +01:00
Vojtěch Trefný
3c189b4183 bitlk: Fix displaying key length in bitlkDump 2019-12-30 21:53:06 +01:00
Vojtěch Trefný
fd5ab0edf7 bitlk: Add Smart Card protected VMKs
Test image protected with smart card is included.
2019-12-30 21:53:06 +01:00
Vojtěch Trefný
420387a7a5 bitlk: Ignore unknown metadata entries for unsupported VMKs
VMKs (keyslots) protected with a smart card or TPM have some
additional metadata entries that are currently unkwnon. We can
safely ignore these because we don't support unlocking the device
using these VMKs so we should still be able to parse the metadata
and unlock the device using other VMKs like the recovery password.
2019-12-30 21:53:06 +01:00
Milan Broz
fc740f8b6d Simplify bitlk test and be sure to load dm-crypt module. 2019-12-30 21:53:06 +01:00
Vojtech Trefny
834059ddfa Do not hardcode number of DM segments for BitLocker devices
Sometimes there is no gap between the metadata so we don't want to
create a dm-crypt segment there.
2019-12-30 21:53:06 +01:00
Vojtěch Trefný
5ec2fbcd38 Allow empty passphrases when opening BitLocker devices
It's probably not possible to create a BitLocker device with an
empty passphrase but we want to support it. And it's definitely
better to ask for the passphrase again instead of returning
ENOMEM.
2019-12-30 21:53:06 +01:00
Vojtěch Trefný
2fbf5cd79f Covert the BitLocker test images to sparse images 2019-12-30 21:53:06 +01:00
Vojtěch Trefný
64ebe95751 Check sha256 sums of the bitlk images in tests 2019-12-30 21:53:06 +01:00
Vojtěch Trefný
77109b3a33 Edit BitLocker test images to be compatible with older blkid
We need to keep the mirror NTFS MFT too because older versions of
blkid check it too.
2019-12-30 21:53:06 +01:00
Vojtěch Trefný
b43429e684 Fix parsing BitLocker metadata on Big Endian architectures 2019-12-30 21:53:06 +01:00
Vojtěch Trefný
97e39f0744 Fix displaying error for not supported BitLocker key decryption
'crypt_bitlk_decrypt_key' can also fail because of wrong
passphrase and other reasons.
2019-12-30 21:53:06 +01:00
Vojtěch Trefný
fad592b512 Fix open on devices with no supported VMKs 2019-12-30 21:53:06 +01:00
Milan Broz
565de3c536 Fix check for bitlk iv overflow in crypto backend. 2019-12-30 21:53:06 +01:00
Milan Broz
c802269ea3 Bitlk: fix some additional gcc warnings. 2019-12-30 21:53:06 +01:00
Milan Broz
06268963fb Bitlk: clean up some inlcudes and warnings. 2019-12-30 21:53:06 +01:00
Milan Broz
2227797691 Bitlk: move test for older blkid. 2019-12-30 21:53:06 +01:00
Milan Broz
f0888c1fe0 Add AEAD define on older kernel headers. 2019-12-30 21:53:06 +01:00
Milan Broz
eda2e62589 Add other backends (Nettle, NSS) for Bitlk decryption (through kernel wrapper). 2019-12-30 21:53:06 +01:00
Milan Broz
494d8ec04c Add kernel backend for Bitlk key decryption. 2019-12-30 21:53:06 +01:00
Milan Broz
bb8088ca0f Another fix for ancient systems. 2019-12-30 21:53:06 +01:00
Milan Broz
26f4bc39fc Fix tes for very old bash. 2019-12-30 21:53:06 +01:00
Milan Broz
025e4d9fc6 Fix bitlk test on older systems. 2019-12-30 21:53:06 +01:00
Milan Broz
b2774d57ba Bitlk: Propagare errno from key decryption. 2019-12-30 21:53:06 +01:00
Milan Broz
51edfb4ec9 Bitlk: add gcrypt key backend. 2019-12-30 21:53:06 +01:00
Milan Broz
79019b1ced Bitlk: Move crypt key handling to crypto backend. 2019-12-30 21:53:06 +01:00
Vojtěch Trefný
bc87140b5b Do not declare control variables in for loops
C89 doesn't like this.
2019-12-30 21:53:06 +01:00
Vojtěch Trefný
1c5251069b Define UUID_STR_LEN not defined in older versions of libuuid 2019-12-30 21:53:06 +01:00
Vojtěch Trefný
0b6dfefcec Add tests and test images for BitLocker 2019-12-30 21:53:06 +01:00
Vojtěch Trefný
a9e32c55c0 Fix parsing BitLocker metadata from latest Windows
Newest version added a new metadata entry to the recovery
passphrase protected VMK containing two new timestamps. We are
ignoring these for now.
2019-12-30 21:53:06 +01:00
Vojtěch Trefný
a494228407 Do not try to activate partially decrypted BitLocker devices 2019-12-30 21:53:06 +01:00
Vojtěch Trefný
9932b5fc5c Do not try to activate BitLocker devices with diffuser
The CBC mode with Elephant Diffuser is currently not supported
by DM crypt.
2019-12-30 21:53:06 +01:00
Vojtěch Trefný
966ba44a33 Add support for opening of BitLocker devices
It's now possible to open/activate the device using passphrase or
recovery passphrase. Support is limited to devices using encryption
modes supported in the DM crypt module (AES-XTS and AES-CBC).
2019-12-30 21:53:06 +01:00
Vojtěch Trefný
62c872eb49 Add support for parsing BitLocker metadata
Currently only support for metadata version 2 is implemented.
2019-12-30 21:53:06 +01:00
Milan Broz
434fee2e13 Add empty template for BITLK device type.
Also add DM_ZERO type for multi-segment mapping.
2019-12-30 21:53:06 +01:00
Andrei Shevchuk
d3f829c065 Add note on integrity mode not supporting discards (TRIM) 2019-12-23 14:31:46 +00:00
Ondrej Kozina
83934bdcf3 Clarify LUKS2 error message related to reencryption.
Original messages could evoke reencryption is currently
in progress. That was inaccurate because code only
detected flag marking such device is in transition state
from metadata pov. We should not imply anything about
running processes. That's detected via reencryption locks.
2019-11-28 16:38:53 +01:00
Ondrej Kozina
3691add163 Minor code cleanup. 2019-11-28 16:38:53 +01:00
Ondrej Kozina
cc7a9e4607 Fix lookup function for keyslot-segment assignment.
In reencryption we can have more than 3 segments.
2019-11-28 16:38:53 +01:00
Ondrej Kozina
943fa69da6 Reduce code duplication in LUKS2 keyslot handling. 2019-11-28 16:38:53 +01:00
Ondrej Kozina
3bef291184 Unify low level LUKS2 keyslot unlock and verify code.
Function is now unused, see later commit
2019-11-28 16:38:53 +01:00
Ondrej Kozina
7316c53b04 Remove redundant digest id to key assignement. 2019-11-28 16:38:52 +01:00
Ondrej Kozina
5e1d1e1850 Add missing validation when unlocking keys for reencryption.
We missed keyslot json validation when unlocking all keys necessary
for reencryption. Also assign appropriate verified digest id to
keys in volume key structure.
2019-11-28 16:38:52 +01:00
Ondrej Kozina
e52c8e148c Remove unnecessary query for volume key size.
In fact we need only stored key size in examined keyslot. It's valid for
default segment volume keys and in case of non-default segment
keys it always returns -1 and fallbacks to stored key size query
instead.
2019-11-28 16:38:52 +01:00
Ondrej Kozina
7eb47f3db1 Split reencryption locking in two variants. 2019-11-28 16:38:52 +01:00
Milan Broz
ec59d31d04 Remove AEAD tests dor MORUS and AEGIS ciphers.
These variants were removed from mainline kernel.
2019-11-25 23:16:53 +01:00
Milan Broz
ddd15b63b2 Add backward compatibility flags API.
We need to have some way hot to configure old integrity devices
with legacy padding.

For now, also use in tests to not fail checksum with new kernel.
2019-11-25 23:14:58 +01:00
Milan Broz
e91b35a53d Print info and warning if dm-integrity fix_padding is set.
The dump operation prints the fix_padding flag if set.

Also try to print warning if an old kernel is used and th edevice
cannot be activated because of missing fix padding support.
2019-11-25 19:48:54 +01:00
Mikulas Patocka
fb4079aa4d cryptsetup: add support for the "fix_padding" option
This patch adds support for fixed padding to cryptsetup.

* Cryptsetup will accept superblocks version 4.
* If the dm-integrity target version is greater than 1.4, cryptsetup will
  add a flag "fix_padding" to the dm-integrity target arguments.

There is still one quirk: if we have an old libdm without
DM_DEVICE_GET_TARGET_VERSION and if dm-integrity module is not loaded,
cryptsetup will not detect that it can use the "fix_padding" option.

Signed-off-by: Mikulas Patocka <mpatocka@redhat.com>
2019-11-24 20:58:47 +01:00
Milan Broz
48b203a134 Add crypt_resume_by_volume_key() function.
If user has volume key available, LUKS device can be resumed
directly using provided volume key.
No keyslot derivation is needed, only key digest is checked.

Fixes: #502.
2019-11-24 18:04:41 +01:00
Milan Broz
2746fd708f Implement active device suspend info.
Add CRYPT_ACTIVATE_SUSPENDED bit to crypt_get_active_device() flags
that informs the caller that device is suspended (luksSuspend).

Fixes: #501.
2019-11-24 16:56:26 +01:00
Ondrej Kozina
684f43d84d Clarify confirmation prompt text.
Fixes: #473
2019-11-22 15:34:16 +01:00
Milan Broz
6b1be52e6b Fix LUKS1 format if pkbdf benchamr is disabled.
We use minimum iteration for key digest in this case
(the same already used in LUKS2).

Fixes: #478.
2019-11-22 13:02:41 +01:00
Ondrej Kozina
de6258d366 Allow --test-passphrase for detached header alone.
Before this fix we required data device specified on cmd line
even though it was not necessary for testing passphrase.

Fixes: #487.
2019-11-19 14:36:06 +01:00
Ondrej Kozina
5e4dbf33be Allow --key-file option in legacy offline encryption.
The option was ignored for LUKS1 encryption initialization.

Fixes: #491.
2019-11-19 12:41:14 +01:00
Milan Broz
b03cb3f3d8 Export memory safe functions.
Make crypt_safe_alloc/realloc/free and memzero part of API.
2019-11-16 21:28:54 +01:00
Ondrej Kozina
e08401a2ec Properly fix encryption initialization message. 2019-11-08 13:15:37 +01:00
Ondrej Kozina
0a9e7028ae Fix LUKS2 encryption initialization with non-zero keyslot.
Positive keyslot number was interpreted as a failure.
2019-11-08 13:15:37 +01:00
Milan Broz
ba0ecc54df Test Bionic distro in Travis. 2019-11-05 22:09:05 +01:00
Milan Broz
6920f9dc27 Set devel version. 2019-11-05 17:56:58 +01:00
Milan Broz
ba2547212e Allow bitlk branch for CI tests. 2019-11-05 17:53:07 +01:00
Milan Broz
bbe1a8a5b6 Update Readme.md for 2.2.2. 2019-11-01 10:16:05 +01:00
Milan Broz
c82728f04d Version 2.2.2. 2019-11-01 09:02:46 +01:00
Milan Broz
cc0d33bca7 Fix DM_DEVICE_GET_TARGET_VERSION detection.
Stable libdevampper used changed name for dm task, let's fix it.
2019-10-31 20:35:46 +01:00
Milan Broz
3933ec7dce Add Ondra to authors. 2019-10-31 20:02:51 +01:00
Petr Pisar
f8c9507612 po: update cs.po (from translationproject.org) 2019-10-31 20:01:51 +01:00
Yuri Kozlov
7c5c9ae8fd po: update ru.po (from translationproject.org) 2019-10-31 12:10:04 +01:00
Frédéric Marchal
cd00792fe9 po: update fr.po (from translationproject.org) 2019-10-31 12:10:04 +01:00
Ondrej Kozina
df390509b2 Hotfix missing new line character in translated string.
Without this fix the message gets immediately overwritten with
reencryption progress bar.
2019-10-31 12:02:55 +01:00
Ondrej Kozina
dd6abe9375 Add luks2-reencryption-test to valgrind checks. 2019-10-22 15:07:57 +02:00
Milan Broz
a3f199d0a3 po: update pot file 2019-10-20 10:40:12 +02:00
Yuri Chornoivan
8e3b85ee12 po: update uk.po (from translationproject.org) 2019-10-20 10:35:43 +02:00
Jakub Bogusz
e60fbfc865 po: update pl.po (from translationproject.org) 2019-10-20 10:35:43 +02:00
Hiroshi Takekawa
a512488fd7 po: update ja.po (from translationproject.org) 2019-10-20 10:35:43 +02:00
Antonio Ceballos
1981d909cf po: update es.po (from translationproject.org) 2019-10-20 10:35:43 +02:00
Roland Illig
ea14f2c98c po: update de.po (from translationproject.org) 2019-10-20 10:35:43 +02:00
Milan Broz
c81becf10d Prepare version tag, and sync po files.
(For some reason I unsynced all po files again,
this patch reverts them to the translationproject versions...)
2019-10-18 10:52:33 +02:00
dofrupisla
1433d040ae Fix luksHeaderRestore occuring twice 2019-10-17 11:07:32 +02:00
Milan Broz
206b70c837 Explicitly print error message if keyslot open failed.
The only quiet message now is EPERM (wrong password) that is
processed by the caller.

Fixes #488.
2019-10-11 14:06:49 +02:00
Ondrej Kozina
bb857dcef2 Silence reencryption compat test. 2019-10-11 12:40:14 +02:00
Ondrej Kozina
5568a780a9 Add missing error message to translation. 2019-10-11 12:40:09 +02:00
Ondrej Kozina
7c2086967b Add various units for progress speed reporting.
The progress function remained silent unless the speed was higher
than minimal delta for double type in MiB/s. That could confuse
users that progress got stucked, but it in fact it was only slow.

Now wipe and reencryption progess functions can report speeds
in B/s up to GiB/s.
2019-10-11 12:40:03 +02:00
Ondrej Kozina
f7fbf4d38c Fix bogus speed reports after resuming tracked operation.
When resuming reencryption operation (both LUKS2 and legacy offline
code) speeds were incorectly calculated from whole progress including
range already reencrypted in previous runs. Now we track speed only
for currently running session.
2019-10-11 12:39:59 +02:00
Ondrej Kozina
0c8cf5c1e0 Switch cryptsetup-reencrypt to use tools_reencrypt_progress. 2019-10-11 12:39:51 +02:00
Milan Broz
33f2af1c09 Change --version option handling and support -V short option.
Fixes #480.
2019-10-10 10:51:04 +02:00
Ondrej Kozina
c9a7e6e4ec Add blkid wipe report messages to translations. 2019-10-08 15:31:57 +02:00
Ondrej Kozina
86bb4ea8f2 Report offsets when wiping device signatures.
Fixes: #489.
2019-10-08 15:31:57 +02:00
Milan Broz
99c4e83994 Properly support LTLIBINTL setting in Makefiles.
Fixes #479.
2019-10-08 15:26:13 +02:00
Milan Broz
ca2f5a8160 Fix tests in previous commits. 2019-10-08 14:58:07 +02:00
Milan Broz
7af304251e Fix activation message during encryption process. 2019-10-08 14:57:15 +02:00
Milan Broz
15f5126296 Support new DM_GET_TARGET_VERSION ioctl.
This way we can load kernel device-mapper target module before
table create ioctl.

Target version is available since kernel 5.4.
2019-10-08 14:05:30 +02:00
Ondrej Kozina
21edd66892 Allow LUKS2 reencryption to run on systems w/o kernel keyring service. 2019-10-07 14:08:41 +02:00
Ondrej Kozina
3e9d6b6960 Temporarily disable test failing due to deferred remove after decryption. 2019-10-04 13:46:13 +02:00
Ondrej Kozina
62b580904b Move check for loop device inside crypt_loop_backing_file.
It also fixes minor regression where we return backing file
for partition on top of loop device when prompting for passphrase.
Partition on loop has different major number so it should not be
considered loop device at all.
2019-10-04 13:46:13 +02:00
Ondrej Kozina
c4c4f9d159 Mark active device for deferred remove after decryption gets finished. 2019-10-04 12:20:34 +02:00
Ondrej Kozina
67a5ec1567 Abort reencryption initialization sooner on error. 2019-10-04 12:20:29 +02:00
Ondrej Kozina
c646832bfe Add hard and soft memory limit to reencrypt hotzone size.
Currently hard memory limit is 1 GiB. Soft limit is
1/4 of system memory.

Note that --hotzone-size cryptsetup parameter can only further
lower hard and soft memory limit on hotzone size and not bypass
it.
2019-10-04 12:20:22 +02:00
Ondrej Kozina
539d4756f2 Do not flush and freeze fs while swapping in/out overlay device. 2019-10-04 12:20:16 +02:00
Ondrej Kozina
8714e115ad Remove unused parameter from reencrypt_swap_backing_device.
It always loads dm-linear mapping in original device that maps 1:1
to helper overlay device (holding original table).
2019-10-04 12:20:12 +02:00
Ondrej Kozina
9c38e09ad3 Retain activation flags during and after online reencryption. 2019-10-04 12:20:06 +02:00
Ondrej Kozina
5628d7d8b5 Drop duplicite flag in LUKS2 device reload after reencryption.
Reload operation implicictly requires shared flag anyway and it's
added later.
2019-10-04 12:19:39 +02:00
Ondrej Kozina
5f2e8d6062 Allow LUKS2 device activation after encryption initialization.
It may be useful to activate device right after LUKS2 encryption
is initialized:

device is ready to use immediately even if data encryption runs in
the background for a long time

It simplifies encryption initialization during reboot.
2019-10-04 12:19:34 +02:00
Ondrej Kozina
630e336ea0 Do not allocate data device when identical with metadata device.
we do not need to allocate separate data device if it's equal
to metadata device during initialization.
2019-10-04 12:19:14 +02:00
Ondrej Kozina
430852736d Cleanup crypt_init_data_device.
data_device can not be NULL
2019-10-04 12:19:09 +02:00
Milan Broz
4eeb741358 Report kernel FIPS mode in module version test. 2019-10-03 14:01:27 +02:00
Ondrej Kozina
bb1ce4a069 Check plain crypt device is properly aligned on activation. 2019-10-02 13:40:10 +02:00
Ondrej Kozina
5e3e4a225e Check resize operation is aligned to device logical size.
Fixes #486.
2019-10-01 12:41:43 +02:00
Ondrej Kozina
583d05e32a Fix upconversion to LUKS2 with detached header.
The check for enough space before moving keyslots data did not expect real
detached header size to be less than aligned LUKS1 header size.

Also if detached header is placed in regular file we can grow so that
moved keyslots area fit the file.

Fixes #445.
2019-09-09 19:01:01 +02:00
Ondrej Kozina
2c0914b2ba Fix LUKS2 reencryption recovery test.
Fix corner case when head or tail of test device is remapped
to error target for writes.
2019-09-09 14:07:30 +02:00
Milan Broz
3ebedfe7b0 Update readme.md. 2019-09-06 13:13:44 +02:00
Milan Broz
1af2f85d43 Fix Release notes. 2019-09-06 12:49:31 +02:00
Milan Broz
0395e8935a Version 2.2.1. 2019-09-06 11:21:15 +02:00
Milan Broz
7ffd182197 Re-add cryptsetup.pot to git. 2019-09-06 10:53:34 +02:00
Milan Broz
fae1abdea9 Update gitignore (remove pot file). 2019-09-06 10:48:18 +02:00
Milan Broz
f17b8ad550 Update po files. 2019-09-06 10:02:15 +02:00
Milan Broz
883b600617 Update po files. 2019-09-02 11:22:06 +02:00
Yuri Chornoivan
f26a9abddb Fix minor typos 2019-09-02 09:20:47 +00:00
Milan Broz
4a7180a4f2 Clarify comments in API examples. 2019-08-30 16:24:56 +02:00
Milan Broz
af0c5c3ccb Set version to 2.2.1-rc0. 2019-08-30 13:15:17 +02:00
Milan Broz
a6e8db99b3 Fix test for very old kernels that truncate loop backing file info. 2019-08-30 10:41:04 +02:00
Milan Broz
e4684752c2 Update po file. 2019-08-30 09:42:27 +02:00
Milan Broz
4d6269a42d Fix some gcc warnings on 32bit systems. 2019-08-30 09:41:04 +02:00
Ondrej Kozina
593f5ee569 Reinstate missing backing file hint for loop device.
This regression was introduced in cryptsetup 2.0.0 release
with refactoring "Enter passphrase for (dev)" prompt.

With cryptsetup 1.7.5, "cryptsetup open /dev/loop0" printed
following prompt:

"Enter passphrase for /path/to/loop/backing_file:"

Whereas cryptsetup 2.0.0 and on printed following one:

"Enter passphrase for /dev/loop:"

Reported in https://bugzilla.redhat.com/show_bug.cgi?id=1726287

Fixes: 39698fa6b7 ("Remove terminal input from libcryptsetup API calls.")
Fixes: c80acbe4c8 ("Add back "Passphrase for (dev):" prompt.")
Fixes: 5171f65c05 ("tests only: Return back password retry support for luksOpen.")
2019-08-30 09:39:41 +02:00
Ondrej Kozina
4862e22cd0 Add opt-io size parameter to LUKS2 reencrypt test device.
So that we can test recovery is not broken for optimal io size
optimization added to reencryption code.
2019-08-30 09:39:38 +02:00
Ondrej Kozina
d13a6f7487 Take optimal io size in account with LUKS2 reencryption.
If device properly exposes optimal io size, let's align
reencryption hotzone to it. Otherwise device-mapper driver
complaints about misaligned tables and reencryption performance
is not optimal.
2019-08-30 09:39:35 +02:00
Milan Broz
09066b1ba6 Simplify API example and use LUKS2. 2019-08-29 13:07:32 +02:00
Milan Broz
8f8f0b3258 Fix mapped segments overflow on 32bit architectures.
All set_segment funcions must use uin64_t everywhere,
not size_t that is platform dependent.

The code later uses it correctly, it is just wrong function
prototype definitions.

Reported in
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=935702

(TODO: add a test for other segment types.)
2019-08-26 10:04:07 +02:00
Milan Broz
d9283970a5 Fix API test in FIPS mode. 2019-08-22 23:35:28 +02:00
Milan Broz
994afad279 Add veracrypt system encryption image. 2019-08-22 15:38:35 +02:00
Ondrej Kozina
b72ea28540 Fix regression in veracrypt system partition unlock.
Do not close base device file descriptor before reading from it.

Fixes #472.
2019-08-22 13:57:16 +02:00
Ondrej Kozina
fc69c6fac4 Add hint for online reencryption in cryptsetup-reencrypt man page.
command "man cryptsetup reencrypt" gets redirected to
cryptsetup-reencrypt man page. This may confuse users that LUKS2 online
reencryption is managed by offline utility.
2019-08-20 13:14:01 +02:00
Milan Broz
4100fd2817 Update Readme.md for 2.2.0. 2019-08-15 08:48:25 +02:00
Milan Broz
686744e48e Prepare version 2.2.0. 2019-08-14 20:38:23 +02:00
Milan Broz
0f49221f57 Add ja.po translation. 2019-08-14 20:37:40 +02:00
Milan Broz
725720dfc3 Fix volume key file if no LUKS2 keyslots are present.
If all keyslots are removed, LUKS2 has no longer information about
the volume key size (there is only key digest present).

If user wants to open or add new keyslot, it must get information
about key size externally.

We do not want to guess key size from the file size (it does not
work for block devices for example), so require explicit --keyfil
option in these cases.

Fixes #470.
2019-08-14 12:31:40 +02:00
Milan Broz
96cdb8edb7 Return error if keysize is 0.
Also use read_buffer to support partial read.
2019-08-14 12:18:04 +02:00
Milan Broz
7aa197be7d Print better warning if online reencrypt is called over LUKS1. 2019-08-14 08:14:02 +02:00
Ondrej Kozina
ea1dbfe961 Fix minimal size check for device in LUKS2 reencryption.
Commit 4c73da31 exposed another bug in minimal device size check.
During reencryption initialization wrong data offset value was used
and adjusted as if device was already undergoing reencryption. The
bug fixed by commit 4c73da31 hid this bug.

This is hotfix only and following functions needs more review:

- LUKS2_reencrypt_data_offset
- LUKS2_get_data_offset
- luks2_check_device_size
- LUKS2_get_data_size
2019-08-13 20:34:14 +02:00
Milan Broz
4c73da31ba Fix bugs found by Coverity. 2019-08-13 12:20:18 +02:00
Milan Broz
5febae8ad0 Fix warnings and flock access to test file in tests. 2019-08-13 10:36:41 +02:00
Milan Broz
d06f01a7d7 Update po files. 2019-08-13 09:26:04 +02:00
Ondrej Kozina
54d757a4c7 Fix illegal access to deallocated memory.
When deallocating context with LUKS2 reencryption handle
we access data device structure after being free'd.
2019-08-09 12:43:23 +02:00
Ondrej Kozina
a23e1cf729 LUKS2 code cleanup.
- drop unused code
- drop unused function declarations
- remove local routines from internal api
2019-08-05 18:29:37 +02:00
Ondrej Kozina
91879960e6 Move most of crypt_reencrypt_status to reencryption file. 2019-08-05 18:29:37 +02:00
Ondrej Kozina
270e6959b8 Make crypt_reencrypt_status return 'none' value for non-LUKS2 devices. 2019-08-05 18:29:37 +02:00
Ondrej Kozina
cbb3ca01f4 Reencryption code cleanup.
- Remove all 'LUKS2_' name prefixes from internal routines
- Make all internal routines prefixed with 'reencrypt_' instead
- Drop few static routines by refactoring
- Rename all variables and routines containing 'pre' prefix to
  contain 'hot' prefix instead (when referring to segments
  undergoing reencryption)
- Rename all variables and routines containing 'after' prefix to
  contain 'post' prefix instead
- Rename all routines prefixed with '_' to 'reencrypt_' instead
2019-08-05 18:29:35 +02:00
Ondrej Kozina
9845d6fd40 Shorten reencryption parameters debug message. 2019-08-05 18:28:15 +02:00
Ondrej Kozina
e5a59d6925 Remove json debug reencryption metadata fragments. 2019-08-05 18:28:15 +02:00
Ondrej Kozina
574170488c Update LUKS2 reencryption api tests. 2019-08-02 16:57:03 +02:00
Ondrej Kozina
9ea99efe13 Add test for absolute path passed to --active-name parameter. 2019-08-02 16:57:03 +02:00
Ondrej Kozina
b3af88708d Change reencryption mode parameter type to enum. 2019-08-01 15:40:53 +02:00
Ondrej Kozina
b96ce0b764 Add LUKS2 reencryption test for detached header misuse. 2019-08-01 10:43:57 +02:00
Ondrej Kozina
97ea39404a Allow reencryption to parse names prefixed with /dev. 2019-08-01 10:43:57 +02:00
Ondrej Kozina
4054f26c4d Add dm_device_name helper.
Gets dm name from absolute device path.
2019-08-01 10:43:57 +02:00
Ondrej Kozina
7380731bf7 Do not fail reencryption silently when --active-name is not LUKS2. 2019-08-01 10:43:57 +02:00
Ondrej Kozina
3bea349f9e Optionaly check device table before reencryption initialization. 2019-08-01 10:43:57 +02:00
Ondrej Kozina
98e0c8d609 Extend device table check in-before reencryption. 2019-08-01 10:43:57 +02:00
Ondrej Kozina
71f7385fcb Add support for linear segment in device comparison. 2019-08-01 10:43:57 +02:00
Ondrej Kozina
fbedf0ba6b Improve dm-crypt segments comparison function.
Check key descriptions are identical if both targets
were constructed using keys in kernel keyring service.
2019-08-01 10:40:37 +02:00
Ondrej Kozina
cf710eab13 Add internal crypt_compare_dm_devices. 2019-08-01 10:40:37 +02:00
Ondrej Kozina
b216a6a30e Introduce crypt_strcmp function (allows NULL). 2019-07-31 14:58:55 +02:00
Ondrej Kozina
b79086b3e9 Refactor assembly of multi-segment LUKS2 devices. 2019-07-31 14:58:55 +02:00
Ondrej Kozina
b551bdb0ce Make json_segments_count fn return unsigned value. 2019-07-31 14:58:55 +02:00
Ondrej Kozina
0886bc7afd Check for error sooner while assigning reencryption segments.
Also wraps function parameters definition.
2019-07-31 14:58:55 +02:00
Milan Broz
e7027e3d40 Revert back last cleanup call in api-test.
Removed by a mistake.
2019-07-31 12:15:49 +02:00
Milan Broz
243690b5ab Disalble luks2-reencryption-test in FIPE mode for now. 2019-07-31 12:03:44 +02:00
Milan Broz
5b5f76002e Fix various tests to run again in FIPS OpenSSL mode. 2019-07-31 10:27:58 +02:00
Milan Broz
fc03f1a1e6 Fix TCRYPT KDF failyure in FIPS mode.
SOme crypto backends now supports plain hash, but not PBKDF2 with
the same hash in FIPS mode.

Let's continue scanning other KDF if this error happens.
2019-07-31 10:25:54 +02:00
Milan Broz
1d59ae9aa9 Remove FIPS mode restriction for crypt_volume_key_get.
It is an application responsibility to use this API in the proper
context.
2019-07-30 14:12:50 +02:00
Milan Broz
8fde1b9f2c Mark API tests as skipped if setup phase fails. 2019-07-30 13:18:34 +02:00
Milan Broz
5e03f8c725 Always close context before failing API test.
Some devices could be still open delaying removal in cleanup.
2019-07-30 13:14:12 +02:00
Milan Broz
d6d4a50f7c Rename cd1-> cd in api test2. 2019-07-30 10:48:08 +02:00
Milan Broz
fe4e1de566 Mention limitiation of crypt_get_volume_key_size(). 2019-07-29 14:32:13 +02:00
Ondrej Kozina
e0d34b8f47 Add basic LUKS2 reencryption api test. 2019-07-26 16:20:36 +02:00
Ondrej Kozina
17c9d35449 Update reencryption flags description. 2019-07-26 16:09:38 +02:00
Ondrej Kozina
0e994265c6 Report data segment is moved in crypt_reencrypt_status. 2019-07-26 16:09:38 +02:00
Ondrej Kozina
e16319a290 Fail encryption initialization when data device too small. 2019-07-26 16:09:38 +02:00
Ondrej Kozina
c033643f07 Fix corner case bug in encryption with data shift.
If we initialized encryption with data shift and only single
segment the resulting metadata were missing
CRYPT_REENCRYPT_MOVE_FIRST_SEGMENT flag and also segments json section was
invalid.
2019-07-26 16:06:03 +02:00
Ondrej Kozina
607e2248c8 Simplify LUKS2_reencrypt_direction function. 2019-07-26 16:06:03 +02:00
Ondrej Kozina
a1111c7aa0 Tighten reencryption direction field validation. 2019-07-26 16:06:03 +02:00
Ondrej Kozina
1b82e70fc1 Fix bug in minimal device size calculation for reencryption. 2019-07-26 16:06:03 +02:00
Ondrej Kozina
35068c2e6e Fix broken segments calculation for backward data shift reencryption. 2019-07-26 16:06:03 +02:00
Ondrej Kozina
212703edf8 crypt_get_data_offset() must always return new offset value. 2019-07-26 16:06:03 +02:00
Ondrej Kozina
7460d1a446 Fix backward reencryption with data shift.
The device has to be shrunk the data shift size during activation.
Otherwise the online reencryption would fail with incorrect device
size.
2019-07-26 16:04:27 +02:00
Ondrej Kozina
c851205f83 Fix bug in reencryption digest to segment assignement. 2019-07-23 17:28:26 +02:00
Ondrej Kozina
dd0e073159 Fill direction field in crypt_reencrypt_status. 2019-07-23 17:28:26 +02:00
Ondrej Kozina
193b477086 Report reencryption data shift value in sectors. 2019-07-23 17:28:26 +02:00
Ondrej Kozina
3f85da0098 Fix datashift calculation in reencryption initialization. 2019-07-23 17:28:25 +02:00
Ondrej Kozina
dad28f3dfe Move exclusive open for offline reencryption in initialization. 2019-07-23 17:28:25 +02:00
Ondrej Kozina
e8e1da3fb5 Do not callback progress twice in reencryption loop. 2019-07-23 17:28:25 +02:00
Ondrej Kozina
4a24311161 Extend offline reencryption test for other keyslot numbers. 2019-07-15 14:36:36 +02:00
Ondrej Kozina
4f8c6b7773 Fix offline reencryption bug in header backup phase.
If first active keyslot number was different from zero the
decryption always failed.
2019-07-15 14:36:36 +02:00
Milan Broz
26fc2c24bd Update po files. 2019-07-15 10:26:13 +02:00
Ondrej Kozina
330f9daade Pass max_hotzone_size inside reencryption parameters in sectors. 2019-07-12 15:37:18 +02:00
Ondrej Kozina
4a232bc868 Pass device size inside reencryption parameters in sectors.
it was mistake in reencryption API. All other device sizes
related to device mapper devices are always in 512b setctors.
2019-07-12 15:37:18 +02:00
Ondrej Kozina
61dff96474 Reencryption keyslot must report as unbound. 2019-07-12 15:37:18 +02:00
Ondrej Kozina
bda28bbf38 Fix bug in crypt_keyslot_add_by_key. 2019-07-12 15:37:18 +02:00
Ondrej Kozina
66bedfd8e4 Fix LUKS2 reencryption recovery test.
Detect properly the case when recovery actually completed
encryption action for detached header case.
2019-07-12 15:37:18 +02:00
Ondrej Kozina
c18f968d84 Extend LUKS2 metadata size api tests. 2019-07-12 15:37:18 +02:00
Ondrej Kozina
5dfbc57117 Move LUKS2 metadata size api tests in separate routine. 2019-07-12 15:37:18 +02:00
Ondrej Kozina
e3fb6771d6 Re-enable mode test for LUKS2.
Since release 2.1.0 mode test for LUKS2 is skipped due to small test image.
Enforce smaller LUKS2 metadata via --offset to reenable the test.

Also detect failure for open action if format pass earlier.
2019-07-12 15:37:18 +02:00
Ondrej Kozina
f4da3c7f1b Add warning when changing explicitly requested LUKS2 metadata size. 2019-07-12 15:37:18 +02:00
Ondrej Kozina
81dbc9c070 Reduce implicit keyslots size when header device is too small.
Unless user explicitly asks for keyslots areas size
(either via --luks2-keyslots-size or --offset) reduce keyslots
size so that it fits in metadata device.
2019-07-12 15:37:08 +02:00
Ondrej Kozina
431bc87f85 Add LUKS2 error message hint when device too small.
If we format LUKS2 device with parameters unsuitable
for current metadata device size we usually fail during header areas
wipe. It was not clear what the reason actually was.
2019-07-12 15:12:46 +02:00
Milan Broz
b0e224a9f8 Update po file. 2019-07-01 10:19:14 +02:00
Ondrej Kozina
e3e6e75d40 Improvements to LUKS2 reencryption error messages.
- make error messages propagated to users more comprehensible
- drop some error messages completely
- replace many error messages with debug logs only

Fixes #458.
2019-07-01 10:18:55 +02:00
Ondrej Kozina
ed856f2ab8 Add tests for reencryption status reporting. 2019-07-01 10:18:52 +02:00
Ondrej Kozina
6425e1c52f Fix data device lookup among dm dependecies in crypt_init_by_name.
Also remove overlooked temporary debug message.
2019-07-01 10:18:49 +02:00
Ondrej Kozina
c842087cc1 Drop identical tests (already in compat-test). 2019-07-01 10:18:45 +02:00
Milan Broz
2651b381bb Update po files. 2019-06-29 10:43:28 +02:00
Yuri Chornoivan
4143d9871e Fix minor typos 2019-06-28 12:02:39 +00:00
Ondrej Kozina
fb9e467147 Add resize tests with --device-size parameter. 2019-06-27 14:40:06 +02:00
Ondrej Kozina
8b959158e3 Make resize action accept --device-size parameter (supports units).
Fixes #368.
2019-06-27 14:40:01 +02:00
Ondrej Kozina
ecb898c7ff Device size parameter must be always aligned to 512. 2019-06-27 14:39:59 +02:00
Milan Broz
c2b2b1ab5c Resync po files with the last translation.
(to be updated later)
2019-06-27 12:15:28 +02:00
Ondrej Kozina
d4682b3b38 Cleanup translated messages id.
- minimize count of almost identical message ids
- unify style for some messages
- remove some useless messages
2019-06-27 10:23:42 +02:00
Ondrej Kozina
2f4a50064f Add direction hint in reencryption hotzone device name. 2019-06-27 10:23:36 +02:00
Ondrej Kozina
6851535fe7 Add info about reencrytpion in LUKS2 status. 2019-06-27 10:23:08 +02:00
Ondrej Kozina
292a5f50b2 Allow offline reencryption on files without root privileges.
If userspace block ciphers are not available try kcapi first.
2019-06-27 10:19:23 +02:00
Ondrej Kozina
c25ce7c585 Allow disabling of reencryption locks via crypt_metadata_locking() 2019-06-27 10:19:18 +02:00
Ondrej Kozina
b22c9a86a9 Add internal crypt_zalloc routine (calloc wrapper). 2019-06-27 10:19:14 +02:00
Ondrej Kozina
767bb952a5 Enable crypt_init_by_name() for LUKS2 device on top of reencryption stack. 2019-06-27 10:19:12 +02:00
Ondrej Kozina
32e7178bbb Allow crypt_get_active_device for multi-segment devices. 2019-06-27 10:19:05 +02:00
Ondrej Kozina
614f671b92 Introduce SUBDEV internal device type.
LUKS2 and other device types allow stacking of dm devices
underneath public top level device.

The new type identifies clearly those private devices in respective
device stack so that they can be easily removed while removing
top level public device.

Switch LUKS2 reencryption device stack to use SUBDEV type immmediately
for hotzone and overlay devices. Other devices will follow in later
releases.
2019-06-27 10:19:01 +02:00
Ondrej Kozina
af62dbf3d3 Add internal limit for count of dm dependencies.
32 should be enough (+1 for terminating NULL byte)
2019-06-27 10:18:58 +02:00
Ondrej Kozina
249e6af3a6 Add LUKS2 uuid component in underlying dm-integrity device. 2019-06-27 10:18:56 +02:00
Ondrej Kozina
59bed375d0 Add type parameter to INTEGRITY_activate_dmd. 2019-06-27 10:18:54 +02:00
Ondrej Kozina
aba95b00aa Activate underlying dm-integrity privately for LUKS2 w/ auth. encryption. 2019-06-27 10:18:50 +02:00
Ondrej Kozina
011ee5b180 Introduce crypt_string_in internal helper.
And replace custom name_in_list function with new helper.
2019-06-27 10:18:47 +02:00
Ondrej Kozina
4e19719bdd Check hotzone size and device size alignment earlier.
It failed later but it was difficult to understand what went wrong.
2019-06-27 10:18:44 +02:00
Ondrej Kozina
fa469aaf41 Update struct crypt_params_reencrypt documentation. 2019-06-27 10:18:41 +02:00
Ondrej Kozina
3cabf608ca Unify reencryption context load error messages. 2019-06-27 10:18:37 +02:00
Milan Broz
2e841622f8 Print proper error message if LUKS2 slot encryption fail. 2019-06-26 17:30:30 +02:00
Milan Broz
9b5e3797b1 Fis status command to display only specific device types.
Cryptsetup, veritysetup and integrity setup should ignore other
device mappings in status command (it should display only
basic type information).
2019-06-25 15:03:04 +02:00
Seong-Joong Kim
07df177332 Fix a typo of comment 2019-06-24 22:31:52 -07:00
Milan Broz
ff364347cf Add FAIL backtrace to all bash tests. 2019-06-20 15:11:56 +02:00
Milan Broz
4c74ff5e5a Add ESSIV test in combination with AEAD data integrity protection. 2019-06-20 14:48:59 +02:00
Milan Broz
2ebd19c9bc Fix another EOL in api-test debug log. 2019-06-20 14:28:32 +02:00
Milan Broz
875ffa49b3 Fix log_dbg EOL in tools. 2019-06-19 12:12:02 +02:00
Ondrej Kozina
ff0030d74f Add missing --retry parameter in tests cleanup. 2019-06-18 13:26:20 +02:00
Ondrej Kozina
7a71feed8c Remove overlooked config scratching from reencryption tests. 2019-06-18 13:26:20 +02:00
Guilhem Moulin
70c4ce199d Fix minor spelling errors in manpage and messages.
Reported by lintian(1) - Static analysis tool for Debian packages:

accidentaly -> accidentally
trigerring -> triggering
alocate -> allocate
alignemnt -> alignment
initalize -> initialize
2019-06-18 09:42:28 +02:00
Alexander Neumann
ed0f8ccbaf Document all options for the --type parameter 2019-06-14 21:28:05 +02:00
Milan Broz
3e5ca2e168 Update readme.md. 2019-06-14 16:30:37 +02:00
Milan Broz
d0dc59e792 Update po file. 2019-06-14 13:54:23 +02:00
Ondrej Kozina
0106c64369 Fix issues reported by valgrind.
keyslot_cipher member leaked after existing LUKS2 context reload.

crypt_keyslot_set_encryption may access freed memory if
crypt_keyslot_get_encryption was previously called with
CRYPT_ANY_SLOT parameter.
2019-06-14 13:50:09 +02:00
Ondrej Kozina
69fdb41934 Add tests for LUKS2 reencryption with multiple active keyslots. 2019-06-14 09:10:28 +02:00
Ondrej Kozina
550b3ee1d3 Fix off-by-one error in reencryption keyslots count check. 2019-06-14 09:10:28 +02:00
Milan Broz
961cc6a6d3 Prepare version 2.2.0-rc1. 2019-06-14 08:20:04 +02:00
Ondrej Kozina
05091ab656 Improve reencryption when dealing with multiple keyslots.
It's possible to retain all keyslots (passphrases) when
performing LUKS2 reencryption provided there's enough
space in LUKS2 json metadata.

When specific keyslot is selected all other keyslots
bound to old volume key get deleted after reencryption
is finished.

Existing tokens are assigned to new keyslots.
2019-06-13 17:04:34 +02:00
Ondrej Kozina
272505b99d If no hash is specified in pbkdf use default value for keyslot AF. 2019-06-13 17:04:21 +02:00
Ondrej Kozina
60a769955b Rename hash data parameter in reencrypt keyslot dump. 2019-06-12 12:36:51 +02:00
Ondrej Kozina
34bec53474 Drop excessive nested locking in LUKS2 keyslot store path.
Since commit 80a435f it's not needed to call device_write_lock
in function luks2_encrypt_to_storage. It's handled correctly on
upper layer.
2019-06-12 12:36:51 +02:00
Ondrej Kozina
c77ae65a0d Wipe both keyslot data and metadata holding single write lock. 2019-06-12 12:36:51 +02:00
Ondrej Kozina
1ed0430b82 Move LUKS2 write lock upper when storing reencryption keyslot. 2019-06-12 12:36:51 +02:00
Ondrej Kozina
82f640e360 Open device in locked mode for wipe when necessary. 2019-06-12 12:36:51 +02:00
Ondrej Kozina
44aabc3ae4 Drop reload of metadata in reencryption initialization. 2019-06-12 12:36:50 +02:00
Ondrej Kozina
bbdf9b2745 Read and compare metadata sequence id after taking write lock. 2019-06-12 12:36:46 +02:00
Ondrej Kozina
96a87170f7 Return usage count from device locking functions. 2019-06-12 11:51:08 +02:00
Ondrej Kozina
281323db42 Fix condition for printing debug message. 2019-06-12 11:51:08 +02:00
Milan Broz
32258ee8ae Fix debugging messages callback.
The debug messages should contain EOL char.

Also check string lengths in internal logging macros.
2019-06-11 15:26:53 +02:00
Milan Broz
df0faef9ca Add integritysetup bitmap mode test. 2019-06-04 20:05:13 +02:00
Ondrej Kozina
9c3a020ecf Remove useless debug message from keyslot dump. 2019-05-27 16:23:56 +02:00
Ondrej Kozina
4c4cc55bb7 Wipe backup segment data after reencryption is finished. 2019-05-27 16:05:21 +02:00
Ondrej Kozina
f4c2e7e629 Implement LUKS2 reencrypt keyslot dump. 2019-05-27 15:27:23 +02:00
Ondrej Kozina
eadef08fd5 Extend LUKS2 reencryption recovery tests.
- test repair commad for reencryption recovery.
- test close command is able to teardown leftover device stack after
  crash.
- test open performs recovery by default (to be able to open root
  volume).
2019-05-24 17:29:56 +02:00
Ondrej Kozina
0c725a257d Compare moved segment specific size against real device size only. 2019-05-24 17:29:56 +02:00
Ondrej Kozina
6f35fb5f80 Silence query error messages for unsupported target types. 2019-05-24 17:29:56 +02:00
Ondrej Kozina
cd1fe75987 Close all device handlers after failed internal load. 2019-05-24 17:29:56 +02:00
Ondrej Kozina
e92e320956 Add explicit device_close routine. 2019-05-24 17:29:56 +02:00
Ondrej Kozina
0e4757e0fb Add LUKS2 reencryption recovery in repair command. 2019-05-24 17:29:56 +02:00
Ondrej Kozina
bd6af68bc5 Add support for explicit reencryption recovery in request. 2019-05-24 17:07:37 +02:00
Ondrej Kozina
13050f73c1 Properly finished reencryption after recovery. 2019-05-24 17:07:37 +02:00
Ondrej Kozina
5472fb0c56 Refactor reencryption recovery during activation. 2019-05-24 17:07:36 +02:00
Ondrej Kozina
73c2424b24 Refactor LUKS2 device activation (in reencryption). 2019-05-24 17:07:36 +02:00
Milan Broz
5117eda688 Switch to Xenial distro in Travis. 2019-05-24 08:33:20 +02:00
Ondrej Kozina
cfbef51d3d Add interactive dialog in case active device auto-detection fails. 2019-05-22 12:50:18 +02:00
Ondrej Kozina
09cb2d76ef Add dialog with default 'no' answer. 2019-05-22 12:50:17 +02:00
Ondrej Kozina
3f549ad0df Refactor yesDialog utility. 2019-05-22 12:50:17 +02:00
Ondrej Kozina
60d26be325 Load volume key in keyring when activated by token.
LUKS2 should use keyring for dm-crypt volume keys by default
when possible. crypt_activate_by_token didn't load keys in
keyring by default. It was a bug.
2019-05-21 18:08:00 +02:00
Ondrej Kozina
013d0d3753 Rename internal reencrypt enum to REENC_PROTECTION_NONE. 2019-05-21 18:08:00 +02:00
Ondrej Kozina
97da67c6a8 Add tests for reencryption with fixed device size. 2019-05-21 18:08:00 +02:00
Ondrej Kozina
f74072ba28 Silence active device detection message in batch mode. 2019-05-21 16:05:23 +02:00
Ondrej Kozina
19eac239b7 Add --device-size parameter for use in LUKS2 reencryption.
Currently it's used only in LUKS2 reencryption code
for reencrypting initial part of data device only.

It may be used to encrypt/reencrypt only initial part
of data device if user is aware that rest of the device
is empty.
2019-05-21 15:54:43 +02:00
Ondrej Kozina
31cd41bfe4 Add support for reencryption of initial device part.
It's useful to reencrypt only initial device part only.
For example with golden image reencryption it may be useful
to reencrypt only first X bytes of device because we know
the rest of device is empty.
2019-05-21 15:54:07 +02:00
Ondrej Kozina
af6c321395 Set default length for reencryption with resilience 'none' only. 2019-05-21 15:54:07 +02:00
Milan Broz
448fca1fdf Integritysetup: implement new bitmap mode. 2019-05-21 15:54:07 +02:00
Ondrej Kozina
1923928fdc Drop duplicate error message from reencrypt load. 2019-05-21 15:54:07 +02:00
Ondrej Kozina
bee5574656 Add --resume-only parameter to reencrypt command. 2019-05-21 15:54:07 +02:00
Ondrej Kozina
8c8a68d850 Add CRYPT_REENCRYPT_RESUME_ONLY flag. 2019-05-13 18:23:20 +02:00
Ondrej Kozina
9159b5b120 Add coverity toctou annotation in device_open_excl.
We can't avoid this race due to undefined behaviour if called with
O_EXCL flag on regular file.

Let's double-check fd with O_EXCL flag is actually open block device.
2019-05-13 18:23:20 +02:00
Ondrej Kozina
2d0079905e Adapt device_open_excl to reusing of fds. 2019-05-10 21:05:31 +02:00
Ondrej Kozina
83c227d53c Sync device using internal write enabled descriptor. 2019-05-10 21:05:31 +02:00
Ondrej Kozina
ee57b865b0 Reuse device file desriptors. 2019-05-10 21:05:31 +02:00
Milan Broz
ecbb9cfa90 Use upstream gnulib patch for Coverity warning fixed by previous patch. 2019-05-10 21:03:22 +02:00
Ondrej Kozina
8545e8496b Fix memleak in reencryption with moved segment. 2019-05-07 17:17:34 +02:00
Kamil Dudka
75b2610e85 Fix TAINTED_SCALAR false positives of Coverity
Coverity Analysis 2019.03 incorrectly marks the input argument
of base64_encode(), and conseuqnetly base64_encode_alloc(), as
tainted_data_sink because it sees byte-level operations on the input.
This one-line annotation makes Coverity suppress the following false
positives:

Error: TAINTED_SCALAR:
lib/luks2/luks2_digest_pbkdf2.c:117: tainted_data_argument: Calling function "crypt_random_get" taints argument "salt".
lib/luks2/luks2_digest_pbkdf2.c:157: tainted_data: Passing tainted variable "salt" to a tainted sink.

Error: TAINTED_SCALAR:
lib/luks2/luks2_keyslot_luks2.c:445: tainted_data_argument: Calling function "crypt_random_get" taints argument "salt".
lib/luks2/luks2_keyslot_luks2.c:448: tainted_data: Passing tainted variable "salt" to a tainted sink.
2019-05-07 15:35:55 +02:00
Milan Broz
237021ec15 Fix some warnings in static analysis. 2019-05-07 13:44:43 +02:00
Ondrej Kozina
4f5c25d0dd Add HAVE_DECL_DM_TASK_RETRY_REMOVE define in local tests. 2019-05-06 15:42:11 +02:00
Ondrej Kozina
4c33ab1997 Remove internal config file scratching (breaks local tests.) 2019-05-06 15:41:37 +02:00
Ondrej Kozina
5bb65aca8f Remove all test dm devices with retry option if available. 2019-05-06 15:37:35 +02:00
Milan Broz
3fd7babacc Update Readme.md. 2019-05-03 15:50:39 +02:00
Ondrej Kozina
caea8a9588 Update rc release notes. 2019-05-03 15:16:12 +02:00
Ondrej Kozina
e1d6cba014 Add reencryption action man page. 2019-05-03 15:00:33 +02:00
Milan Broz
1f91fe7a2c Use JSON-debug wrappers. 2019-05-03 14:02:43 +02:00
Milan Broz
dc53261c3b Fix data leak in format and reencrypt command. 2019-05-03 13:06:58 +02:00
Milan Broz
b3e90a93b0 Add test release notes and increase ABI version. 2019-05-03 12:57:29 +02:00
Milan Broz
1f3e2b770c Fix offline reencryption tool name. 2019-05-02 21:05:22 +02:00
Ondrej Kozina
d310e896cb Add basic offline tests for LUKS2 reencryption. 2019-05-02 17:23:59 +02:00
Ondrej Kozina
a36245cef6 Add new reencrypt cryptsetup action.
The new reencryption code is enabled via cryptsetup cli
and works with LUKS2 devices only.
2019-05-02 16:45:43 +02:00
Ondrej Kozina
092ef90f29 Add autodetection code for active dm device. 2019-05-02 16:44:23 +02:00
Ondrej Kozina
64f59ff71e Add reencryption progress function. 2019-05-02 16:44:23 +02:00
Ondrej Kozina
a7f80a2770 Add resilient LUKS2 reencryption library code. 2019-05-02 16:44:23 +02:00
Ondrej Kozina
a5c5e3e876 Add dm_device_deps for quering dm device dependencies. 2019-05-02 15:23:29 +02:00
Ondrej Kozina
8e4fb993c0 Add error target support in dm_query_device. 2019-05-02 15:23:29 +02:00
Ondrej Kozina
846567275a Move dm_query_device body in static function. 2019-05-02 15:23:28 +02:00
Ondrej Kozina
741c972935 Remove unused minor number from dm_is_dm_device. 2019-05-02 15:23:28 +02:00
Ondrej Kozina
6c2760c9cd Report data sync errors from storage wrapper. 2019-04-29 16:48:20 +02:00
Ondrej Kozina
b35a5ee4a3 Replace table with error mapping even when in use. 2019-04-29 16:10:57 +02:00
Ondrej Kozina
345385376a Add missing validation check for area type specification. 2019-04-29 16:10:57 +02:00
Milan Broz
dbe9db26fc Never serialize memory-hard KDF for small amount of memory. 2019-04-29 16:10:57 +02:00
Milan Broz
91ba22b157 Do not try to remove device that was not succesfully activated. 2019-04-29 16:10:57 +02:00
Ondrej Kozina
86b2736480 Drop unused type parameter from LUKS2_keyslot_find_empty() 2019-04-23 10:41:56 +02:00
Milan Broz
cfe2fb66ab Fix some untranslated error messages. 2019-04-23 10:41:06 +02:00
Milan Broz
428e61253c Fix dm_error_device() to properly use error device. 2019-04-10 15:06:07 +02:00
Milan Broz
95bcd0c9d5 Fix previous patch locking to return EBUSY. 2019-04-10 14:27:42 +02:00
Milan Broz
23bada3c5a Fix several issues found by Coverity scan. 2019-04-10 12:30:09 +02:00
Stig Otnes Kolstad
de0cf8433b Add pbkdf options to all key operations in manpage 2019-04-09 17:19:41 +02:00
Milan Broz
1b49ea4061 Add global serialization lock for memory hard PBKDF.
This is very ugly workaround for situation when multiple
devices are being activated in parallel (systemd crypttab)
and system  instead of returning ENOMEM use OOM killer
to randomly kill processes.

This flag is intended to be used only in very specific situations.
2019-03-29 11:58:12 +01:00
Ondrej Kozina
29b94d6ba3 Add arbitrary resource locking (named locks).
It's complementary to current device locking. It'll be used
for mutual exclusion of two or more reencryption resume processes
2019-03-26 14:48:27 +01:00
Ondrej Kozina
80a435f00b Write keyslot binary data and metadata holding single lock. 2019-03-25 11:37:32 +01:00
Ondrej Kozina
fdcd5806b1 Allow to change requirements flag in-memory only. 2019-03-25 11:37:32 +01:00
Ondrej Kozina
9ddcfce915 Refactor locking code. 2019-03-25 11:37:32 +01:00
Ondrej Kozina
6ba358533b Modify crypt lock handle internal structure.
makes it ready for future lock handle type
2019-03-25 11:37:32 +01:00
TrueDoctor
73aa329d57 fixed Grammar in manpage cryptsetup-reencrypt(8) 2019-03-22 23:20:13 +00:00
Ondrej Kozina
379016fd78 Add no flush internal suspend/resume flag. 2019-03-22 08:01:21 +01:00
Ondrej Kozina
ea4b586c77 Add tests for CRYPT_VOLUME_KEY_DIGEST_REUSE flag.
Tests commit 7569519530
2019-03-22 08:01:21 +01:00
Ondrej Kozina
6961f2caae Switch crypt_suspend() to DM_SUSPEND_WIPE_KEY flag. 2019-03-22 08:01:21 +01:00
Ondrej Kozina
4df2ce4409 Add wipe key flag for internal device suspend. 2019-03-22 08:01:21 +01:00
Ondrej Kozina
052a4f432c Add internal option to skip fs freeze in device suspend. 2019-03-22 08:01:21 +01:00
Ondrej Kozina
de86ff051e Introduce support for internal dm suspend/resume flags. 2019-03-22 08:01:21 +01:00
Ondrej Kozina
f5feeab48d Add experimental storage wrappers. 2019-03-22 08:01:21 +01:00
Milan Broz
1317af028e Use compatible switch for free command. 2019-03-21 15:32:22 +01:00
Milan Broz
cdcd4ddd35 Print free memory in tests. 2019-03-21 15:16:33 +01:00
Milan Broz
2960164cf8 Fix localtest if the last test is skipped. 2019-03-21 15:12:39 +01:00
Milan Broz
a98ef9787c Set devel version. 2019-03-20 21:58:27 +01:00
Milan Broz
b6d406fbc8 Add fixed Makefile that can run tests outside of compiled tree. 2019-03-20 21:58:07 +01:00
Ondrej Kozina
e3488292ba Fix typo in --disable-keyring description. 2019-03-13 15:24:45 +01:00
Ondrej Kozina
fea2e0be4f Add algorithm for searching largest gap in keyslots area. 2019-03-13 14:56:31 +01:00
Milan Broz
751f5dfda3 Move error message for a keyslot area search. 2019-03-13 14:56:31 +01:00
Ondrej Kozina
d5f71e66f9 Allow digest segment (un)binding for all segments at once. 2019-03-13 14:56:31 +01:00
Ondrej Kozina
03e810ec72 Split crypt_drop_keyring_key in two different routines.
crypt_drop_keyring_key function allow to drop all keys in keyring
assocatiated with passed volume key list.

crypt_drop_keyring_key_by_description is used to drop independent key.
2019-03-13 14:56:31 +01:00
Ondrej Kozina
6c6f4bcd45 Add signed int64 json helpers. 2019-03-13 14:56:31 +01:00
Ondrej Kozina
304942302b Introduce CRYPT_DEFAULT_SEGMENT abstraction.
Default segment is no longer constant segment with id 0.
2019-03-13 14:56:31 +01:00
Ondrej Kozina
8dc1a74df8 Adapt existing code to future reencryption changes. 2019-03-13 14:56:31 +01:00
Ondrej Kozina
e295d01505 Adding new functions later used in reencryption. 2019-03-13 14:56:31 +01:00
Ondrej Kozina
aa1b29ea0e Add volume key next helper. 2019-03-13 14:56:31 +01:00
Ondrej Kozina
cef857fbbd Add routine for adding volume key in a list. 2019-03-13 14:56:31 +01:00
Ondrej Kozina
6bba8ce0dc Allow vk insert in linked list.
Also adds search function crypt_volume_key_by_id.
2019-03-13 14:56:31 +01:00
Ondrej Kozina
b0330d62e5 Add id member in volume_key structure.
Also adds set/get helper routines.
2019-03-13 14:56:31 +01:00
Frederik Nnaji
fc0c857cfe Update README.md 2019-03-13 13:52:40 +00:00
Milan Broz
238b18b8ac Upstream fixes to bundled Argon2 code.
Wait for already running threads if a thread creation failed.
Use explicit_bzero() on recent glibc versions.
(Without fixed logic, we have already macro definition through automake.)

Fixes #444.
2019-03-13 08:26:40 +01:00
Ondrej Kozina
6a2d023b7b Make keyring utilities ready for additional kernel key types. 2019-03-08 09:03:35 +01:00
Ondrej Kozina
4bb1fff15d Add new functions for kernel keyring handling. 2019-03-08 08:54:09 +01:00
Ondrej Kozina
37f5bda227 Add explicit key type name in keyring functions. 2019-03-08 08:53:33 +01:00
Ondrej Kozina
56b571fcaa Use const before vk in all digest verify functions. 2019-03-08 08:52:47 +01:00
Ondrej Kozina
46bf3c9e9c Add segment create helpers. 2019-03-08 08:44:51 +01:00
Ondrej Kozina
361fb22954 Remove helper get_first_data_offset completely. 2019-03-08 08:43:19 +01:00
Ondrej Kozina
203fe0f4bf Move get_first_data_offset to luks2_segment.c 2019-03-08 08:42:23 +01:00
Ondrej Kozina
36ac5fe735 Move LUKS2 segments handling in separate file. 2019-03-08 08:39:32 +01:00
Ondrej Kozina
7569519530 Allow unbound keyslots to be assigned to existing digest.
If passed key matches any existing digest we will not create
new digest but assign the keyslot to already existing one.

Because reencryption should be able to create more than one
keyslot assigned to new key digest.

TODO: Tests for the new feature
2019-03-08 08:37:27 +01:00
Ondrej Kozina
a848179286 Add json_object_copy wrapper. 2019-03-08 08:27:18 +01:00
Milan Broz
456ab38caa Allow to set CRYPTSETUP_PATH in tests for system installed cryptsetup tools.
Run: make check CRYPTSETUP_PATH=/sbin
2019-03-08 08:16:45 +01:00
Milan Broz
c71b5c0426 Update po files. 2019-03-08 08:15:57 +01:00
Ondrej Kozina
868cc52415 Abort conversion to LUKS1 with incompatible sector size. 2019-03-05 17:08:05 +01:00
Ondrej Kozina
8c168cc337 Introduce file for luks2 segments handling. 2019-03-05 17:08:02 +01:00
Ondrej Kozina
f9fa4cc099 Add kernel only detection in crypt storage API. 2019-03-05 17:07:57 +01:00
Ondrej Kozina
a0540cafb3 alter crypt_storage interface
rename sector_start -> iv_start (it's now a iv shift for subsequent
en/decrypt operations)

rename count -> length. We accept length in bytes now and perform sanity
checks at the crypt_storage_init and crypt_storage_decrypt (or encrypt)
respectively.

rename sector -> offset. It's in bytes as well. Sanity checks inside
crypt_storage functions.
2019-03-05 17:07:45 +01:00
Ondrej Kozina
88b3924132 Update LUKS2 locks for atomic operations.
Atomic operation requires to hold a lock for longer period than
single metadata I/O. Update locks so that we can:

- lock a device more than once (lock ref counting)
- reaquire read lock on already held write lock (write lock
  is stronger than read lock)
2019-03-05 17:07:31 +01:00
Ondrej Kozina
3023f26911 Always allocate new header file of 4KiB.
All issues related to header wiping and smaller
files were resolved. It's no longer needed to allocate
files larger than 4KiB.
2019-03-05 16:55:17 +01:00
Milan Broz
c9347d3d7d Fix a gcc warning when accessing packed struct member. 2019-03-05 16:50:24 +01:00
Ondrej Kozina
d85c7d06af Do not fail tests if benchmarked >= 1000 iterations with -i1. 2019-03-01 21:43:35 +01:00
Ondrej Kozina
e229f79741 Open device in locked mode if needed. 2019-03-01 21:43:31 +01:00
Ondrej Kozina
a4d236eebe Add device_is_locked function. 2019-03-01 21:43:25 +01:00
Milan Broz
1192fd27c6 Add query for cipher implementation is used through kernel API. 2019-03-01 21:43:10 +01:00
Milan Broz
cd1cb40033 Use crypto library for ciphers if algorithms are available. 2019-03-01 21:34:22 +01:00
Milan Broz
14e085f70e Move cipher performance check to crypto backend. 2019-03-01 21:16:05 +01:00
Milan Broz
fc37d81144 Move crypt_cipher to per-lib implementation.
For now, it calls kernel fallback only.
2019-03-01 21:14:13 +01:00
Milan Broz
a859455aad Move block ciphers backend wrappers to per-library files.
For now it always fallbacks to kernel crypto API.
2019-03-01 21:10:50 +01:00
Milan Broz
93d596ace2 Introduce internal backend header.
And remove commented-out test vectors (moved to tests).
2019-03-01 20:39:33 +01:00
Ondrej Kozina
c03e3fe88a Fix getting default LUKS2 keyslot encryption parameters.
When information about original keyslot size is missing (no active
keyslot assigned to default segment) we have to fallback to
default luks2 encryption parameters even though we know default
segment cipher and mode.

Fixes: #442.
2019-03-01 20:39:06 +01:00
Ondrej Kozina
a90a5c9244 Avoid double free corruption after failed crypt_init_data_device. 2019-03-01 20:31:00 +01:00
Ondrej Kozina
26772f8184 Return NULL explicitly if keyslot is missing.
json_object_object_get_ex return parameter is
undefined if function returns false.
2019-03-01 20:30:21 +01:00
Ondrej Kozina
8f8ad83861 Validate metadata before writting binary keyslot area. 2019-03-01 20:29:49 +01:00
Ondrej Kozina
d111b42cf1 Fix keyslot area gap find algorithm.
get_max_offset must use value calculated from LUKS2 metadata
boundaries. Data offset didn't have to match end of LUKS2 metadata
area.
2019-03-01 20:29:40 +01:00
Ondrej Kozina
821c965b45 Drop commented code block. 2019-03-01 20:28:56 +01:00
Ondrej Kozina
4acac9a294 Properly handle DM_LINEAR type while checking version or dmflags. 2019-03-01 20:28:43 +01:00
Ondrej Kozina
4adb06ae91 Add missing direction flag in dm_crypt_target_set.
This bug may have caused memory corruption in dm_targets_free
later.
2019-03-01 20:27:53 +01:00
Milan Broz
dce7a1e2aa Fix gcc warning in tests. 2019-02-24 12:35:54 +01:00
Milan Broz
a354b72546 Add some symmetric block ciphers vector tests for crypto backend. 2019-02-24 12:35:50 +01:00
Milan Broz
ac8f41404b Simplify and reformat hash/HMAC test vectors test. 2019-02-24 12:35:45 +01:00
Milan Broz
fc7b257bab Silence dmsetup removal messages. 2019-02-13 13:34:39 +01:00
Milan Broz
787066c292 Report error if no LUKS keyslots are available.
Also fix LUKS1 keyslot function to proper return -ENOENT errno in this case.

This change means, that user can distinguish between bad passphrase and
no keyslot available. (But this information was avalilable with luksDump
even before the change.)
2019-02-13 13:19:48 +01:00
Milan Broz
71ab6cb818 Fix other tests to not fail if keyring support is missing in kernel. 2019-02-12 16:16:56 +01:00
Milan Broz
1158ba453e Use better test for a bad loop descriptor. 2019-02-12 14:54:56 +01:00
Milan Broz
2e3f764272 Fix api-test-2 to properly detect missing keyring in kernel.
Also properly cleanup after some failures.
2019-02-12 14:49:21 +01:00
Milan Broz
2172f1d2cd Print PBKDF debug log in a better format.
Fixes #439.
2019-02-11 12:37:33 +01:00
Milan Broz
6efc1eae9f Update Readme.md. 2019-02-08 15:37:17 +01:00
Milan Broz
6a740033de Add 2.1. release notes. 2019-02-08 15:08:04 +01:00
Ondrej Kozina
d754598143 Preserve LUKS2 mdata & keyslots sizes after reencryption. 2019-02-08 12:00:24 +01:00
Ondrej Kozina
47f632263e Add missing crypt_free() in api test. 2019-02-08 11:56:52 +01:00
Milan Broz
98af0b0c77 Increase API version. 2019-02-07 18:42:17 +01:00
Ondrej Kozina
b9c6a62437 Do not call fallocate on image file that is already large enough. 2019-02-07 18:41:06 +01:00
Ondrej Kozina
57670eeeb7 Detect LUKS2 default alignmnet in align tests. 2019-02-07 18:40:48 +01:00
Ondrej Kozina
f26ee11913 Assert reasonable LUKS2 default header size. 2019-02-07 18:40:39 +01:00
Milan Broz
2435d76a39 Use 16MB LUKS2 header size by default. 2019-02-07 18:40:14 +01:00
Milan Broz
348d460ab7 Workarounds for larger LUKS2 header for tests. 2019-02-07 18:39:50 +01:00
Milan Broz
2b8b43b3db Fix file descriptor leak in error path. 2019-02-07 17:37:16 +01:00
Milan Broz
91b74b6896 Fix some compiler warnings. 2019-02-07 17:14:47 +01:00
Milan Broz
319fd19b5e Add implementation of crypt_keyslot_pbkdf().
This function allows to get PBKDF parameters per-keyslot.
2019-02-07 12:55:12 +01:00
Milan Broz
4edd796509 Fix typo. 2019-02-06 21:48:29 +01:00
Ondrej Kozina
b0ced1bd2c Make compat-test2 work with 16M data offset. 2019-02-06 21:43:36 +01:00
Ondrej Kozina
6ed3a7774f Calculate keyslots size based on requested metadata size. 2019-02-06 21:42:51 +01:00
Ondrej Kozina
1ce3feb893 Add format test for detached header using last keyslot. 2019-02-06 21:41:43 +01:00
Milan Broz
ebbc5eceb8 Fix crypt_wipe to allocate space and not silently fail.
This change will allocate space if underlying device is smaller file
and fail if it is block device.

Previously smaller device was quietly ignored, leading to keyslot
access failure with older dm-crypt mapped keyslot encryption
(disabled kernel user crypto API).
2019-02-06 21:39:26 +01:00
Ondrej Kozina
0cac4a4e0c Make api test run with any defalt LUKS2 header size. 2019-02-06 11:48:47 +01:00
Milan Broz
1908403324 Prepare change for default LUKS2 keyslot area size. 2019-02-06 11:48:34 +01:00
Ondrej Kozina
faa07b71f9 Fix debug message when zeroing rest of data device.
The debug message printed wrong expected value and
also remained silent if expected value differed from
real bytes written to the data device.
2019-02-06 11:48:24 +01:00
Ondrej Kozina
e9dcf6b8dd Simplify create_empty_header in cryptsetup-reencrypt.
In most cases we do not need to create large files for new headers.
crypt_format already allocates enough space for all keyslots in files
during internal header wipe.

Fixes #410.
2019-02-06 11:48:07 +01:00
Milan Broz
3ea60ea0ae Update po files. 2019-02-06 11:46:37 +01:00
Milan Broz
54171dfdd3 Fix api-test to detect kernel without needed crypto module for tcrypt test. 2019-01-31 16:32:11 +01:00
Milan Broz
dc8db34155 Run keyring test only for recent kernels. 2019-01-31 16:31:09 +01:00
Milan Broz
a68f3939cf Use min memory limit from PBKDF struct in Argon benchmark. 2019-01-31 10:53:51 +01:00
Milan Broz
ae90497762 Switch to default LUKS2 format in configure. 2019-01-31 09:30:04 +01:00
Rafael Fontenelle
2b55f6420a Fix misspellings 2019-01-28 08:40:20 -02:00
Milan Broz
6d3545624d Fix typo in API documentation. 2019-01-26 12:44:31 +01:00
Milan Broz
46dc5beee9 Increase LUKS keysize if XTS mode is used (two internal keys). 2019-01-25 13:56:21 +01:00
Milan Broz
943cc16020 Fix test to print exit line and use explicit key size. 2019-01-25 13:38:24 +01:00
Milan Broz
a6f5ce8c7b Update copyright year.
And unify name copyright format.
2019-01-25 09:45:57 +01:00
Milan Broz
bc3d0feb5c Switch default cryptographic backend to OpenSSL.
Cryptsetup/libcryptsetup currently supports several cryptographic
library backends.

The fully supported are libgcrypt, OpenSSL and kernel crypto API.

FIPS mode extensions are maintained only for libgcrypt and OpenSSL.

(Nettle and NSS are usable only for some subset of algorithms and
cannot provide full backward compatibility.)

For years, OpenSSL provided better performance for PBKDF.

Since this commit, cryptsetup uses OpenSSL as the default backend.

You can always switch to other backend by using a configure switch,
for libgcrypt (compatibility for older distributions) use:
--with-crypto_backend=gcrypt
2019-01-25 08:24:10 +01:00
Milan Broz
580f0f1a28 Add some FIPS mode workarounds.
We cannot (yet) use Argon2 in FIPS mode, hack scripts and library
to use PBKDF2 or skip tests and fix tests to run in FIPS mode.
2019-01-24 17:04:13 +01:00
Milan Broz
715b0c9b6c Switch to fetching default PBKDF values from library. 2019-01-23 14:15:23 +01:00
Milan Broz
388afa07f4 Cleunup devices before running mode-test. 2019-01-23 14:14:45 +01:00
Milan Broz
1def60cd2c Do not allow conversion to LUKS1 if hash algorithms differs (digest,AF). 2019-01-22 14:19:58 +01:00
Milan Broz
cdb4816fbb Allow setting of hash function in LUKS2 PBKDF2 digest.
For now, the hash was set to sha256 (except for converted LUKS1 header).

This patch adds the same logic as in LUKS1 - hash aglorithms is
loaded from PBKDF setting.

Fixes #396.
2019-01-22 12:45:01 +01:00
Milan Broz
be46588cf0 Allow LUKS2 keyslots area to increase if data offset allows it.
ALso deprecate align-plauload option and add more debugging code
to understand internal calculation of metadata and keyslots area sizes.

Fixes #436.
2019-01-22 09:23:49 +01:00
Milan Broz
6dc2f7231b Fix a possible NULL pointer in opt_type. 2019-01-21 14:07:33 +01:00
Milan Broz
3165b77ec9 Remove undeeded check for DM_SECURE_SUPPORTED. 2019-01-21 13:55:43 +01:00
Ondrej Kozina
ad0e2b86dc Do not issue flush when reading device status.
Fixes #417.
2019-01-21 11:20:02 +01:00
Milan Broz
5ee0b01118 Add test for specific legacy plain hash type. 2019-01-20 10:20:44 +01:00
Milan Broz
fbfd0c7353 Update Nettle crypto backend.
WARNING: this is just experimental backend, use only for testing.
2019-01-16 21:13:00 +01:00
Milan Broz
ee8970c11e Fix strncpy gcc warning. 2019-01-15 15:34:00 +01:00
Milan Broz
82a1f33260 Silence new warning in tests if run on older kernel. 2019-01-15 15:15:25 +01:00
Milan Broz
9607b322d2 Add missing struct to Nettle backend. 2019-01-15 15:00:36 +01:00
Milan Broz
238c74643b Add some more hash algorithms test. 2019-01-15 14:06:51 +01:00
Milan Broz
712c1783b6 Warn user if sector size is not supported by the loaded dm-crypt module.
Fixes #423.
2019-01-15 10:31:06 +01:00
Milan Broz
081fb6ec78 Do not try to read LUKS header if there is a clear version mismatch (detached header).
Fixes #423.
2019-01-14 20:14:46 +01:00
Milan Broz
c04d332b7f Do not require gcrypt-devel for authconfig.
The gcrypt does not use standard pkgconfig detection and requires
specific macro (part of gcrypt development fileS) to be present
during autoconfigure.

With other crypto backend, like OpenSSL, this makes no sense,
so make this part of autoconfigure optional.
2019-01-14 13:20:02 +01:00
Milan Broz
32786acf19 Add kernel crypt backend option to Travis build. 2019-01-14 09:11:01 +01:00
Milan Broz
51dd2762a9 Add --debug-json switch and log level.
The JSON structures should not be printed by default to debug log.

This flag introduces new debug level that prints JSON structures
and keeps default debug output separate.
2019-01-10 14:52:49 +01:00
Milan Broz
cf31bdb65c Workaround for test failure with disabled keyring.
NOTE: this need proper fix, tests should not expect a device state
from previous test.
2019-01-08 13:32:34 +01:00
Milan Broz
50cae84100 Print AF hash in luksDump. 2019-01-07 21:25:03 +01:00
Milan Broz
98feca280f Add crypt_get_default_type() API call. 2019-01-07 20:38:17 +01:00
Milan Broz
304c4e3d3b Add more common hash algorithms to kernel crypto backend.
Fixes #430.
2019-01-07 20:07:18 +01:00
Milan Broz
c5b55049b9 Fix AEAD modes check with kernel and Nettle backend.
These do not implement backend RNG yet, so use a fixed key for test.
2019-01-07 20:05:55 +01:00
Ondrej Kozina
c494eb94f4 Add LUKS2 refresh test.
Test refresh doesn't affect device vk.
2019-01-07 15:52:03 +01:00
Milan Broz
5f173e9357 Fix allocating of LUKS header on format.
Fixes #431.
2019-01-07 13:07:46 +01:00
Milan Broz
307a7ad077 Add keyslot encryption params.
This patch makes available LUKS2 per-keyslot encryption settings to user.

In LUKS2, keyslot can use different encryption that data.

We can use new crypt_keyslot_get_encryption and crypt_keyslot_set_encryption
API calls to set/get this encryption.

For cryptsetup new --keyslot-cipher and --keyslot-key-size options are added.

The default keyslot encryption algorithm (if cannot be derived from data encryption)
is now available as configure options (default is aes-xts-plain64 with 512-bits key).
NOTE: default was increased from 256-bits.
2019-01-07 13:07:46 +01:00
Milan Broz
0039834bb9 Rename function to describe precisely keys size it obtains.
This should avoid confusion between key size for the stored key and
key size that actually encrypts the keyslot.
2019-01-07 13:07:45 +01:00
Milan Broz
d064c625f4 Fix reencryption test to use more context lines to parse parameters. 2019-01-07 13:07:45 +01:00
Ondrej Kozina
77a62b8594 Remove trailing newline in loopaes error message. 2019-01-07 13:07:45 +01:00
Ondrej Kozina
d4339661df Fix cipher spec leak in crypt_format on error. 2019-01-07 13:07:45 +01:00
Ondrej Kozina
39a014f601 dm backend with support for multi-segment devices.
Support for multi-segment devices is requirement for online
reencryption to work. Introducing modififed dm backend that
splits data structures describing active device and individual
dm target (or segment).
2019-01-07 13:07:45 +01:00
Ondrej Kozina
1e22160e74 Fix dm-integrity auto-recalculation flag handling.
Fail with proper error message rather than silently
dropping the flag if not supported in kernel.
2019-01-03 19:57:23 +01:00
Milan Broz
267bf01259 Add crypt_get_pbkdf_type_params() API.
This function allows get default (compiled-in) PBKDF parameters
per every algorithm.

Fixes #397.
2019-01-03 14:13:01 +01:00
Milan Broz
e23fa65ef2 Fix leak of json struct on crypt_format() error path. 2019-01-02 14:08:41 +01:00
Milan Broz
ee7ff024c1 Use json_object_object_add_ex if defined.
The json-c lib changed json_object_object_add() prototype to return int,
this is backward incompatible.
2019-01-02 13:59:04 +01:00
Milan Broz
e8a92b67c3 Use snprintf. 2019-01-01 21:42:46 +01:00
Milan Broz
3ce7489531 Fix context init/exit pairing in libdevmapper.
And few small reformats.
2019-01-01 21:42:46 +01:00
Ondrej Kozina
ffbb35fa01 Update git ignore file. 2019-01-01 21:42:46 +01:00
Ondrej Kozina
de0b69691d Add json_object_object_del_by_uint helper routine. 2019-01-01 21:42:46 +01:00
Ondrej Kozina
82aae20e9c Add json_object_object_add_by_uint helper routine. 2019-01-01 21:42:46 +01:00
Ondrej Kozina
7362b14d41 Extend device-test with refresh actions. 2019-01-01 21:42:46 +01:00
Ondrej Kozina
77d7babf92 Add new crypt_resize tests. 2019-01-01 21:42:46 +01:00
Ondrej Kozina
545b347ca5 Add api test for CRYPT_ACTIVATE_REFRESH flag. 2019-01-01 21:42:46 +01:00
Ondrej Kozina
df2111eb4f Drop DEV_SHARED definition.
There are no users.
2019-01-01 21:42:46 +01:00
Ondrej Kozina
c7d3b7438c Replace DEV_SHARED with DEV_OK.
DEV_SHARED is never checked for in device_check.
2019-01-01 21:42:46 +01:00
Ondrej Kozina
5c0ad86f19 Move device_block_adjust() check lower in code. 2019-01-01 21:42:46 +01:00
Ondrej Kozina
675cf7ef59 Add dm_clear_device routine. 2019-01-01 21:42:46 +01:00
Ondrej Kozina
d74e7fc084 Add dm_error_device routine. 2019-01-01 21:42:46 +01:00
Ondrej Kozina
2cd85ddf11 Add stand alone dm_resume_device routine. 2019-01-01 21:42:46 +01:00
Ondrej Kozina
3c1dc9cfaa Refactor LUKS2 activation with dm-integrity. 2019-01-01 21:42:46 +01:00
Ondrej Kozina
8b2553b3f4 Split integrity activation between two function. 2019-01-01 21:42:46 +01:00
Ondrej Kozina
b9373700a2 Switch crypt_resize to reload internally.
This ties up few loose ends with regard to
target device parameters verification.
2019-01-01 21:42:46 +01:00
Ondrej Kozina
bdce4b84d8 Add new internal crypt_get_cipher_spec.
Add function for getting cipher spec (cipher
and mode) in convenient single string format.
2019-01-01 21:42:46 +01:00
Ondrej Kozina
2dd4609699 Implement cryptsetup refresh action (open --refresh alias).
It allows active device refresh with new activation
parameters. It's supported for LUKS1, LUKS2, crypt plain
and loop-AES devices.
2019-01-01 21:42:46 +01:00
Ondrej Kozina
5c67ca015b Add CRYPT_ACTIVATE_REFRESH flag to activation calls.
The new flag is supposed to refresh (reload) active dm-crypt
mapping with new set of activation flags. CRYPT_ACTIVATE_READONLY
can not be switched for already active device.

The flag is silently ignored for tcrypt, verity and integrity
devices. LUKS2 with authenticated encryption support is added in
later commit.
2019-01-01 21:42:46 +01:00
Ondrej Kozina
957b329e94 _dm_simple cleanup (wait is no longer needed) 2019-01-01 21:42:46 +01:00
Ondrej Kozina
120ebea917 Split low level code for creating dm devices.
The separate code for reloading device tables
will be used in later features.
2019-01-01 21:42:46 +01:00
Milan Broz
6e1e11f6cd Redirect lib API docs. 2018-12-19 11:56:36 +01:00
Milan Broz
dbc056f9ac Remove file commited by a mistake... 2018-12-13 22:29:51 +01:00
Ondrej Kozina
7de815e957 Silence annoying shell checks for dracut module.
Also fixes one theoretical issue with 'local' keyword for
any (if any) POSIX-strictly shell.
2018-12-12 15:08:06 +01:00
Ondrej Kozina
1894d6e6ff Add devno comparison for bdevs in device_is_identical(). 2018-12-12 15:07:33 +01:00
Ondrej Kozina
1cc722d0cc Simplify device_is_identical.
If any argument is null return false (with higher
priority than trivial identity check).

Also device_path can't return null if device struct gets
allocated succesfully.
2018-12-12 15:06:59 +01:00
Milan Broz
ec07927b55 Add cryptsetup options for LUKS2 header size settings.
Also print these area sizes in dump command.

NOTE: since now, the metadata area size in dump command contains
mandatory 4k binary section (to be aligned with API definition).
2018-12-12 14:51:40 +01:00
Milan Broz
41c7e4fe87 Remove incorrect parameter in crypt_reload test. 2018-12-12 12:28:42 +01:00
Milan Broz
217cd0f5e9 Do not use dd for JSON metadata tests.
This should fix random testsuite failures.
2018-12-12 11:51:44 +01:00
Milan Broz
fd02dca60e Add crypt_set_metadata_size / crypt_get_metadata_size API. 2018-12-11 21:59:59 +01:00
Milan Broz
2a1d58ed22 Check data device offset if it fits data device size in luksFormat. 2018-12-11 21:59:49 +01:00
Milan Broz
7d8003da46 cryptsetup: add support for --offset option to luksFormat.
This option can replace --align-payload with absolute alignment value.
2018-12-06 14:22:18 +01:00
Milan Broz
03edcd2bfd Add crypt_set_data_offset API function.
The crypt_set_data_offset sets the data offset for LUKS and LUKS2 devices
to specified value in 512-byte sectors.

This value should replace alignment calculation in LUKS param structures.
2018-12-06 11:10:21 +01:00
Milan Broz
a9d3f48372 Fix metadata test log message. 2018-12-05 19:46:28 +01:00
Milan Broz
316ec5b398 integrity: support detached data device.
Since the kernel 4.18 there is a possibility to speficy external
data device for dm-integrity that stores all integrity tags.

The new option --data-device in integritysetup uses this feature.
2018-12-05 19:42:31 +01:00
Milan Broz
d06defd885 Add automatic recalculation to dm-integrity.
Linux kernel since version 4.18 supports automatic background
recalculation of integrity tags for dm-integrity.

This patch adds new integritysetup --integrity-recalculate options
that uses this option.
2018-12-05 14:53:17 +01:00
Milan Broz
0fed68dd16 Introduce crypt_init_data_device and crypt_get_metadata_device_name.
For some formats we need to separate metadata and data device before
format is called.
2018-12-05 12:33:16 +01:00
Milan Broz
ce60fe04cb Update po files. 2018-12-04 16:28:25 +01:00
Milan Broz
4e1c62d7f1 Ignore false positive Coverity warning for string length. 2018-12-04 12:57:08 +01:00
Milan Broz
3ea8e01a9d Fix some cppcheck warnings.
Despite it is nonsense and cppcheck should understand the code better :-)
2018-12-04 12:30:14 +01:00
Milan Broz
9cbd36163c Fix various gcc compiler warnings in tests. 2018-12-03 13:47:43 +01:00
Milan Broz
0f5c3e107e Update README.md. 2018-12-03 10:35:50 +01:00
Milan Broz
1ae251ea5b Update LUKS2 docs. 2018-12-03 09:33:49 +01:00
Milan Broz
90742541c6 Add 2.0.6 release notes. 2018-12-03 09:30:48 +01:00
Milan Broz
84d8dfd46c Update po files. 2018-12-02 19:00:18 +01:00
Ondrej Kozina
3ed404e5bb Add validation tests for non-default metadata. 2018-12-02 18:56:59 +01:00
Ondrej Kozina
4b64ffc365 Update LUKS2 test images.
- update test images for validation fixes
  from previous commits

- erase leftover json data in between secondary
  header and keyslot areas.
2018-11-29 13:32:02 +01:00
Ondrej Kozina
e297cc4c2a Remove redundant check in keyslot areas validation.
Due to previous fix it's no longer needed to add
all keyslot area lengths and check if result sum
is lower than keyslots_size.

(We already check lower limit, upper limit and
overlapping areas)
2018-11-29 13:31:59 +01:00
Ondrej Kozina
9ab63c58f2 Fix keyslot areas validation.
This commit fixes two problems:

a) Replace hardcoded 16KiB metadata variant as lower limit
   for keyslot area offset with current value set in config
   section (already validated).

b) Replace segment offset (if not zero) as upper limit for
   keyslot area offset + size with value calculated as
   2 * metadata size + keyslots_size as acquired from
   config section (also already validated)
2018-11-29 13:31:54 +01:00
Ondrej Kozina
3c0aceb9f7 Reshuffle config and keyslots areas validation code.
Swap config and keyslot areas validation code order.

Also split original keyslots_size validation code in
between config and keyslot areas routines for furhter
changes in the code later. This commit has no funtional
impact.
2018-11-29 13:31:50 +01:00
Ondrej Kozina
d7bd3d2d69 Do not validate keyslot areas so frantically.
Keyslot areas were validated from each keyslot
validation routine and later one more time
in general header validation routine. The call
from header validation routine is good enough.
2018-11-29 13:31:46 +01:00
Ondrej Kozina
3136226134 Test cryptsetup can handle all LUKS2 metadata variants.
following tests:

add keyslot
test passphrase
unlock device
store token in metadata
read token from metadata
2018-11-27 16:56:57 +01:00
Ondrej Kozina
5a7535c513 Add LUKS2 metadata test images.
Test archive contains images with all supported
LUKS2 metadata size configurations. There's
one active keyslot 0 in every image that can be
unlocked with following passphrase (ignore
quotation marks): "Qx3qn46vq0v"
2018-11-27 16:54:51 +01:00
Milan Broz
991ab5de64 Fixe more context propagation paths. 2018-11-27 16:09:45 +01:00
Milan Broz
b17e4fa3bf Use context in PBKDF benchmark log. 2018-11-27 15:04:03 +01:00
Milan Broz
35fa5b7dfc Propagate context in libdevmapper functions. 2018-11-27 14:47:50 +01:00
Milan Broz
7812214db6 Add context to device handling functions. 2018-11-27 14:19:57 +01:00
Milan Broz
a5a8467993 Use context in debug log messages.
To use per-context logging even for debug messages
we need to use the same macro as for error logging.
2018-11-27 13:37:20 +01:00
Ondrej Kozina
544ea7ccfc Drop needless size restriction on keyslots size. 2018-11-27 11:25:40 +01:00
Ondrej Kozina
024b5310fa Add validation tests for non-default json area size.
Test both primary and secondary header validation tests
with non-default LUKS2 json area size.

Check validation rejects config.keyslots_size with zero value.

Check validation rejects mismatching values for metadata size
set in binary header and in config json section.
2018-11-26 16:28:07 +01:00
Ondrej Kozina
177cb8bbe1 Extend baseline LUKS2 validation image to 16 MiBs. 2018-11-26 16:28:01 +01:00
Ondrej Kozina
35f137df35 Move some validation tests in new section. 2018-11-26 16:27:52 +01:00
Milan Broz
c71ee7a3e6 Update POTFILES. 2018-11-25 16:02:59 +01:00
Milan Broz
9a2dbb26a5 Fix signed/unsigned comparison warning. 2018-11-25 15:11:44 +01:00
Milan Broz
3d2fd06035 Fix setting of integrity persistent flags (no-journal).
We have to query and set flags also for underlying dm-integrity device,
otherwise activation flags applied there are ignored.
2018-11-25 12:46:41 +01:00
Milan Broz
2f6d0c006c Check for algorithms string lengths in crypt_cipher_check().
The kernel check will fail anyway if string is truncated, but this
make some compilers more happy.
2018-11-25 10:55:28 +01:00
Milan Broz
43088ee8ba Fix unsigned return value. 2018-11-25 10:55:08 +01:00
Milan Broz
c17b6e7be3 Fix LUKS2_hdr_validate funtion definition. 2018-11-25 10:28:34 +01:00
Milan Broz
71299633d5 Properly handle interrupt in cryptsetup-reencrypt and remove log.
Fixes #419.
2018-11-24 20:10:46 +01:00
Milan Broz
dfe61cbe9c Fix sector-size tests for older kernels. 2018-11-24 20:10:03 +01:00
Milan Broz
18c9210342 Check for device size and sector size misalignment.
Kernel prevents activation of device that is not aligned
to requested sector size.

Add early check to plain and LUKS2 formats to disallow
creation of such a device.
(Activation will fail in kernel later anyway.)

Fixes #390.
2018-11-24 18:53:46 +01:00
Milan Broz
1167e6b86f Add support for Adiantum cipher mode. 2018-11-23 21:03:02 +01:00
Milan Broz
1684fa8c63 Do not run empty test set in main directory. 2018-11-22 16:30:33 +01:00
Milan Broz
b4dce61918 Try to check if AEAD cipher is available through kernel crypto API. 2018-11-22 16:02:33 +01:00
Milan Broz
d7ddcc0768 Reformat AF implementation, use secure allocation for buffer. 2018-11-22 16:02:00 +01:00
Milan Broz
36c26b6903 Properly propagate error from AF diffuse function. 2018-11-22 15:51:27 +01:00
Milan Broz
2300c692b8 Check hash value in pbkdf setting early. 2018-11-22 15:51:10 +01:00
Milan Broz
da6dbbd433 Fallback to default keyslot algorithm if backend does not know the cipher. 2018-11-22 15:49:56 +01:00
Ondrej Kozina
0a4bd8cb7d Remove unused crypt_dm_active_device member. 2018-11-22 15:49:21 +01:00
Ondrej Kozina
32d357e1a8 Secondary header offset must match header size. 2018-11-22 15:34:28 +01:00
Ondrej Kozina
21e259d1a4 Check json size matches value from binary LUKS2 header.
We have max json area length parameter stored twice. In
LUKS2 binary header and in json metadata. Those two values
must match.
2018-11-22 15:34:18 +01:00
Ondrej Kozina
c3a54aa59a Change max json area length type to unsigned.
We use uint64_t for max json length everywhere else
including config.json_size field in LUKS2 metadata.

Also renames some misleading parameter names.
2018-11-22 15:34:00 +01:00
Ondrej Kozina
7713df9e41 Enable all supported metadata sizes in LUKS2 validation code.
LUKS2 specification allows various size of LUKS2 metadata.
The single metadata instance is composed of LUKS2 binary header
(4096 bytes) and immediately following json area. The resulting
assembled metadata size have to be one of following values,
all in KiB:

16, 32, 64, 128, 256, 512, 1024, 2048 or 4096
2018-11-22 15:32:31 +01:00
Milan Broz
49900b79a9 Add branch v2_0_x to Travis. 2018-11-19 13:25:37 +01:00
Milan Broz
4f075a1aef Remove python dev from Travis script. 2018-11-09 10:28:29 +01:00
Milan Broz
d4cd902e1c Update po file. 2018-11-09 09:59:27 +01:00
Milan Broz
ef4484ab27 Remove python bindings in favour of liblockdev. 2018-11-09 09:18:41 +01:00
Ondrej Kozina
9e7f9f3471 Parse compat values from LUKS2 default segment encryption.
We used to preset compat cipher and cipher_mode values during
crypt_format() or crypt_load(). Since we can change 'default segment'
dynamically during reencryption (encryption, decryption included) we
need to parse those values from default segment json encryption field
each time crypt_get_cipher() or crypt_get_cipher_mode() is called.
2018-11-07 10:18:41 +01:00
Milan Broz
493e8580d6 Log all debug messages through log callback.
This cahnge allow to redirect all output of library
to a log processor.
2018-11-07 10:17:51 +01:00
Milan Broz
bce567db46 Add workaround for benchmarking Adiantum cipher. 2018-11-07 10:17:33 +01:00
Milan Broz
38e2c8cb8a Set devel version. 2018-11-07 10:16:35 +01:00
Milan Broz
16309544ac Fix ext4 image to work without CONFIG_LBDAF. 2018-11-05 12:00:01 +01:00
Milan Broz
517b5da67a Version 2.0.5. 2018-10-28 15:30:25 +01:00
Milan Broz
98460af44f Update LUKS2 docs. 2018-10-28 15:27:55 +01:00
Milan Broz
7213d5a76b Fix verbose message about key removal in luksKillSlot,luksErase and luksKremoveKey.
The crypt_keyslot_destroy() does not return keyslot number,
so return value 0 was always used as a keyslot reference.
2018-10-27 17:44:38 +02:00
Ondrej Kozina
bb29c5b322 Update man section describing convert command.
Fixes #414.
2018-10-26 10:07:41 +02:00
Milan Broz
58ad7bae48 Add 2.0.5 release notes. 2018-10-22 12:23:54 +02:00
Milan Broz
82a3480b12 Update po files. 2018-10-21 12:30:34 +02:00
Ondrej Kozina
c00811a846 Run LUKS2 validation code before header areas wiping.
Also drops redundant checks peformed in general validation code.
2018-10-18 08:48:48 +02:00
Milan Broz
27eaf46c8a Fix issues found by Coverity scan.
- possible overflow of data offset calculation in wipe and
- dereferencing of pointer in a keyring error path.
2018-10-14 21:50:06 +02:00
Milan Broz
202aeece3c Fix test module inclusion in tarball. 2018-10-14 20:54:06 +02:00
Milan Broz
825fc895dc Fix some signed/unsigned comparison warnings. 2018-10-14 20:36:45 +02:00
Milan Broz
a74aecedf1 Set devel version. 2018-10-14 20:24:34 +02:00
Milan Broz
fa1f63bcd0 Update po files. 2018-10-14 20:23:32 +02:00
Milan Broz
c2bce3e93e Wipe full header areas (including unused) during LUKS format.
All previous version of cryptsetup wiped only first 4k for LUKS1
and both JSON areas for LUKS2 (first 32k) and the allocated
keyslot area (as it contained the generated key).

Remaining areas (unused keyslots, padding, and alignment) were
not wiped and could contain some previous data.

Since this commit, the whole area up to the data offset is zeroed,
and subsequently, all keyslots areas are wiped with random data.

Only exceptions are
 - padding/alignment areas for detached header
   if the data offset is set to 0
 - bogus LUKS1 keyslot areas (upstream code never
   created such keyslots but someone could use that).

This operation could slow down luksFormat on some devices, but
it guarantees that after this operation LUKS header does not
contain any foreign data.
2018-10-14 13:11:50 +02:00
Milan Broz
a46733e701 Reintroduce error message if LUKS device is not detected.
Older cryptsetup printed this message through library,
later it disappeared even in cryptsetup binary.
2018-10-13 10:13:29 +02:00
Milan Broz
8f350f9b9f Print error message if crypt_load() detects unsupported version of LUKS. 2018-10-12 12:34:43 +02:00
Milan Broz
484692aacd Do not ask wiping questions in format if we just created the file. 2018-10-12 12:24:42 +02:00
Milan Broz
7f0df99511 Properly parse errno to error message for devices. 2018-10-12 12:03:56 +02:00
Milan Broz
bebd2fe7e7 Do not print error for used device twice. 2018-10-12 12:03:54 +02:00
Milan Broz
36e8839675 Do not fail if device is smaller than requested wipe size. 2018-10-11 21:20:34 +02:00
Ondrej Kozina
61305a50c1 Add delay=0 parameter to scsi_debug in all tests.
Speed up tests significantly.
2018-10-11 16:21:36 +02:00
Milan Broz
1d7749a40f Show better errors if kesylot decryption fails.
This happens also in cipher check where the old message was
very confusing.
2018-10-11 15:41:35 +02:00
Milan Broz
f01d044618 Print file name size instead of a loop device in error messages. 2018-10-11 15:40:22 +02:00
Milan Broz
31532adf86 Do not copy buffer if read fails. 2018-10-11 15:39:31 +02:00
Milan Broz
879e06db39 Wiping empty device should not fail. 2018-10-11 15:38:56 +02:00
Milan Broz
4beb0f702a Do not allow device activation if data area overlaps with LUKS header. 2018-10-11 11:55:45 +02:00
Ondrej Kozina
a771460dbd Add validation tests for optional segment flags section. 2018-10-11 11:55:26 +02:00
Ondrej Kozina
f849f83d84 Add validation code for option flags section of segment. 2018-10-11 11:55:22 +02:00
Ondrej Kozina
1d084a41ad Add support for optional flags section in LUKS2 segments dump. 2018-10-11 11:55:18 +02:00
Ondrej Kozina
c4198986f1 Sort LUKS2 segments by keys in crypt_dump output. 2018-10-11 11:55:13 +02:00
Milan Broz
7514786b20 Add an error message if device is unusable. 2018-10-04 20:00:12 +02:00
Milan Broz
9df042c0b8 Use explicit_bzero if available. 2018-10-04 15:21:01 +02:00
Ondrej Kozina
37e0150f70 Do not use fallocate in blockwise tests.
fs driver may skip some sanity checks if it's aware the content
of file is uninitialized.

Fixes warnings for xfs in kernel 4.19+
2018-10-04 11:20:03 +02:00
Milan Broz
294e4cbcb7 Fix tcrypt test on very old distros. 2018-10-02 13:56:57 +02:00
Milan Broz
952716afe1 Report versions in test run. 2018-10-02 13:46:03 +02:00
Milan Broz
24aba9a514 tcrypt: Support additional Veracrypt modes.
Add support for Camellia and Kuznyechik ciphers and Streebog hash functions,
introduced in recent Veracrypt.

Note, that Kuznyechik requires out-of-tree kernel module and Streebog
hash function is available only with gcrypt backend.
2018-10-02 10:47:38 +02:00
Milan Broz
905993751c Fix integritysetup build. 2018-09-29 18:28:10 +02:00
Milan Broz
0b10d877b0 Some more gcc warnings fixes. 2018-09-29 17:32:33 +02:00
Milan Broz
874fa5810d Do not use local libutils. 2018-09-29 10:42:05 +02:00
Milan Broz
5be31bbce6 More warnings fixes. 2018-09-27 20:54:06 +02:00
Milan Broz
a6e3a31690 Workaround for some gcc8 warnings.
Some new string length checks are too clever now...
2018-09-27 13:25:52 +02:00
Milan Broz
506f3f7b57 Decrease memory limit for pbkdf test. 2018-09-26 10:48:31 +02:00
Ondrej Kozina
cd1c36ef94 Allow passphrase change for unbound keyslots.
Also fixes small typo in API.

Fixes #409.
2018-09-25 13:13:31 +02:00
Ondrej Kozina
ee689d88b4 Add blkid scan when attemting to open plain device.
Warn user about existing device signatures on candidate ciphertext
device and prompt for action confirmation.

Fixes #411.
2018-09-25 13:13:18 +02:00
Ondrej Kozina
b93b676336 Move blkid scan after device context initialization.
Fixes bug with misleading error message when target device
does not exist.
2018-09-25 08:55:24 +02:00
Ondrej Kozina
1c6d66fccc Emit error message for converting inactive keyslot.
Fixes: #416.
2018-09-25 08:53:48 +02:00
Ondrej Kozina
114356ad2e Properly load new device context after header restore. 2018-09-25 08:53:26 +02:00
Ondrej Kozina
7ab419701c Rename get_key_size_strlen() to int_log10().
because that's what the function does
2018-09-25 08:52:29 +02:00
Ondrej Kozina
d41b1a7560 Unify checks for misaligned values. 2018-09-25 08:51:51 +02:00
Ondrej Kozina
622943529e Wipe LUKS header if luksFormat fails to add first keyslot. 2018-09-25 08:45:03 +02:00
Ondrej Kozina
9d7cc152f9 Do not enforce iv_tweak alignment in LUKS2 validation.
1) iv_tweak is not in 'bytes'
2) it may be arbitrary number
3) there's no reason to enforce alignment to encryption sector size

Fixes #406.
2018-09-25 08:44:31 +02:00
Milan Broz
3f73d448f3 Retry temporary device removal in align test. 2018-09-10 15:53:27 +02:00
Milan Broz
a1b606803f Fix HMAC vector test exit value. 2018-09-05 14:38:16 +02:00
Michal Virgovič
b2c7b40568 Add test vectors for HMAC - sha1, sha256, sha512. 2018-09-05 14:17:25 +02:00
Milan Broz
0cbe09d43a Rephrase LUKS info. 2018-09-03 15:16:31 +02:00
Milan Broz
f1d5b94762 Run API tests without verbose flag by default.
And rename some tests.
2018-08-10 12:36:15 +02:00
Ondrej Kozina
6fc2e7c774 Skip pbkdf benchmark in align-test (test speedup). 2018-08-10 08:20:00 +02:00
Ondrej Kozina
3b39c1d1ef Fix data alignment test in compat-test2.
Alignment should not expected failure when --align-payload is not
aligned to encryption sector size.
2018-08-10 08:19:49 +02:00
Ondrej Kozina
5a3e4abf71 Add basic LUKS2 align test. 2018-08-10 08:19:38 +02:00
Ondrej Kozina
48e9362186 Do not enforce encryption sector size alignment on data offset.
crypt segment data offset has nothing to do with encryption sector
size. The device may hint alignment offset which is completely
unrelated and LUKS2 validation blocks it.
2018-08-10 08:19:17 +02:00
Ondrej Kozina
03a74b74e5 Revert "Fix data alignment calculations with custom encryption sector size."
This reverts commit 71dd149ca2.

Enforcing data alignment to be encryption sector size aligned
is completelly wrong. The underlying data device alignment
has nothing to do with dm-crypt internal encryption sector size.

The restriction is however valid for dm-crypt segment size.
2018-08-10 08:19:02 +02:00
Ondrej Kozina
248f99cad3 Data alignment is always 512B sectors count. 2018-08-10 08:18:18 +02:00
Ondrej Kozina
d2f0773eb8 Remove useless division followed by multiplication by same base. 2018-08-10 08:16:27 +02:00
Ondrej Kozina
dd36d56d47 Fix miscalculation of device alignment offset.
device_topology_alignment routine already returns alignment offset
in bytes. There's no need to divide it by sector size, since LUKS2
format have all offsets and sizes stored in bytes.
2018-08-10 08:15:01 +02:00
Milan Broz
0270fc66a1 Fix align test.
Seems that the forced alignment value was never properly used...
2018-08-09 13:53:48 +02:00
Milan Broz
69a844c654 Remove O_SYNC from device open and use fsync().
This speed up wipe operation considerably.
2018-08-09 12:01:20 +02:00
Ondrej Kozina
5b5a64361f Update blockwise-compat test.
Issue warning in case of failure with file-systems based
tests.

Mute the test so that it prints out messages only for 'warning'
and 'fail' results.
2018-08-08 21:48:10 +02:00
Milan Broz
26f6d1cb10 Create --master-key-file in luksDump and fail if file already exists.
For some reason the volume key file have to exists.

Let's change the logic to the same as for luksBackupHeader
(a file is created and operation fails if it already exists).
2018-08-08 14:32:15 +02:00
Ondrej Kozina
f87eb1668a Allow compat-test2 to run with larger LUKS2 header size. 2018-08-08 12:55:29 +02:00
Milan Broz
3114abfd55 Remove not needed -Z option from diff that is not present on older systems. 2018-08-08 10:43:03 +02:00
Ondrej Kozina
5a94cff91e Do not fail device-test with larger LUKS2 header. 2018-08-08 10:13:40 +02:00
Ondrej Kozina
d704e87ee4 No need to lock data device in crypt_format. 2018-08-08 08:54:42 +02:00
Ondrej Kozina
c8ce996872 Wipe data device in crypt_format with auth. encryption.
crypt_wipe_device was called incorrectly on metadata device even
though integrity header is always on data device from cryptsetup
pov. During LUKS2 crypt_format with detached header scenario we
would wiped first 8 sectors of metadata device instead of data
device.
2018-08-08 08:52:44 +02:00
Milan Broz
0e7b068061 Add sector-size & payload align test. 2018-08-08 08:45:26 +02:00
Ondrej Kozina
71dd149ca2 Fix data alignment calculations with custom encryption sector size. 2018-08-08 08:01:45 +02:00
Ondrej Kozina
b30ba41d6a Fix typo in blockwise-compat test. 2018-08-08 07:44:07 +02:00
Ondrej Kozina
a0bf790892 Fix FAST_PBKDF typos in LUKS2 reencrypt tests. 2018-08-08 07:43:56 +02:00
Ondrej Kozina
caefc4eb8e Add basic test for token import and export. 2018-08-08 07:42:58 +02:00
Milan Broz
31364c17d6 Fix configure typo in previous patch. 2018-08-07 15:28:43 +02:00
Milan Broz
5e56966e72 Make tests for strings in configure more consistent.
Intead of
  test x$enable_xyz = xyes;
use
  test "$enable_xyz" = "xyes"; then
2018-08-07 09:29:51 +02:00
Milan Broz
1f951ed7ec Use AC_ARG_ENABLE consistently.
AC_ARG_ENABLE(feature, ...) -> AC_ARG_ENABLE([feature], ...
2018-08-07 08:37:55 +02:00
joerichey@google.com
ecd82f1fc9 Fix configure.ac formatting
Currently, AC_ARG_[ENABLE|WITH] are used in multiple different ways.
This change makes all their uses the same by following the style of
the GNU manual:
  - AC_ARG_ENABLE(foo) should only define $enable_foo
  - Use the 2 argument form with a --enable_foo flag
  - Use the 4 argument form with a --disable_foo flag
  - Format all uses the same way
  - Always compare using: test "x$enable_foo" = "xyes"

This makes the easier to debug, more readable, and shorter.

This formatting fix also revealed a bug (fix submitted seperately).
2018-08-07 08:21:25 +02:00
Milan Broz
7aaf1eeb1b Fix bz2->xz untar api-test option. 2018-08-06 15:16:39 +02:00
Milan Broz
e53fe70668 Use only xz archives in tests.
Bzip2 is sometimesmissing and we use xz already.

Seems xz produces slightly larger archives (despite the best mode)
but it is not worth to keep bz2 here.
2018-08-06 13:48:54 +02:00
Milan Broz
9e2e0a4a2d Update Readme.md 2018-08-03 12:51:22 +02:00
Milan Broz
b52719fd73 Version 2.0.4. 2018-08-03 12:31:21 +02:00
Milan Broz
7953976d25 Add 2.0.4 Release Notes 2018-08-03 12:29:31 +02:00
Ondrej Kozina
39d6b94835 Add test for reencryption after format conversion. 2018-08-03 11:15:43 +02:00
Ondrej Kozina
4fdce0695d Add test for LUKS2 detached header with non-default alignment. 2018-08-03 11:15:33 +02:00
Ondrej Kozina
ae8247fe6a Calculate keyslots area size properly with detached headers.
When LUKS2 crypt_format() is called with detached header and custom data
alignment is requested, keyslots area is miscalculated. This mistake
is correctly detected by LUKS2 validation code but it's feature
regression with regard to LUKSv1 format.
2018-08-03 11:15:27 +02:00
Milan Broz
d664565174 Add snapshot of LUKS2 docs. 2018-08-02 15:47:56 +02:00
Ondrej Kozina
b24a46ad8f Add tests for updated segments validation.
Tests commit c1777cfb8
2018-08-02 09:21:23 +02:00
Ondrej Kozina
6bffe34faa Fix problem found by Coverity scan.
NEGATIVE_RETURNS from crypt_hmac_size().
2018-08-02 09:19:57 +02:00
Milan Broz
abe3fb4acb Return no encryption if segment is not crypt type.
Currently the code expects "cipher" everywhere, this is temporary
workaround to enable basic operations if other segmens are present
in metadata.
2018-08-01 13:58:08 +02:00
Ondrej Kozina
39905bd8fd Return proper err when looking for segment digest.
Otherwise keyslot in luksDump are wrongly marked as device
keyslots even though default segment is not crypt.
2018-08-01 13:57:06 +02:00
Ondrej Kozina
078dbfb0a9 Do not dump crypt segment specific fields for other types. 2018-08-01 13:56:50 +02:00
Ondrej Kozina
dfeb5cfdd2 Do not allow segment with size set to 0. 2018-08-01 13:56:40 +02:00
Ondrej Kozina
c1777cfb89 Move crypt specific segment validation in new routine.
Also rename all 'length' variable to 'size' since json
field is named size.

Make segment validation two step process. First
validate general segment object is valid and later
validate specific segment type has all necessary fields.

Without this patch older libraries won't be able to print out
(luksDump) basic information about devices created with newer
libraries.
2018-08-01 13:55:28 +02:00
Ondrej Kozina
974072bdae Add segment validation tests. 2018-08-01 13:53:14 +02:00
Ondrej Kozina
b95e18956f Fix possible segfault in validation code.
If any segment has missing 'offset' field keyslots validation
routine could trigger segfault due to misuse of function that
expects valid 'segments' object.

Fix it by reordering validation routines.
2018-08-01 13:52:46 +02:00
Michal Virgovič
3c1c5ef281 Add vector tests for hash algorithms. 2018-08-01 09:16:44 +02:00
Ondrej Kozina
7194b14cd2 Fix typo in crypt_persistent_flags_set documentation. 2018-07-27 13:50:34 +02:00
Milan Broz
4e6f8d561c Update po files. 2018-07-27 08:39:49 +02:00
Milan Broz
ac26921569 Add support for dm-integrity superblock V2.
Only support parsing superblock data,
new functions will be supported in later kernel and releases.
2018-07-21 15:24:07 +02:00
Rafael Fontenelle
a60543728b Remove unmatched parethensis
This string had parentheses around part of the text, but it was restyled.
2018-07-21 07:25:52 -03:00
Rafael Fontenelle
f35ec9771e Fix typos
A bunch of typos reported by codespell, most of them comments in the code
2018-07-21 07:24:25 -03:00
Ondrej Kozina
de4fe99e34 Silence empty stdin error message in tests. 2018-07-21 11:28:46 +02:00
Ondrej Kozina
8ea6b3eebd Redirect stdout to stderr during reencryption in initrd.
Stdout is not printed in initrd unless user invokes debug mode.
It's inconvenient to have users waiting for reencryption to
finish with no input at all.
2018-07-21 11:28:41 +02:00
Milan Broz
a01836fe8d Update po files. 2018-07-21 11:28:24 +02:00
Ondrej Kozina
268dc97857 Emit error when there's nothing to read from key file. 2018-07-20 15:24:16 +02:00
Milan Broz
fc203c9654 Set devel version. 2018-07-19 14:48:34 +02:00
Milan Broz
8eedd5b277 Update po files. 2018-07-19 14:47:06 +02:00
Milan Broz
561d9ac2bc Fix problems found by Coverity scan. 2018-07-19 14:45:46 +02:00
Milan Broz
1112da76f1 Fix some compiler warnings. 2018-07-19 14:45:37 +02:00
Ondrej Kozina
081aa18f39 Exclude valgrind logs from git. 2018-07-19 14:45:29 +02:00
Milan Broz
c05c8bbba1 Fix switched parameters in cryptsetup-reencrypt. 2018-07-19 14:45:23 +02:00
Milan Broz
eabd23f31e Print verbose message about keyslot and token numbers.
Move all messages to cryptsetup tools and print these
verbose messages:

  - Key slot X unlocked.
  - Key slot X created.
  - Key slot X removed.
and
  - Token X created.
  - Token X removed.

Also print error, if unknown token is tried to be removed.
2018-07-19 14:45:16 +02:00
Ondrej Kozina
cc27088df9 Add support for LUKS2 token export and import. 2018-07-19 14:44:54 +02:00
Ondrej Kozina
97ab7e9c65 Add interruptible variants of buffered io. 2018-07-19 14:44:42 +02:00
Ondrej Kozina
bbf92828f6 Move buffered io implementation in new functions.
No functional changes yet. See later commits.
2018-07-19 14:44:37 +02:00
Milan Broz
2f83bf9f83 Change wording of blkid signature messages. 2018-07-18 13:22:11 +02:00
Ondrej Kozina
b2a1728201 Fix bundled argon2 distcheck errors. 2018-07-18 11:57:43 +02:00
Ondrej Kozina
18cbbbe9aa Silent compiler warning about unused code. 2018-07-18 11:56:34 +02:00
Ondrej Kozina
d90f8a3697 Remove useless redeclaration in blkid_utils. 2018-07-18 11:56:19 +02:00
Ondrej Kozina
fe3ef6fc2e Fix type mistake in blkid_handle allocation. 2018-07-18 11:56:12 +02:00
Ondrej Kozina
1b9148f12f dracut-reencrypt: add --progress-frequency parameter 2018-07-18 11:56:04 +02:00
Ondrej Kozina
deb8e49483 Cleanup test files after failure.
'missing-file' must be removed if test failes. Otherwise
the test fails even after regression is fixed :)
2018-07-18 11:55:53 +02:00
Ondrej Kozina
d75af2a156 Move pwquality libs in tools. 2018-07-18 11:55:47 +02:00
Ondrej Kozina
9895edefff Fix misleading parameter name in crypt_keyfile_device_read.
This patch has no functional impact. It only renames misleading
parameter 'keyfile_size_max' to 'key_size' because that's
how it's actually interpreted since beginning. Also updated
API documentation accordingly.
2018-07-18 11:55:20 +02:00
Ondrej Kozina
b60e856087 Rephrase error message for invalid --type param in convert. 2018-07-17 10:53:20 +02:00
Milan Broz
6244b4d00f Use LANG=C in interactive tests. 2018-07-13 08:58:38 +02:00
Milan Broz
ee167b1a43 Fix offset parsing in unit test. 2018-07-11 22:41:15 +02:00
Ondrej Kozina
e8b9bfe44c Use 'cannot' instead of 'can not' in every message. 2018-07-11 22:39:31 +02:00
Ondrej Kozina
50f5593ffc Update dm-crypt version check in device-test.
Test is now able to detect backported sector_size feature
in RHEL7 kernels.
2018-07-11 22:24:26 +02:00
Ondrej Kozina
3f0f7acbc0 Update cryptsetup man page for --type option usage.
Fixes #394.
2018-07-11 22:24:05 +02:00
Ondrej Kozina
7f6f8ec386 Test fixes for pbkdf verifications. 2018-07-11 22:23:53 +02:00
Ondrej Kozina
24d1798779 Fix mistakes in pbkdf_type verification.
- hash is currently relevant only for pbkdf2
- time_ms may be unset (zero) if forced iterations
  are set.

Fixes #398.
2018-07-11 22:23:41 +02:00
Ondrej Kozina
3e9d603f0b Add cryptsetup repair tests. 2018-07-11 22:23:24 +02:00
Ondrej Kozina
71a8fd3106 Test basic LUKS2 repair capabilities.
a) checks crypt_load() fails when single LUKS2 header is corrupted and
   blkid detect other device signature from LUKS or none.
b) check explicit crypt_repair is able to override blkid restriction
   and fix corrupted primary header
c) check a) and b) with disabled locks
2018-07-11 22:23:10 +02:00
Ondrej Kozina
49279a3c19 Print device signatures before prompt in repair action. 2018-07-11 22:22:47 +02:00
Milan Broz
43a1291f7c Add Argon2 SSE compile to Travis script. 2018-07-11 22:22:32 +02:00
Milan Broz
6dc5340f60 Add libblkid-dev to Travis script install. 2018-07-11 22:22:16 +02:00
Ondrej Kozina
2a6e33bc73 Add prompt for integritysetup format action.
Also adds blkid wipe support when user confirms format action.
2018-07-11 22:22:04 +02:00
Ondrej Kozina
0f6b2cfd3d Wipe all device signatures in luksFormat action. 2018-07-11 22:21:51 +02:00
Ondrej Kozina
30d109c0e9 Add support for blkid scans and signature wiping in tools. 2018-07-11 22:21:32 +02:00
Ondrej Kozina
e8e1f844d9 Extend blkid utilities for signatures wiping.
For older distributions there's fallback mode for missing
blkid_do_wipe function. We erase signatures based on offsets
and lengths detected by blkid.
2018-07-11 22:20:54 +02:00
Ondrej Kozina
05a89e5566 Allow LUKS2 repair with disabled locks. 2018-07-11 22:20:31 +02:00
Ondrej Kozina
c122889c95 Update crypt_repair API documentation for LUKS2. 2018-07-11 22:20:16 +02:00
Ondrej Kozina
9de5dc932b Allow explicit LUKS2 repair.
Also moves FIXME comment lower to LUKS2 code with note that currently it's
safe to do crypt_repair on LUKS2 format without paying attention to LUKS2
requirements.
2018-07-11 22:19:58 +02:00
Ondrej Kozina
289c9ecf5d Allow LUKS2 repair to override blkid checks.
Allow user to run cryptsetup repair command and explicitly do
repair on corrupted LUKS2 headers where blkid decides it's no longer
a LUKS2 device.
2018-07-11 22:19:47 +02:00
Ondrej Kozina
2c1a6e3f94 Make LUKS2 auto-recovery aware of device signatures.
auto-recovery triggers any time when only single correct LUKS2
header instance was found. That may be dangerous.

We should suppress auto-recovery in case blkid decided the
device is no longer LUKS device. For example if secondary (intact)
LUKS2 header was left behind and blkid declares the device is LVM2
member.

Moreover if at least one header instance is corrupted and blkid
declares device non-empty and non-LUKS in the same time, header load
operation will be aborted with error.
2018-07-11 22:19:35 +02:00
Ondrej Kozina
ad092a898d Add blkid utilities for fast detection of device signatures. 2018-07-11 22:19:11 +02:00
joerichey@google.com
56f2548b6e Fix --disable-dev-random bug
--disable-dev-random now disables reading from /dev/random instead of
incorrectly enabling it. This was found by reviewing all of flags
in configure.ac.
2018-07-11 22:03:47 +02:00
joerichey@google.com
25467243a6 Add missing call to crypt_random_exit
We call crypt_random_init in init_crypto, but never call
crypt_random_exit. This change just copies what the crypt_backend
functions do, and calls crypt_random_exit in the descructor.
2018-07-11 22:03:44 +02:00
joerichey@google.com
e07d40fc26 Fix .gitignore to ignore all generated files 2018-07-11 22:03:41 +02:00
Milan Broz
09877e4e63 Use explicit list for LUKS2 secondary header offsets.
The code scan for the second header only if primary is corrrupted.

Let's set the possible offsets more clear.

This patch also removes 8kB header offset (that was not supported anyway).
2018-07-11 10:05:36 +02:00
Milan Broz
d3460b6cf5 Fix internal bundled Argon2 build. 2018-07-07 11:06:54 +02:00
Milan Broz
ba384d15d2 Add optimized Argon2 SSE code.
Note: it is always better to use external libargon2 library.

Unfortunately, until Argon2 is in generic crypto libraries,
we must sometimes use bundled version just for bureaucratic reasons.

Let's include optimized variant of reference implementation as well.

Note, this code will not add any SSE compiler switches.

If --enable-internal-sse-argon2 option is used, it checks if current
compilation flags support simple SSE progam and if so, it use
the optimized variant.
(Not tested for AVX optimizations; it expects that SSE is enabled as well.)
2018-07-07 10:36:49 +02:00
Milan Broz
2f38ade0e0 Update Argon2 header to match upstream. 2018-07-07 10:35:23 +02:00
Ondrej Kozina
4d110d4c82 Silence luksFormat in tests. 2018-07-07 10:26:32 +02:00
Ondrej Kozina
1bf5ff3e6e Open files in read-write mode for posix_fallocate.
Unfortunately there exists some weird NFS variations requiring read
permissions for fallocate.
2018-07-07 10:25:01 +02:00
Milan Broz
cd2a1a169f Skip test if scsi_debug is not available. 2018-07-07 10:24:35 +02:00
joerichey@google.com
59b5f360af Make all header files self-suffienct
Almost all the headers in cryptsetup are self-suffienct (in that they
compile on their own). By including <stddef.h>, <stdint.h>, or
<sys/types.h>, all headers will now compile on their own.

This is useful for importing cryptsetup into Bazel/Blaze.
2018-07-07 10:23:39 +02:00
joerichey@google.com
e8b6890318 Don't implicitly discard const
As poptGetOptArg() returns "const char *", assigning it to a
"const char *" varible triggers a warning on Clang:
"incompatible-pointer-types-discards-qualifiers".
2018-07-07 10:22:57 +02:00
Ondrej Kozina
d7b9ed05f0 Add scsi_debug_teardown loop in blockwise tests.
scsi_debug module sometimes fails to remove due to
open references from udev scans.
2018-06-20 16:58:25 +02:00
Ondrej Kozina
dc852a100f Fix write_blockwise on short files.
see unit test write_blockwise(length=2097153, bsize=4096), on x86
with original test file size=2097152.

The test is trying to write_blockwise 1 more byte than actual file
size.
2018-06-20 16:58:19 +02:00
Ondrej Kozina
838d51d296 Fix write_lseek_blockwise for in the middle of sector case.
See unit test write_lseek_blockwise(bsize=512, offset=1, length=1).

The test tries to modify single byte at offset 1 of device with
bsize=512.
2018-06-20 16:58:01 +02:00
Ondrej Kozina
e2845bc032 Zero length lseek blockwise i/o should return zero.
Note that both functions perform seek operations aligned to sector
boundary if possible before returning.

Unaligned input offset gets aligned on first preceding sector
boundary.
2018-06-20 16:57:54 +02:00
Ondrej Kozina
8c021fd784 Extend blockwise unit tests on files. 2018-06-20 16:57:46 +02:00
Ondrej Kozina
406ec14585 Add unit tests for low level io helpers. 2018-06-20 16:57:40 +02:00
Ondrej Kozina
c27b42e425 Make low level io functions internal library.
it's prerequisite for later unit tests
2018-06-20 16:57:33 +02:00
joerichey@google.com
2d94d7ab0c Fix declaration of logger()
This change makes the declaration of logger() match its definition,
it also avoids the use of the "class" C++ keyword. This is useful for
importing cryptsetup into Bazel/Blaze.
2018-06-19 08:27:46 +02:00
Milan Broz
5fcf430c81 Fix crypto backend for LibreSSL >= 2.7.0.
There are now OpenSSL 1.1.x API functions, no need for compatibility wrapper.

Fixes #393.
2018-06-17 16:45:09 +02:00
Milan Broz
cea4b3e363 Fix #389 Base64 typo. 2018-06-07 08:37:23 +02:00
Milan Broz
e00d8fb544 Add basic tests for new AEAD modes. 2018-05-21 15:52:31 +02:00
Milan Broz
e654fabe04 Add some new AEAD modes and allow SHA1 for integrity check.
NOTE: all this code will be switched to generic checks, this list
is just a temporary hack.
2018-05-21 15:29:49 +02:00
Milan Broz
18592a08be Update readme.md. 2018-05-03 22:45:48 +02:00
Milan Broz
1763260578 Update po files. 2018-05-03 21:30:29 +02:00
Milan Broz
955f10e621 Add 2.0.3 release notes. 2018-05-03 21:29:39 +02:00
Ondrej Kozina
2565fedeb7 Add test for stand-alone --keep-key parameter.
The --keep-key should work when no other parameters are requested.
It was meant to be "apply defaults on original header".
2018-05-03 20:23:41 +02:00
Ondrej Kozina
6b8e553ecc Remove subcondition for reencryption --keep-key parameter.
If removed subcondition was true --keep-key parameter (alone)
would fail the command. But it is valid to request reencryption
of LUKS header and applying defaults to pbkdf parameters.
2018-05-03 20:23:38 +02:00
Ondrej Kozina
14f81cb275 Fix few typos in cryptsetup-reencrypt man page. 2018-05-03 14:41:18 +02:00
Milan Broz
ddb844226d Run PBKDF2 benchmark always.
The PBKDF2 benchmark heavily depends on exported volume key length,
so we either have to remeber benchmarked length or just run test always.

For other KDFs the dependence on generated key length is negligible,
so we can cache benchmark.
2018-05-03 13:01:54 +02:00
Milan Broz
f87ee5112a Fix check for AEAD cipher.
The crypt_get_integrity() can be not yet set, check for key size
explicitly (otherwise we reject composed ciphers in keyslot check too early.)
2018-05-03 13:00:40 +02:00
Milan Broz
2a1a773777 Fixes and workarounds for some Coverity scan reports. 2018-04-30 12:26:12 +02:00
Milan Broz
7fede3ee45 Update po files.
(Version 2.0.3.1 is just resping of translation strings with
trimmed EOL characters.)
2018-04-30 08:03:40 +02:00
Ondrej Kozina
abcd3511bf Fix memory leak in luksKillSlot action. 2018-04-26 16:39:39 +02:00
Milan Broz
a387557970 Introduce crypt_keyslot_get_key_size()
This function allows to get key size even for unboud keyslots.
2018-04-26 14:24:10 +02:00
Milan Broz
daba04d54b Update po files. 2018-04-26 11:50:42 +02:00
Milan Broz
b00a87d8fa Remove trailing EOL for verbose and error messages. 2018-04-26 10:38:17 +02:00
Milan Broz
aee55b0595 Use fixed buffer in log function.
And unify EOL for error and verbose messages.
2018-04-26 10:00:31 +02:00
Milan Broz
e58883c183 Hide return code check fot fallocate (that can silenty fail in this context). 2018-04-26 09:55:31 +02:00
Milan Broz
321e840c1c Fix some signed/unsigned warnings. 2018-04-25 14:59:36 +02:00
Milan Broz
19ac1dd393 Fix Veracrypt PIM iteration calculation for system volumes
According to
https://www.veracrypt.fr/en/Personal%20Iterations%20Multiplier%20%28PIM%29.html

The PBKDF2-SHA512 and PBKDF2-Whirlpool KDF for system volumes uses the same
formula as normal encryption.

Thanks Bernhard Kirchen for original patch.
2018-04-25 14:01:36 +02:00
Ondrej Kozina
13796ee4c7 Add --with-default-luks-format configure time option.
Add option to override default LUKS format version (currently LUKS1).
2018-04-25 12:19:45 +02:00
Milan Broz
10bb78458d Move EOL in tool verbose and error messages to log wrapper. 2018-04-25 10:43:02 +02:00
Milan Broz
6997506bb9 Fix error messages and include benchmark string for translators. 2018-04-25 09:35:11 +02:00
Milan Broz
480c7178a8 Do not use trailing period in options help texts. 2018-04-25 08:41:59 +02:00
Milan Broz
0279d8f466 Update po files. 2018-04-25 08:32:40 +02:00
Milan Broz
1a6183d0c4 Fix non-translated string with default integrity algorithm macro.
Fixes #377.
2018-04-25 08:29:34 +02:00
Milan Broz
487acbb573 Merge branch 'veracrypt-kdf-preference' into 'master'
adjust KDF preference to VeraCrypt order

See merge request cryptsetup/cryptsetup!39
2018-04-24 21:08:28 +00:00
Milan Broz
f97eba6539 Merge branch 'tcryptDump-pim-support' into 'master'
tcryptDump: fix support for --veracrypt-pim

See merge request cryptsetup/cryptsetup!37
2018-04-24 21:02:19 +00:00
Milan Broz
cac84abdd9 Merge branch 'urlencode-veracrypt-docs-link' into 'master'
urlencode brackets in URL to VeraCrypt PIM docs

See merge request cryptsetup/cryptsetup!36
2018-04-24 21:00:10 +00:00
Bernhard Kirchen
ef045f9f65 adjust KDF preference to VeraCrypt order
RIPEMD160 is not even allowed any more as an option when creating an
encrypted file container using VeraCrypt. when encryption the system
partition/drive, it is below SHA256 in the list of options.

the order is like that since VeraCrypt version 1.0f (2014-12-30,
see https://www.veracrypt.fr/en/Release%20Notes.html).
2018-04-24 22:22:55 +02:00
Bernhard Kirchen
6002099288 tcryptDump: fix support for --veracrypt-pim
the user provided PIM value was not forwarded to the respective
implementation dumping the VeraCrypt header information.

extends the tcrypt-compat-test such that tcryptDump is performed
on VeraCrypt containers as well.
2018-04-24 22:20:06 +02:00
Bernhard Kirchen
181f621a90 urlencode brackets in URL to VeraCrypt PIM docs 2018-04-24 21:54:26 +02:00
Milan Broz
5a71c6f2eb Set devel version. 2018-04-24 20:22:00 +02:00
Milan Broz
487965dc8a Fix LUKS convert on trimmed headers in file.
If last write in move area failed, the keyslot is in fact destroyed.

We need to at least ensure that the whole area is there
(so write fails only for hard errors).
2018-04-24 16:36:17 +02:00
Milan Broz
874c573bd4 Do not allow used block size larger than page size.
Some filesystems (NFS) returns bogus blocksize (1MB).
Page-size io should always work and avoids increasing IO beyond aligned LUKS header.
2018-04-24 16:36:11 +02:00
Milan Broz
f63e1cfbfc Rename contains() to json_contains(). 2018-04-24 11:04:53 +02:00
Milan Broz
f049f719f8 Fix keyslot validation. 2018-04-24 10:51:47 +02:00
Milan Broz
30754473fc Add API to get integrity current failure count for dm-integrity. 2018-04-24 08:51:32 +02:00
Ondrej Kozina
7c70e6ce74 Add repair test for keyslot with kdf leftover params. 2018-04-21 20:29:17 +02:00
Ondrej Kozina
a702b7ccc5 Add new validation test for keyslot digest bond 2018-04-21 20:29:12 +02:00
Ondrej Kozina
f6be62ac5f Add repair for known glitches in LUKS2 json. 2018-04-21 20:27:05 +02:00
Ondrej Kozina
dddd30bef8 Add paranoid check for accidental volume key length change. 2018-04-21 20:18:00 +02:00
Ondrej Kozina
a054206d25 Suppress useless slash escaping in json lib 2018-04-21 20:14:28 +02:00
Ondrej Kozina
5b6f06b2ac Hide luks2 specific keyslot allocation from internal api. 2018-04-21 19:43:11 +02:00
Ondrej Kozina
6f83822b6e Validate all keyslot implementations after load and before write. 2018-04-21 19:42:55 +02:00
Ondrej Kozina
9b635a3e90 Cleanup LUKS2 keyslot specific validation.
- do not run general LUKS2 format validation from inside the specific one
- validate luks2 json object only
- temporary move digests count restrictions, going to be fixed in next
  commit
2018-04-21 19:37:05 +02:00
Ondrej Kozina
172af5465d Harden LUKS2 keyslot kdf section validation. 2018-04-21 19:36:31 +02:00
Ondrej Kozina
22f10dd8d2 Remove custom made 'contains' helper from keyslot validation. 2018-04-21 10:57:24 +02:00
Ondrej Kozina
790fdc0aa6 Add crypt_volume_key_get tests for unbound key. 2018-04-21 10:54:12 +02:00
Ondrej Kozina
45356f5e12 Split keyslot update in separate functions.
This patch fixes several problems:

- pbkdf benchmark should be run with keyslot encryption key length
  instead volume key length
- run LUKS2 keyslot validation on final keyslot json object instead
  temporary stub created in keyslot_alloc
- replace whole json kdf object during keyslot update. We left behind
  old parameters from old pbkdf during transition to differnt type
2018-04-21 10:53:54 +02:00
Ondrej Kozina
08ee50403d Move reading keyslot pbkdf params in helper. 2018-04-20 21:08:03 +02:00
Milan Broz
aa1551c6e8 Introduce CRYPT_SLOT_UNBOUND keyslot status for LUKS2.
A keyslot not bound to any segment can store any key for any purpose.

To easily check slot status, new enum value is introduced.
This status is valid only for LUKS2, so the functions are backward compatible
with LUKS1.
2018-04-19 22:28:13 +02:00
Ondrej Kozina
879403a172 Add tests for cryptsetup luksAddKey --unbound. 2018-04-19 18:29:47 +02:00
Milan Broz
6ddf765d8d Remove example covered by cryptsetup already. 2018-04-19 18:29:26 +02:00
Ondrej Kozina
38d83c27b4 Add --unbound keyslot option to cryptsetup.
An unbound keyslot is slot not assigned to a segment;
such a keyslot cannot be used to activate LUKS device, but
can be used for an arbitrary key store.

This patch adds --unboud option for luksAddKey cryptsetup command.
2018-04-19 18:25:35 +02:00
Ondrej Kozina
103fa8fa2c Remove redundant check for key file.
Semantically same check is in tools_get_key routine.
2018-04-19 18:18:56 +02:00
Ondrej Kozina
53dcee6176 Test dump of volume key in a file. 2018-04-19 18:17:45 +02:00
Ondrej Kozina
0c6129c54e Allow volume key store in a file with cryptsetup.
The --dump-master-key together with --master-key-file allows cryptsetup
to store the volume key to a file instead of standard output.
2018-04-19 18:08:37 +02:00
Ondrej Kozina
1f01754ea6 Update FIPS restrictions on crypt_volume_key_get
Allow crypt_volume_key_get for wrapped volume keys.
Allow crypt_volume_key_get for unbound LUKS2 keyslot keys.
2018-04-19 18:01:31 +02:00
Milan Broz
f8a7ab1752 Add crypt_get_pbkdf_default() function to get per-type PBKDF default. 2018-04-16 15:26:43 +02:00
Ondrej Kozina
09842ce46f Update docs for crypt_keyslot_add_by_key. 2018-04-15 15:46:16 +02:00
Ondrej Kozina
0b849985b2 Do not wipe keys for wrapped key enabled ciphers.
We can't wipe (overwrite with random noise) wrapped key in
kernel. Such keys are usually structured and not only random
bytes.

Also it doesn't make sense to wipe these keys. They are supposed
to be protected (encrypted) by keys sealed in hardware.

TODO: tests: 1) with header, 2) without header (dm-crypt only),
      3) arch with working paes cipher (at least).
2018-04-15 15:44:17 +02:00
Ondrej Kozina
34b8a48252 Add stand-alone device suspend. 2018-04-15 15:41:42 +02:00
Ondrej Kozina
6f6e1efbc8 Abort conversion when wrapped key cipher is used. 2018-04-15 15:40:48 +02:00
Milan Broz
9a72ec366d Move generic ciper backend utilities to separate file.
And add wrapped key check.
2018-04-15 15:31:10 +02:00
Ondrej Kozina
d97302f351 Extend suspend tests for missing header case. 2018-04-15 13:12:25 +02:00
Ondrej Kozina
4eb75f3c80 Add debug message for failed external token validation. 2018-04-15 13:10:32 +02:00
Ondrej Kozina
e5f72a0d4f Remove duplicate CRYPT_ANY_TOKEN define. 2018-04-15 13:10:01 +02:00
Ondrej Kozina
b11b11f9b0 Add test for LUKS2 conversion with tokens. 2018-04-15 13:08:57 +02:00
Ondrej Kozina
70077db07d Abort conversion when LUKS2 header contains tokens.
Tokens may contain import 3rd party data. Prompt users
to remove such tokens explicitly.
2018-04-15 13:08:44 +02:00
Ondrej Kozina
eed682c529 Add fixme in luks2->luks1 convert code. 2018-04-15 13:05:22 +02:00
Ondrej Kozina
fbf2d64f34 Allow crypt_volume_key_get for unbound keyslots. 2018-04-15 13:05:08 +02:00
Ondrej Kozina
48bf08922c Make all LUKS2 key size helpers return negative value on error. 2018-04-15 13:03:51 +02:00
Ondrej Kozina
3616ee50c0 Fix off by one bug in LUKS2 keyslot max id allocation.
This is almost impossible to hit bug. The max keyslot id is
checked in higher layer.
2018-04-12 15:50:24 +02:00
Ondrej Kozina
255c8e8ff4 Avoid pbkdf benchmark on LUKS2 header down conversion.
Also clarify use of placeholder keyslots in down conversion.
2018-04-12 15:49:35 +02:00
Ondrej Kozina
0891e84bf8 Add reencrypt tests for --master-key-file option. 2018-04-12 15:45:40 +02:00
Ondrej Kozina
a63db4ab24 Add --master-key-file parameter to cryptsetup-reencrypt. 2018-04-12 15:45:30 +02:00
Ondrej Kozina
169d45fbdb Move reading master key in command line utilities.
Move and rename _read_mk->tools_read_mk in utils_password.c
2018-04-12 15:44:19 +02:00
Ondrej Kozina
965e0237a3 Add basic test for CRYPT_VOLUME_KEY_SET flag.
Also test for bug in keyslot to digest assignment if target
digest id is not 0.
2018-04-12 15:42:32 +02:00
Ondrej Kozina
4caef0dec7 Add new volume key flag to crypt_keyslot_add_by_key.
The new flag may be used to force update device volume key.
2018-04-12 15:35:34 +02:00
Ondrej Kozina
622763b240 Fix memory leak on error path in cryptsetup-reencrypt. 2018-04-11 16:12:15 +02:00
Ondrej Kozina
35d29b22c0 Move CRYPT_ANY_DIGEST definition. 2018-04-11 15:49:29 +02:00
Ondrej Kozina
fee1d659cf Fix wrong digest assignment to new LUKS2 (volume key) keyslot.
All new LUKS2 keyslots added by passphrase or by volume key
were assigned to digest 0 despite the fact segment was assigned
to different digest.
2018-04-11 15:49:15 +02:00
Ondrej Kozina
869767a5cf Move general i/o code to stand-alone utility file.
Get rid of internal library stuff linked to the utilities.
Also rename 'count' param to 'length' clarifying handling
of the parameter internally.
2018-04-11 15:33:43 +02:00
Milan Broz
23b01621ff Print better debug message for open with write mode. 2018-04-10 15:33:30 +02:00
Milan Broz
f21ebaf839 Check LUKS2 conversion for luksmeta header.
We will reject upconversion if there is a luksmeta magic signature.
2018-04-10 14:54:35 +02:00
Milan Broz
f6f00b98a7 Always convert the whole last keyslot (including alignment). 2018-04-10 14:53:33 +02:00
Milan Broz
187170ec51 Check cipher before writing metadata (LUKS2).
Some ciphers and key sizes created on-disk metadata that cannot be used.
Use the same test for length-preserving cipher as LUKS1.

Also check if key for integrity algorithm is not too small.

Fixes #373.
2018-04-06 12:57:58 +02:00
Milan Broz
f7ad64a3d3 Move absolute path helper to m4 macro. 2018-04-04 12:35:08 +02:00
Eli Schwartz
103d75f773 configure.ac: fix bashisms
In commits 9bcc97bc5e and
5536b3a58d new features were
added, which used bash-specific features in a POSIX sh script. This
caused configure to completely fail with syntax errors on systems where
/bin/sh was not symlinked to GNU bash.

`==` is a bash-specific alias for `=` and should never, ever, ever be
used since it offers no additional utility for bash but merely serves
to confuse people writing POSIX.

substring parameter expansion, e.g. `${with_tmpfilesdir:0:1}` is not
POSIX but can be trivially replaced by case wildcards.
2018-04-04 12:13:59 +02:00
Milan Broz
ed2968e3e8 Add paes to ciphers that cannot be used for LUKS2 keyslot encryption.
And use AES-XTS for keyslot in this case.
2018-03-31 17:42:30 +02:00
Milan Broz
fef5121cee veritysetup: add support for --check-at-most-once option.
The kernel 4.17 will include a new dm-verity flag that
instructs kernel to verify data blocks only once.

This patch adds support for it to libcryptsetup and veritysetup.

This flag can be dangerous; if you can control underlying device
(you can change its content after it was verified) it will no longer
prevent reading tampered data and also it does not prevent to silent
data corrruptions that appears after the block was once read.
2018-03-31 11:50:09 +02:00
Milan Broz
c84983f91e Add simple luksConvertKey test. 2018-03-25 15:04:00 +02:00
Milan Broz
86f4f4440a Reformat crypt_resize function. 2018-03-25 14:25:02 +02:00
Milan Broz
af0887fb48 Remove no passphrase error message from library.
And move it to tools.

This will unify LUKS1/2 error messages.
2018-03-25 14:14:37 +02:00
Matthew Garrett
610c7858d6 Add explicit key conversion command
Add support for converting a keyslot from one pbkdf to another without
opening the device.
2018-03-23 09:53:06 +01:00
Milan Broz
8d1fb88a20 Fix return code and retry count for bad passphrase and non-tty input.
It there is an input on stdin (pipe), we cannot retry for password,
a retry applies only for the real terminal.

Also the retry lost EPERM (wrong passphrase) return code in this case,
replacing it with tty read error.

Fixes #321.
2018-03-23 08:13:43 +01:00
Ondrej Kozina
1e2ad19d68 Validate LUKS2 keyslot json before opening it. 2018-03-22 14:06:31 +01:00
Ondrej Kozina
7bee66fe36 Add new luks2 keyslot validation condition. 2018-03-22 14:05:19 +01:00
Ondrej Kozina
303fe886b7 Fix misleading param name in prototype. 2018-03-22 14:05:08 +01:00
Ondrej Kozina
761a472b45 Remove missing digest condition from LUKS2 digest verification. 2018-03-22 14:04:56 +01:00
Ondrej Kozina
3cf2da877f Refactor crypt_activate_by_keyfile_device_offset.
It's activation by passphrase after all.
2018-03-22 14:03:48 +01:00
Michal Virgovič
5b7b1596a2 Add tests for veritysetup FEC userspace decoding. 2018-03-22 12:44:14 +01:00
Michal Virgovič
dc58985ac6 Enable userspace FEC decoding in veritysetup. 2018-03-22 12:43:49 +01:00
Michal Virgovič
5e0db46f17 Add Reed-Solomon user-space decoding lib. 2018-03-22 12:41:57 +01:00
Milan Broz
4e19bc01d5 Fix test vectors test link. 2018-03-19 19:21:35 +01:00
Milan Broz
2d2acda404 Add crypto backend vectors test.
Still need to add
 - hash, HMAC,
 - symmetric ciphers,
 - storage encryption wrapper.
2018-03-19 13:02:12 +01:00
Milan Broz
fa8d5d1769 Remove losetup handling from reencrypt2 test. 2018-03-13 15:20:07 +01:00
Milan Broz
fe058e2c27 Update reencrypt test to use option --type only when really needed. 2018-03-13 14:14:44 +01:00
Milan Broz
a22a24bc98 Support detached header for cryptsetup-reencrypt.
This patch allows encryption/decryption of the whole device,
IOW add encryption later with detached header.

This operation can be dangerous, there is no fixed bindings between
the specific LUKS header and data device (encrypted data device
contains no magic signatures).
2018-03-08 10:15:56 +01:00
Milan Broz
b7c2465887 Add link to ABI tracker. 2018-03-07 13:47:00 +01:00
Milan Broz
f34158250a Update Readme.md. 2018-03-07 13:33:22 +01:00
Milan Broz
87dcc9fe07 Prepare version 2.0.2. 2018-03-07 12:55:54 +01:00
Milan Broz
c56e0eb556 Update po files. 2018-03-06 09:18:08 +01:00
Milan Broz
ba959970c6 Update po files. 2018-03-02 08:58:39 +01:00
Milan Broz
c75e31d3da Set devel version. 2018-03-01 15:04:12 +01:00
Milan Broz
bcc2330a18 Actually fail early Travis test if non-root test fails. 2018-03-01 14:31:04 +01:00
Milan Broz
f0f5913efe Fix device_test to properly fail for non-root user. 2018-03-01 14:05:51 +01:00
Milan Broz
17aefd333a Fix intearctive tests to actually fail if there is a timeout. 2018-03-01 13:48:04 +01:00
Milan Broz
b86a652b90 Return back check for inactive keyslot for luksKillSlot. 2018-03-01 13:46:50 +01:00
Ondrej Kozina
5968323642 Refactor cryptsetup-reencrypt luks2 handling.
Fold former luks2_transfer_tokens and luks2_transfer_flags into
new luks2_metadata_copy.
2018-02-28 10:37:14 +01:00
Ondrej Kozina
26727882d0 Refactor update_persistent_flags. 2018-02-28 10:36:43 +01:00
Ondrej Kozina
106e441a61 Add error message explaining locking failure. 2018-02-28 10:36:34 +01:00
Ondrej Kozina
6d22ba9f87 Allow symbolic links in locking path.
Allow symbolic links in the initial part of locking path.
If /run/x/y/crypsetup is locking path, starting with
'run' anything may be symbolic link up to (including) 'y'.
2018-02-28 10:36:26 +01:00
Ondrej Kozina
8cd9db272f Adapt device-test to different performance options handling.
cpu --perf-* options do not trigger error when
not supported by current kernel.

Also be more carefull about --sector-size when not supported by
dm-crypt. Test is made more pedantic now.
2018-02-28 10:36:06 +01:00
Ondrej Kozina
b8691649c5 Retry dm-crypt load if performance options are not supported. 2018-02-28 10:35:53 +01:00
Ondrej Kozina
e9a2938c6b Test persistent flags after reencryption. 2018-02-28 10:35:41 +01:00
Milan Broz
44fa0bfbc6 Ensure that we do not process null in atoi call. 2018-02-28 08:57:10 +01:00
Ondrej Kozina
36c213ed3a Remove warning from cryptsetup-reencrypt man page.
Tokens and persistent flags are now transferred during
reencryption.
2018-02-27 12:09:44 +01:00
Ondrej Kozina
5f26f8a03d Transfer persistent flags to new LUKS2 header. 2018-02-27 12:09:18 +01:00
Ondrej Kozina
471f781022 Enhance persistent flags handling in cryptsetup.
With --persistent option, write only flags actually
used during activation. In other words we will not
store anymore flags not supported by running kernel.
2018-02-27 11:58:20 +01:00
Ondrej Kozina
f6cb8e4118 Do not allow --persistent and --test-passphrase. 2018-02-27 11:58:15 +01:00
Ondrej Kozina
515eff269c Add basic tests for persistent flags API. 2018-02-27 11:58:11 +01:00
Ondrej Kozina
bd370ab789 Fix bugs in crypt_persistent_flags_get.
various bugfixes:
- erase flags variable if no flags are stored
- do not print false debug warning
- during activation do not overwrite activation flags
  with persistent flags
2018-02-27 11:58:05 +01:00
Ondrej Kozina
3e10116437 Test crypt_activate_by_token() and keyring. 2018-02-27 11:58:01 +01:00
Ondrej Kozina
05f665ecda Return error on conflicting keyring requests.
Add missing check in crypt_activate_by_token. An oversight
from previous patch.
2018-02-27 11:57:57 +01:00
Milan Broz
cd65f6a84d Speedup reencryption test. 2018-02-23 13:50:44 +01:00
Milan Broz
6d2979459e Key parameter is always const in cipher and storage backend. 2018-02-23 10:40:17 +01:00
Milan Broz
dee38e9c0b Rename buffer to key in hmac_init in crypto backend.
It is key and naming was confusing.
2018-02-23 10:40:14 +01:00
Milan Broz
b4fc36ea62 Make all crypto backend destructors return void.
Nothing in the code actually checks the return values anyway.
2018-02-23 10:40:11 +01:00
Milan Broz
fb6b4739e4 Clean up keyring handling.
Move all keyring functions to one place and separate LUKS2 specific
code to generic handling.

Also fix possible mismatch if volume key is in keyring but it is not native
LUKS2 device (libarary cannot process such a device properly).
2018-02-22 15:26:07 +01:00
Milan Broz
32700cc51b Fix possible dereference of type string. 2018-02-22 15:26:03 +01:00
Milan Broz
1ac353d24e Allocate key description in volume key.
The key description is now allocated by volume key wrappers.
2018-02-22 15:23:11 +01:00
Ondrej Kozina
d7686201dc Grow fs images and alter tests accordingly. 2018-02-22 15:22:39 +01:00
Ondrej Kozina
248733de44 Add reencryption test for LUKS2 tokens.
Test tokens are transferred properly to new LUKS2 header.
2018-02-22 15:22:08 +01:00
Ondrej Kozina
e410ba9623 On reencryption transfer tokens to new LUKS2 header. 2018-02-22 15:21:59 +01:00
Ondrej Kozina
8295bde95a Update tests for token enhancements.
- add crypt_token_is_assigned tests
- test crypt_token_json_set extended to be able
  to create builtin tokens.
2018-02-22 15:21:52 +01:00
Ondrej Kozina
f3a9e95dd8 Add simple API for token assignment reporting. 2018-02-22 15:21:37 +01:00
Ondrej Kozina
7378e3be01 Allow crypt_token_json_set to create internal types. 2018-02-22 15:21:31 +01:00
Ondrej Kozina
1968efe9f0 Do not allow unexpected fields in keyring token validation. 2018-02-22 15:21:24 +01:00
Milan Broz
2b6808f165 Fix some anoying gcc buffer size warnings. 2018-02-14 18:23:25 +01:00
Milan Broz
92f14d28d1 Fix null dereference in previous commit. 2018-02-14 14:19:48 +01:00
Milan Broz
954214e48c Use integrity key during integritysetup format.
Kernel could reject HMAC without a key during format, we must set a key here as well.

Because there is no data area (device size is 8 sectors), it is actually never used,
so we can use zeroed key here.

The real HMAC key is used later during device activation with the real size.
2018-02-13 14:41:36 +01:00
Milan Broz
828e6f2077 Skip legacy TrueCrypt algoritms if PIM is specified. 2018-02-13 13:27:07 +01:00
Ondrej Kozina
982b7373ea Sort option descriptions in reencrypt man page.
Sort detailed option descriptions alphabetically (LANG=C)
2018-02-13 13:04:11 +01:00
Ondrej Kozina
39b5359efd Update cryptsetup-reencrypt page.
- add --pbkdf* option descriptions
- few clarifications wrt LUKS2 format
- alter note about limited support for LUKS2. It's 1:1
  with LUKS1 format currently, but tokens are not yet
  transfered to new LUKS2 header for reencrypted device.
- few minor corrections
2018-02-13 13:04:07 +01:00
Milan Broz
627a538bf2 Fix Veracrypt PIM handling.
The code must not set global table with KDF variants but
it shuld calculate local iterations count.

Also PIM is not used for old Trucrypt modes, do not use it there.

Also fix leak of PIM iteration count to debug log.

Fixes issue #366 and issue #367.
2018-02-12 20:19:04 +01:00
Milan Broz
e07e3ecc22 Fix integrity tests to always use a key with HMAC algorithms.
Recent kernel changes disallows to use keyed-hash algorithms
without settting the key.

Unfortunately, dm-integrity fails too late (during IO, not on init).

For now fix just the test.
2018-02-12 11:53:02 +01:00
Ondrej Kozina
b426db6086 Reencrypt tests improvements.
- adapt tests to new features (luks2 keyslot change, pbkdf params)
- add tests for fixes (max keyslot)
- speed up tests significantly by add minimal forced values everywhere.
2018-02-11 15:09:38 +01:00
Ondrej Kozina
d4b43d8578 Allow changing LUKS2 keyslot params in cryptsetup-reencrypt. 2018-02-11 14:59:32 +01:00
Ondrej Kozina
b9b1680f08 Various improvements to cryptsetup-reencrypt tool.
- allow changing pbkdf parameters for LUKS2
- allow force iterations for both LUKS1 and LUKS2 formats.
2018-02-11 14:53:20 +01:00
Ondrej Kozina
3e37975a00 Fix cryptsetup-reencrypt verbose message.
Print volume key change only when --keep-key option is not specified.
2018-02-11 14:52:34 +01:00
Ondrej Kozina
b0e252684d Allow higher keyslot numbers with LUKS2 format in reencryption. 2018-02-11 14:49:47 +01:00
Ondrej Kozina
919e1c3f08 Adapt tests to --pbkdf-force-iterations restrictions. 2018-02-08 15:35:02 +01:00
Milan Broz
16dc58312c Move PBKDF limits to crypto backend (to one place). 2018-02-08 15:34:45 +01:00
Ondrej Kozina
169bd9db5e Do not allow forced pbkdf parameters below minimal values. 2018-02-08 15:33:08 +01:00
Milan Broz
4e5e8fd8fe cryptsetup: Print message about operation aborted if user did not answer YES.
Thanks Colin Walters for the initial idea in !33.
2018-01-24 10:17:28 +01:00
Milan Broz
8728ba08e2 Fix loopaesOpen for keyfile on standard input.
The change in keyfile processing caused that special loopAES
keyfiles are no longer read from stdin if key-file argument is "-".

Fix it by using /dev/stdin in cryptsetup if "-" is detected.
(The libcryptsetup API no longer parses spacial meaning of "-" internally).

Fixes #364.
2018-01-24 09:05:52 +01:00
Milan Broz
3ba07ed27f Fix another typo in release notes. 2018-01-21 12:59:08 +01:00
Milan Broz
9b4b659804 Fix missing 2.0.0 release notes in readme.md. 2018-01-21 12:48:57 +01:00
Milan Broz
c00a31077c Update Readme.md for 2.0.1. 2018-01-21 12:43:00 +01:00
Milan Broz
e8fc17f816 Prepare version 2.0.1. 2018-01-21 12:28:01 +01:00
Milan Broz
4a2da4b51e Add 2.0.1 Release Notes. 2018-01-21 12:10:23 +01:00
Milan Broz
180d96234e Fix another compiler warnings with extra flags. 2018-01-20 21:17:10 +01:00
Milan Broz
1a04ffbae4 Update LUKS1 standard doc (link fixes). 2018-01-20 18:46:00 +01:00
Milan Broz
1fe014dbae Update copyright year. 2018-01-20 17:55:21 +01:00
Milan Broz
579c31aa23 Update po files. 2018-01-20 17:26:49 +01:00
Milan Broz
74c914475f Increase maximum allowed PBKDF memory limit.
And also fix physical memory trimming function
to really allow requested value.
2018-01-20 17:04:02 +01:00
Milan Broz
1ca439f4e0 Fix some warnings found during static analysis. 2018-01-20 14:42:05 +01:00
Ondrej Kozina
08e7c143b3 Add internal code for LUKS2 keyslot params.
This fixes crypt_keyslot_add_by_key where we were unable to store
keyslot (unbound to segment) with different key_size.
The code used (new) volume key size implicitly which could be wrong
if new size was not compatible with cipher parameter for keyslot area.
2018-01-19 13:48:09 +01:00
Milan Broz
d399dfa792 Add error hint for wrongly formatted cipher strings in LUKS1. 2018-01-19 11:09:06 +01:00
Milan Broz
f6e613a76f Revert cipher requirement in parse cipher.
There is several specification that violate this (chacha20 etc).
Just use the old way...
2018-01-18 22:42:34 +01:00
Milan Broz
c6a8b6471a Allow ECB in cipher spec (fixes previous patch). 2018-01-18 21:55:52 +01:00
Ondrej Kozina
83589b7cec Extend LUKS2 specific tests.
Add yet another flawed dm-crypt test (keyring)
and test crypt_get_volume_key_size works
as expected after LUKS2 crypt_format (before
adding first keyslot).
2018-01-18 21:26:55 +01:00
Milan Broz
aeea93fa95 Properly fail in luksFormat if cipher format is missing required IV.
For now, crypto API quietly used cipher witout IV if a cipher
algorithm wihtou IV specificaton was used (e.g. aes-xts).

This caused fail later during activation.

This patch allows only two specific backed use without specified IV
(ECB mode and NULL cipher).

Also check cipher string early during parsing of CLI options.
2018-01-18 21:20:25 +01:00
Ondrej Kozina
be417d6605 Test keyring is disabled with flawed dm-crypt. 2018-01-18 14:37:51 +01:00
Ondrej Kozina
2f890dea18 Update tests for dm-crypt kernel key bugfix.
cryptsetup now requires dm-crypt v1.18.1 or higher
to use kernel keyring service for passing VKs.

Also, relevant API functions fail if CRYPT_ACTIVATE_KEYRING_KEY
is set, but library is not allowed to use kernel keyring for
VK.
2018-01-18 14:24:24 +01:00
Ondrej Kozina
de76628539 Return error for conflicting requests.
Return error when CRYPT_ACTIVATE_KEYRING_KEY flag is
raised but activation with vk in kernel keyring is not
possible.
2018-01-18 14:19:33 +01:00
Ondrej Kozina
598dd672bc Detect kernel version for dm-crypt kernel key bugfix.
When loading first dm-crypt table (or action that triggers dm-crypt
module load) we do not know dm-crypt version yet. Let's assume all
kernels before 4.15.0 are flawed and reject VK load via kernel keyring
service.

When dm-crypt is already in kernel, check for correct target version
instead (v1.18.1 or later).
2018-01-18 14:17:00 +01:00
Ondrej Kozina
d12fb3d6e1 Postpone use of kernel keyring for VKs to dm-crypt 1.18.1
Upstream dm-crypt v1.15.0 through v1.18.0 contains
serious bug in kernel key processing that may cause
data corruption for ciphers using essiv, tcw and lmk IVs.

Patch adds patch number processing to DM version checks.
2018-01-18 14:07:54 +01:00
Ondrej Kozina
9504d866b6 Use default segment alias in LUKS2 activatation. 2018-01-18 14:05:33 +01:00
Ondrej Kozina
865b1dc66e Add kernel key compat tests.
This test can detect ugly dm-crypt kernel key bug
present in kernels 4.10.0 through 4.15.0-rc8.
2018-01-18 14:05:13 +01:00
Ondrej Kozina
5143b210cf Return correct volume key size if internal volume key exists.
Return correct volume key size as long as valid volume key
is reachable at least in device context.
2018-01-18 13:42:11 +01:00
Milan Broz
f34ce81f25 Introduce new 64bit *keyfile_device_offset functions.
The keyfile interface was designed, well, for keyfiles.

Unfortunately, a keyfile can be placed on a device and the size_t offset
can overflow.

We have to introduce new set of fucntions that allows 64bit offsets even on 32bit systems:
 - crypt_resume_by_keyfile_device_offset
 - crypt_keyslot_add_by_keyfile_device_offset
 - crypt_activate_by_keyfile_device_offset
 - crypt_keyfile_device_read

The new functions have added _device_ in name.

Old functions are just internall wrappers around these.

Also cryptsetup --keyfile-offset and --new-keyfile-offset must now
process 64bit offsets.

For more info see issue 359.
2018-01-17 22:07:23 +01:00
madblobfish
b072c6c4c9 fix logic sentence error in releasenotes 2018-01-15 09:50:17 +01:00
Milan Broz
7951ed3bce Remove GMANE list archive that no longer exists. 2018-01-15 09:48:29 +01:00
Ondrej Kozina
02431c57db Force dmsetup to show dm-integrity keys in tests.
Recent dmsetup requires --showkeys option to
print dm-integrity keys.
2018-01-10 18:46:32 +01:00
Milan Broz
3f186c009c Auth tag size and iv size can depend on auth cipher.
Some experimental ciphers will use different IV sizes,
add parameter to check it in future (unused for now).
2018-01-05 16:38:58 +01:00
Milan Broz
6f4c15b2b2 Use /run/cryptsetup as default for cryptsetup locking dir.
There are problems with sharing /run/lock with lockdev and also in early boot
we cannot create the whole subir chain.

It is safe to switch to separate locking dir.
This can be changed with --with-luks2-lock-path and --with-luks2-lock-dir-perms
configure switches.

See Issue#361 and issue#362.
2018-01-04 09:23:11 +01:00
Ondrej Kozina
b31e029000 Validate LUKS2 header in crypt_set_uuid(). 2018-01-04 09:20:23 +01:00
Ondrej Kozina
5f5ffcd48a Remove logging from keyring utilities.
Reduce bloated code in low level keyring utilities code.
Move log messages higher the library code.

Also return -ENOTSUP when code was compiled out by configure
option.
2018-01-04 09:20:14 +01:00
Ondrej Kozina
cc76f3746f Remove unused digests handling code.
Remove code for handling multiple digests per single keyslot.
Same would apply to segments with the only exception of segment
in-reencryption. We need that exception so that we will not lose
old key digests too early.
2018-01-04 09:17:34 +01:00
Yuri Chornoivan
982da4d20c Fix minor typos 2018-01-04 09:13:58 +01:00
Milan Broz
113374fd04 Update po files. 2018-01-04 09:11:28 +01:00
Ondrej Kozina
e4520693dd API docs cleanup and clarifications 2017-12-18 19:32:44 +01:00
Milan Broz
ccffc88ceb Check for recent Argon2 lib to support Argon2id.
Fixes Issue#356.
2017-12-17 15:29:35 +01:00
Milan Broz
7c9312607c Fix cryptsetup-reencrypt static build if pwquality is enabled.
In static build we need to link also to pwquality.

Fixes Issue#357.
2017-12-17 15:20:49 +01:00
Ondrej Kozina
286c2960c8 silence signed/unsigned compiler warnings
any array with item count close to INT32_MAX would
not fit LUKS2 header json area anyway
2017-12-13 12:06:58 +01:00
Ondrej Kozina
a12e374a04 harden checks of json_object_array_length return values
with json-c until 0.12.x json_object_array_length returned signed
integer. json-c 0.13.x and later changed return type to unsigned
size_t.

Consider return values less or equal to zero as empty array, otherwise
array is non-empty.
2017-12-13 12:06:54 +01:00
Ondrej Kozina
d799c8bd1e update crypt_resize api docs 2017-12-12 14:02:41 +01:00
Milan Broz
251eec8401 Update Readme.md. 2017-12-10 21:26:56 +01:00
Milan Broz
bca8a32674 Prepare version 2.0.0. 2017-12-10 20:49:43 +01:00
Ondrej Kozina
c740324636 Derive VK kernel key description from digest id
Originally the key description for VK was derived
from segment id. This could lead to ambiguity when
keyslot key is verified and loaded in kernel keyring
using activation functions with CRYPT_ACTIVATE_KEYRING_KEY
flag raised.
2017-12-10 19:56:14 +01:00
Milan Broz
f049afcb5b Fix a rare fail in key-length regression test with PBKDF2.
PBKDF2 has nasty behaviour that it generates the same output
for passwords that has several trailing zero bytes.
(IOW null trailing bytes causes collision.)

Unfortunatelly our test plays with password length
and expect wrong length must always fail.
Sometimes the randomly generated key key contains
the null byte in the "wrong" place and PBKDF2 causes test to fail.

For now, fix it by using fixed keyfile without null bytes
(similar to fixed passphrased we already have).
2017-12-10 11:39:00 +01:00
Ondrej Kozina
c188654ebd simplify kernel keyring key removal path
simplify crypt_drop_keyring_key

also do not search for keyring keys when we know
we haven't loaded any
2017-12-09 14:55:23 +01:00
Ondrej Kozina
a6aba8cab2 tests: check keyring key is gone after crypt_suspend 2017-12-09 14:53:02 +01:00
Ondrej Kozina
583fbfdb2a drop keyring key after successful crypt_suspend
due to wrong sequence of function calls the volume key
(if present) in keyring was never dropped properly.
2017-12-09 14:52:46 +01:00
Ondrej Kozina
7c34ac6f6d always return error when VK fails to load in keyring 2017-12-09 14:52:26 +01:00
Milan Broz
b72354ca22 Fix test scripts to always use different keyfile size.
Othewise it fails later with 1/256 probability if the first random byte is
the same :-]
2017-12-07 14:21:29 +01:00
Ondrej Kozina
82d81b9e86 extend use of lseek_blockwise functions 2017-12-07 13:01:04 +01:00
Ondrej Kozina
ed19ddf620 be specific about version in failed format operation 2017-12-07 13:00:59 +01:00
Milan Broz
ebbd33db7a Add po file. 2017-12-07 12:16:37 +01:00
Milan Broz
7ba4ca1854 Add bundled lib README to package. 2017-12-07 12:15:55 +01:00
Milan Broz
fa1f8c0d87 Limit KDF memory by available physical memory.
On some systems the requested amount of memory causes OOM killer
to kill the process (instead of returning ENOMEM).

For now, we never try to use more than half of available
physical memory.
2017-12-07 10:43:52 +01:00
Milan Broz
e0cacef52e Align legacy keyslot temporary device according to keyslot alignment.
For some strange filesystems (nfs) we get big block size (1MB).

For temporary keyslot devices this mapping does not make sense and
can cause problem with detached headers that are smaller (contains
exactly the slot size).
2017-12-06 17:07:24 +01:00
Milan Broz
767ed40b75 Use better "time cost" for Argon than time. 2017-12-05 15:41:24 +01:00
Milan Broz
3c2f92a7af Increase Argon2 LUKS2 default. 2017-12-05 14:44:44 +01:00
Milan Broz
2568f828c8 Workaround to delete stale library if --disable-libargon2 was used. 2017-12-05 14:43:41 +01:00
Michal Virgovic
5427f55358 Add test for integritysetup modes. 2017-12-05 10:50:45 +01:00
Ondrej Kozina
92b41e4935 more return NULL instead of 0 cleanups 2017-12-01 13:17:32 +01:00
Ondrej Kozina
6edae6ddef return NULL instead of 0 2017-12-01 13:10:37 +01:00
Ondrej Kozina
f787eafd8a drop duplicate default segment define 2017-11-30 16:54:06 +01:00
Milan Broz
9588a961d6 Do not alloc tcrypt keyfileon stack.
The keyfile has 1MB, it is better to run malloc for this code.
2017-11-24 13:45:21 +01:00
Ondrej Kozina
88758703fa test: update luks2 validation tests 2017-11-23 16:18:27 +01:00
Ondrej Kozina
3c839f44d8 luks2: fix off-by-one error in uint64 validation 2017-11-23 16:18:19 +01:00
Ondrej Kozina
304bdd7d0d luks2: add json_object_new_uint64 wrapper
json doesn't support 64 bits integers. We workaround it by storing
large numbers as string and validate the value internally.
2017-11-23 16:18:14 +01:00
Ondrej Kozina
382d27b4dc remove unused function 2017-11-23 16:17:07 +01:00
Milan Broz
b80278c04f Ignore device opt-io alignment if it is not multiple of minimal-io.
Some USB enclosures seems to report bogus topology info.
Fixes https://bugzilla.redhat.com/show_bug.cgi?id=1513820
2017-11-21 15:39:36 +01:00
Ondrej Kozina
7d4fcfa191 fix memleaks on integrity format error path 2017-11-19 10:01:59 +01:00
Ondrej Kozina
ad3fe00dea fix memleaks on verity format error path 2017-11-19 09:51:59 +01:00
Milan Broz
f507d16baa Update bundled Argon2 source. 2017-11-14 12:07:53 +01:00
Milan Broz
dcce2edc4f Fix integrity setup test journal watermark setting. 2017-11-14 09:31:33 +01:00
Milan Broz
e7e1e7a0a3 Update po files. 2017-11-13 19:57:59 +01:00
Milan Broz
68f4485cdd Fix deactivation of standalone integrity device. 2017-11-13 19:57:16 +01:00
Guilhem Moulin
d93ac3c496 Remove libargon2 code from source tree
[mbroz: fix for make distcheck]
2017-11-08 10:51:58 +01:00
Andrea Gelmini
a97de38b6b Fix typos. 2017-11-08 10:22:49 +01:00
Milan Broz
444eac3597 Update po files. 2017-11-08 09:56:32 +01:00
Ondrej Kozina
1f01c76fa5 fix memory leak on failed luks2 activation 2017-11-03 17:30:14 +01:00
Milan Broz
16da1a5c88 Version 2.0.0-rc1. 2017-11-01 10:41:35 +01:00
Milan Broz
e514d1201d Use hardcoded location for distcheck tmpfiles.d. 2017-11-01 08:57:41 +01:00
Milan Broz
eb0293a637 And also define AS_VAR_COPY for old automake. 2017-10-31 21:46:55 +01:00
Milan Broz
03581fc8cc Define PKG_CHECK_VAR for old pkg-config <= 0.28 2017-10-31 21:40:49 +01:00
Milan Broz
246cf0df26 Add Travis compile only option. 2017-10-31 21:18:04 +01:00
Milan Broz
cf1d6461cb Do not rename tmpfile config but use it directly. 2017-10-31 21:11:25 +01:00
Ondrej Kozina
9bcc97bc5e install cryptsetup_tmpfiles.conf
add --with-tmpfilesdir configuration option. Use the option
either to override default systemd tmpfiles.d directory location
or to specify install location for systems without systemd.
2017-10-31 20:50:39 +01:00
Milan Broz
3bc124d9d3 Switch to rc1 version. 2017-10-31 11:00:37 +01:00
Ondrej Kozina
764ae2a489 man: update cryptsetup-reencrypt for LUKS2 format 2017-10-30 21:13:59 +01:00
Ondrej Kozina
e678d5ae8e test: drop useless luks2 test image 2017-10-30 16:09:40 +01:00
Ondrej Kozina
13b1720899 reencrypt: add message about using default parameters with LUKS2 2017-10-30 16:09:36 +01:00
Ondrej Kozina
35512f4ee9 cryptsetup-reencrypt: internal safeguard against mistakes 2017-10-30 16:09:33 +01:00
Milan Broz
e55f10a8f1 Decrease size of another testing LUKS2 images. 2017-10-29 18:53:16 +01:00
Milan Broz
b187e499a4 Decrease size of testing images. 2017-10-29 18:29:35 +01:00
Milan Broz
dd397a9957 Fix Makefile example after automake changes. 2017-10-29 16:31:49 +01:00
Daniel Reichelt
cdfed8fabc fix typo in usage text for veracrypt pim parameters 2017-10-29 09:06:37 +01:00
Ondrej Kozina
759577ad9b tests: LUKS2 reencrypt tests 2017-10-28 23:26:11 +02:00
Ondrej Kozina
356402942f luks2: adapt reencrypt to luks2 version
TODO: currently there's no way to change pbkdf to non-default for LUKS2
2017-10-28 22:35:21 +02:00
Ondrej Kozina
76947fa835 luks2: add offline reencrypt requriement 2017-10-28 22:29:28 +02:00
Milan Broz
f7dadfb646 Fix some benign compiler warnings. 2017-10-28 14:12:25 +02:00
Milan Broz
4e31595c7a Enable build of cryptsetup-reencrypt by default. 2017-10-28 14:08:26 +02:00
Milan Broz
31779c0763 Fix memory leak in LUKS2 requirements handling for restore context. 2017-10-28 12:01:02 +02:00
Milan Broz
6e3622e0f1 Fix some warning and leaks in api test code. 2017-10-28 11:59:06 +02:00
Milan Broz
b78bd4ccce Add new valgrind tests. 2017-10-27 22:39:50 +02:00
Milan Broz
a10059d531 Fix memory leak in verity device destructor. 2017-10-27 21:45:54 +02:00
Milan Broz
1f2ce01c08 Fix a memory leak of key description for integrity device. 2017-10-27 15:58:33 +02:00
Milan Broz
fb5a70a663 Fix memory leak in integrity device query processing. 2017-10-27 15:18:10 +02:00
Milan Broz
d62d0ed076 Add configure option to disable build of cryptsetup tool.
You can use --disable-cryptsetup to not build cryptsetup binary.
2017-10-25 11:47:45 +02:00
Michal Virgovic
a4b9ce13ee Enable valgrind in veritysetup tests. 2017-10-20 10:45:11 +02:00
Michal Virgovic
43ee152eb4 Enable valgrind in integritysetup tests. 2017-10-20 08:56:21 +02:00
Michal Virgovic
fee909deee Add tests for integritysetup journal parameters. 2017-10-19 09:00:13 +02:00
Milan Broz
702bcb8684 Fail if integrity option is used with LUKS1 format. 2017-10-17 10:37:17 +02:00
Ondrej Kozina
961e65424e crypt_deactivate: fail earlier when holders detected
crypt_deactivate_* fail earlier without noisy dm retries
when other device holders detected. The early detection
works if:

a) other device-mapper device has a hold reference on the
   device

- or -

b) mounted fs is detected on the device

Any deactivation flag CRYPT_DEACTIVATE_FORCE or
CRYPT_DEACTIVATE_DEFERRED will disable this detection
2017-10-17 10:03:17 +02:00
Michal Virgovic
f901cb7b25 Output correction of integritysetup status. 2017-10-17 09:50:50 +02:00
Ondrej Kozina
1d9d248456 man: fix two typos in integrity parameters
--integrity-no-wipe
--integrity-no-journal options
2017-10-16 16:43:19 +02:00
Milan Broz
86ef5475b9 Enable OpenSSL backend in FIPS mode.
Note that this is just for testing, primary FIPS backend is gcrypt.
2017-10-14 21:37:10 +02:00
Michal Virgovic
087c314154 Integritysetup: add tests for journal encryption.
[modified by gmazyland@gmail.com]
2017-10-14 20:54:37 +02:00
Michal Virgovic
956ea10f56 Integritysetup manual correction (key size).
Also mention key size in header struct doc.
2017-10-14 19:46:37 +02:00
Milan Broz
4a4faa5d46 Fix warning for major() macro. 2017-10-12 12:29:41 +02:00
Milan Broz
7e2a3fda4d Update gettext version. 2017-10-12 11:48:42 +02:00
Milan Broz
786e51ecd1 Do not run configure automatically after running autogen.sh. 2017-10-12 11:48:38 +02:00
Milan Broz
d77bbe93c1 Use non-recursive automake.
This change also causes that now binaries and libraries are placed in
build root directory.

Now we can use subdir-objects for automake.
2017-10-12 11:48:17 +02:00
Milan Broz
892b80ffa4 Do not depend in test on loop code from library sources.
This patch duplicates part of the code because following
switch to non-recursive automake is not easily fixable without this change.

(Automake cannot use top_srcdir anymore in this context.)
2017-10-12 11:46:26 +02:00
Milan Broz
1c2cc9f35c Do not print error output from older "which" command in tests. 2017-10-11 08:04:02 +02:00
Milan Broz
12908709bb Resize loop device after fallocate.
On old systems we have a loop mapped so the loop must be resized as well.
2017-10-10 19:48:29 +02:00
Milan Broz
b42d183b08 Create LUKS header file in luksFormat if it does not exist. 2017-10-10 13:52:50 +02:00
Milan Broz
e1ed664adc Print error if device name is invalid (in use by other target). 2017-10-09 14:36:43 +02:00
Milan Broz
de2f07b82f Do not try to load LUKS2 header if backup_file is LUKS1.
Also do not allow header restore if a different version is requested.
2017-10-06 12:28:59 +02:00
Milan Broz
cc5c91158d Do not allow resize if device size is not aligned to sector size. 2017-10-04 15:26:00 +02:00
Milan Broz
8dc35a7906 Enable to use system libargon2.
Rename --disable-argon2 to --disable-internal-argon2 option
and add --enable-libargon2 flag to allow system libarhgon2.
2017-10-04 15:24:26 +02:00
Milan Broz
7e53c87f5c Add parameter for progress update without in separate lines.
Useful for reencryption or integrity format.
2017-10-04 15:22:32 +02:00
Milan Broz
59e6b33c6f Update README.md. 2017-09-29 10:08:01 +02:00
Milan Broz
9843014dce Add API changes list to release notes. 2017-09-29 09:15:02 +02:00
Milan Broz
728a454919 Update version. 2017-09-29 01:25:25 +02:00
Milan Broz
dff09b7e65 Add RC0 release notes. 2017-09-29 01:22:58 +02:00
Ondrej Kozina
bb40433960 add keyring notes 2017-09-28 11:25:17 +02:00
Milan Broz
6cd770e501 Add temporary description of LUKS2 on-disk format. 2017-09-28 11:23:33 +02:00
Milan Broz
0f347b9c5c SLighly reformat locking doc. 2017-09-28 11:23:03 +02:00
Ondrej Kozina
c3b3d7b022 fix api-test for builds without keyring support 2017-09-27 11:03:11 +02:00
Milan Broz
948006561a Yet another fix for header strings. 2017-09-27 10:54:03 +02:00
Milan Broz
3ccbb8fe84 Fix some problems found by Coverity analysis. 2017-09-27 10:18:38 +02:00
Milan Broz
c1c541642e Add a note about locking to man page. 2017-09-27 08:12:09 +02:00
Ondrej Kozina
b4782809d4 luks2: allow masking of requirements internaly
before this patch any LUKS2 requirement defined in header
would stop a restricted operation from proceeding further.
This patch adds ability to mask requirements (internal only).
2017-09-27 07:48:53 +02:00
Ondrej Kozina
b3feae5474 luks2: unify naming for requirements flags 2017-09-27 07:47:41 +02:00
Ondrej Kozina
c015aeca4e luks2: move pre-activation requirements check lower 2017-09-27 07:47:13 +02:00
Milan Broz
9bbc13f256 Add LUKS2 examples.
Signed-off-by: Milan Broz <gmazyland@gmail.com>
2017-09-27 07:46:41 +02:00
Milan Broz
38d53db6e9 Reformat and fix libcryptsetup.h / Doxygen doc.
No functional change in this patch.
2017-09-26 16:35:20 +02:00
Ondrej Kozina
0f4d83960f add remainders to fix some longstanding issues 2017-09-24 19:50:34 +02:00
Milan Broz
19a1852e4b Support sector size option even for plain devices. 2017-09-24 19:50:28 +02:00
Milan Broz
c6d4ebd80c Add libLUKS2 tests. 2017-09-24 19:50:17 +02:00
Milan Broz
9f2727bb77 Add libLUKS2. 2017-09-24 19:50:12 +02:00
Milan Broz
00b103c85c Allow wip-luks2 build in Travis. 2017-09-24 19:50:05 +02:00
Milan Broz
a0d2d4c0b1 Add uint64_to_str helper. 2017-09-24 19:50:01 +02:00
Milan Broz
64e91951b2 Add generic LUKS format define.
It means "load any LUKS version".
2017-09-24 19:49:56 +02:00
Milan Broz
e7de19fe1d Split utils from API test. 2017-09-24 19:49:51 +02:00
Milan Broz
5536b3a58d Add implementation of device/file locking for metadata.
To be used later.
2017-09-24 19:49:46 +02:00
Milan Broz
a8347d2820 Add integrity intefrace test stub. 2017-09-24 19:49:40 +02:00
Milan Broz
c56bdee177 Add backend support for new device-mapper kernel options.
This patch adds support for using keyring for volume key
and support for new integrity fields for dm-crypt.

Also helpers for searching disk by id.

To be used later.
2017-09-24 19:49:35 +02:00
Milan Broz
894e7b9357 Add base64 implementation.
To be used later. Copy from gnulib.
2017-09-24 19:49:30 +02:00
Milan Broz
2aee1426de Speed up tests by avoiding PBKDF benchmarks in many cases. 2017-09-24 19:49:25 +02:00
Milan Broz
66db5b39bb Change PBKDF insterface to allow forced iterations (time cost) count.
Also move functions to separate utils_pbkdf.c file.

PBKDF can be now set for any context.

TODO: new setting is not covered by tests.
2017-09-24 19:49:21 +02:00
Milan Broz
a73bb733ff Fix list of files for translation. 2017-09-24 10:09:48 +02:00
Michal Virgovic
3d57f5fcbb Add tests for integritysetup error detection. 2017-09-23 23:49:25 +02:00
Ondrej Kozina
c34bee2009 return correct key description format in dm_query_device
dm_query_device is expected to return kernel key description
string only. By mistake the code returned also type in head
of key description.
2017-09-23 23:45:32 +02:00
Milan Broz
c3a0cbfc85 Update documentation. 2017-09-23 23:34:18 +02:00
Milan Broz
57825365fe Fix another signed/unsigned compilation warnings. 2017-09-23 23:30:28 +02:00
Milan Broz
b35785bb1b Fix some signed/unsigned and other compiler warnings. 2017-09-23 23:29:11 +02:00
Milan Broz
0d2f888413 Fix some tests to run under make distcheck and separately. 2017-09-23 23:24:24 +02:00
Milan Broz
a85fee7a0d Silence compiler warning (dmt_flags is always initialized). 2017-09-11 12:36:43 +02:00
Milan Broz
f66dedc759 Add plain64be IV to storage backend. 2017-09-11 12:33:10 +02:00
Ondrej Kozina
a62da3d530 extend stackframe in valgrind tests 2017-08-26 11:46:26 +02:00
Ondrej Kozina
1cc972c723 improve kernel keyring usability detection for tests 2017-08-26 11:46:16 +02:00
Milan Broz
6b7a2f6641 Fix memory leaks in dm_query_integrity and dm_query_verity. 2017-08-26 11:44:21 +02:00
Milan Broz
34b79794ea Mark python test as skipped with exit code 77. 2017-08-26 11:44:03 +02:00
Ondrej Kozina
fb114d8d20 fix memleaks in lower level dm_query_device on error path 2017-08-26 11:43:31 +02:00
Ondrej Kozina
a6106117a9 Fail gracefully if name is NULL in crypt_init_by_name() & co 2017-08-25 21:36:50 +02:00
Ondrej Kozina
b27507790f fix memleak in crypt_resize() 2017-08-25 21:32:57 +02:00
Milan Broz
a0880b64f2 Add magic exit code for automake to count skipped tests. 2017-08-23 16:54:04 +02:00
Milan Broz
6e057c010f Revert "Set block size for loop device if supported by kernel (4.13+)."
This reverts commit 4e2deadba7.

There is too many cases with 4k unaligned images that this optimization
adds more problems than it solves. Revert it for now.
2017-08-23 08:07:27 +02:00
Milan Broz
540972ff59 Move progress function to utils. 2017-08-22 16:13:40 +02:00
Milan Broz
677adc7adc Add crypt_backend_destroy() function and cll it as library destructor. 2017-08-22 15:48:24 +02:00
Milan Broz
096c50cafc Fix memory leak during repeated password entry. 2017-08-22 15:38:29 +02:00
Ondrej Kozina
8c57e3ffca Hint kernel keyring disabled in debug message 2017-08-22 13:47:20 +02:00
Milan Broz
4e2deadba7 Set block size for loop device if supported by kernel (4.13+). 2017-08-22 13:45:59 +02:00
Milan Broz
497fb0b3c3 Fix Argon2 benchmark.
1) If the calculated costs were the same, it run forever.

2) If the calculation returned final values in the first step,
out costs were not updated and benchmark returned too low values.
2017-08-16 15:43:11 +02:00
Milan Broz
8debcf9f92 Do not use too complicated regular expression in test. 2017-08-15 12:01:59 +02:00
Milan Broz
db0a21b93f Fix PBKDF benchmark for old PBKDF2 tests (hash specified only). 2017-08-15 09:20:30 +02:00
angelomariafederichini191269@protonmail.com
e2fee206c2 Allocate suitable sized buffer when reading a keyfile
If the keyfile size is explicitly given, then allocate a suitable sized
buffer right from the start instead of increasing it in 4k steps. This
speeds up reading larger keyfiles.
2017-08-15 08:49:44 +02:00
angelomariafederichini191269@protonmail.com
596e374313 Use bulk read when reading keyfile
If reading a keyfile use bulk read operations instead of reading one
character at the time. This speeds up reading larger keyfiles.

If read should stop at a EOL, then fallback to reading one character at
the time to not read anything beyond the EOL character.
2017-08-15 08:39:53 +02:00
Milan Broz
503956707c Move crypt_keyfile_read() to libcryptsetup internal file.
The utils_crypt.c file is directly linked to userpsace tools,
we should use library call and not local implementation.
2017-08-15 08:35:10 +02:00
Milan Broz
87dd427d79 Make benchmark progress parameter the same as the internal unsigned type. 2017-08-12 17:55:01 +02:00
Milan Broz
5fc79f5627 Move PBKDF internal benchmark to one place.
Also cache its value in active context, so we run benchmark
only once.

The patch also changes calculated value for LUKS1 key digest
to 125 miliseconds (it means that for full 8 used slots
the additional slow-down is circa 1 second).

Note that there is no need to have too high iteration count
for key digest; if it is too computationally expensive, attacker
will better decrypt of one sector with candidate key anyway.
(Check for a known signature.)

The reason to have some delay for key digest check was
to complicate brute-force search for volume key with LUKS header
only (and if RNG used to generate volumekey was flawed
allowing such a search i reasonable time).
2017-08-12 17:50:02 +02:00
Milan Broz
f4bb2ad613 Tweak kdf benchmark log.. 2017-08-11 16:08:44 +02:00
Ondrej Mosnáček
15b4f64b91 Fix Argon2 benchmark for decreasing parameters
When we have measured time smaller than target time, we are decreasing
the parameters. Thus, we should first try to decrease t_cost and only
if that is not possible should we try to decrease m_cost instead. The
original logic was only valid for the case where parameters are being
increased. Most notably this caused unusual parameter combinations for
iteration time < 250 ms.

In this commit we also factor out the now heavily nested parameter
update formula.
2017-08-11 16:01:09 +02:00
Milan Broz
a1a7d41e7a Group functions together more logically.
No functional change in this patch, just code shuffling.
2017-08-11 14:41:11 +02:00
Milan Broz
74547a4313 Remove unused code from integritysetup. 2017-08-10 19:27:24 +02:00
Milan Broz
9a532080d0 Fix PBKDF2 check to not overflow and not divide by zero. 2017-08-10 18:14:36 +02:00
Milan Broz
32c6afb120 Do not run keyring test in without root privileges. 2017-08-10 13:48:23 +02:00
Milan Broz
896eb26877 Add keyutils package to Travis tests. 2017-08-10 13:25:52 +02:00
Milan Broz
0a8bc6f1c7 Decrease iteration count to make compat test faster. 2017-08-10 13:18:42 +02:00
Michal Virgovic
175aaedc79 Add interactive tests. 2017-08-10 13:00:49 +02:00
Milan Broz
4125beb0fb Add callback for PBKDF benchmark.
Also change API so the kdf structure is continuously updated
with the benchmarked data (callback can see progress or debug).
2017-08-10 12:44:24 +02:00
Ondrej Mosnáček
93ea4f4f6f Tweak Argon2 benchmark to finish faster.
The benchmark is taking too long...
2017-08-10 12:39:25 +02:00
Michal Virgovic
d3f4eedb12 Add non-root tests. 2017-08-07 14:35:39 +02:00
Milan Broz
5a49efec58 Allow separate benchmark for a KDF (with --pbkdf option). 2017-08-07 12:30:05 +02:00
Milan Broz
3435f9cb2c Use only crypt_get_integrity_info in API.
Some other functions remain internal only.

Signed-off-by: Milan Broz <gmazyland@gmail.com>
2017-08-06 21:34:01 +02:00
Milan Broz
d891e00f63 Add kernel keyring functions for volume key.
Code is written by Ondrej Kozina.

This patch adds ability to store volume key in kernel keyring
(feature available in recent kernels) and avoid setting
key through dm-ioctl and avoiding key in table mapping.

Will be used in LUKS2.

Signed-off-by: Milan Broz <gmazyland@gmail.com>
2017-08-06 21:30:51 +02:00
Milan Broz
8a859391be Add Argon2 benchmark code.
Code based on patch by Ondrej Mosnacek

The new benchmark works as follows:

Phase 1:
It searches for smallest parameters, such that the duration is 250 ms
(this part is quite fast).
Then it uses that data point to estimate the paramters that will have
the desired duration (and fulfill the basic constraints).

Phase 2:
The candidate parameters are then measured and if their duration falls
within +-5% of the target duration, they are accepted.
Otherwise, new candidate parameters are estimated based on the last
measurement and phase 2 is repeated.

When measuring the duration for given parameters, the measurement
is repeated 3 or 4 times and a minimum of the measured durations
is used as the final duration (to reduce variance in measurements).
A minimum is taken instead of mean, because the measurements definitely
have a certain lower bound, but no upper bound (therefore mean value
would tend to be higher than the value with highest probability density).
The actual "most likely" duration is going to be somewhere just above
the minimum measurable value, so minimum over the observations is
a better estimate than mean.

Signed-off-by: Milan Broz <gmazyland@gmail.com>
2017-08-06 21:30:11 +02:00
Milan Broz
0abf57be5d Change PBKDF interface API.
Prepare API for PBKDF that can set three costs
  - time (similar to iterations in PBKDF2)
  - memory (required memory for memory-hard function)
  - threads (required number of threads/CPUs).

This patch also removes wrongly designed API call
crypt_benchmark_kdf and replaces it with the new call
crypt_benchmark_pbkdf.

Two functions for PBKDF per context setting
are introduced: crypt_set_pbkdf_type and crypt_get_pbkdf_type.

The patch should be backward compatible when using
crypt_set_iteration_time function (works only for PBKDF2).

Signed-off-by: Milan Broz <gmazyland@gmail.com>
2017-08-06 21:24:05 +02:00
Milan Broz
09d14a0b6c Add Argon2 bundled library to crypto backend.
The Argon2i/id is a password hashing function that
won Password Hashing Competiton.

It will be (optionally) used in LUKS2 for passworrd-based
key derivation.

We have to bundle code for now (similar PBKDF2 years ago)
because there is yet no usable implementation in common
crypto libraries.
(Once there is native implementation, cryptsetup
will switch to the crypto library version.)

For now, we use reference (not optimized but portable) implementation.

This patch contains bundled Argon2 algorithm library copied from
  https://github.com/P-H-C/phc-winner-argon2

For more info see Password Hashing Competition site:
  https://password-hashing.net/
and draft of RFC document
  https://datatracker.ietf.org/doc/draft-irtf-cfrg-argon2/

Signed-off-by: Milan Broz <gmazyland@gmail.com>
2017-08-06 21:13:12 +02:00
Milan Broz
9bd06be43b Add info function for integrity devices and print info about journal attributes. 2017-07-31 16:49:19 +02:00
Milan Broz
01598028c4 Aff info function for integrity device and print info ion status. 2017-07-31 16:48:29 +02:00
Milan Broz
cf9428fba1 Fix typo in journal integrity processing. 2017-07-31 15:42:20 +02:00
Milan Broz
4faa9e9f45 Swtich default integritysetup crc32 alg to crc32c (that is hw accelerated in recent Intel CPUs). 2017-07-27 14:26:41 +02:00
Milan Broz
4bcba41d77 Fix crypt_init(cd, NULL) case in the previous commit. 2017-07-27 13:36:53 +02:00
Milan Broz
12040570ca Allow to open device without read check.
In some specific situation we do not want to read the devices
before initialization.

Here it is integrity checking that will produce warning, because
the device is not yet initialized.

Used only in wipe function (here we must use direct-io anyway)
and expect the device is capable of direct-io.
2017-07-27 12:56:07 +02:00
Milan Broz
5824e8d242 Simplify device block size check. 2017-07-26 14:53:37 +02:00
Milan Broz
d7a0d860b9 Use getvfs for block size of filesytem if available. 2017-07-26 14:32:21 +02:00
Milan Broz
dbdb611bcc Document crypt_params_integrity struct members. 2017-07-26 13:21:19 +02:00
Michal Virgovic
3b3e14d056 Update doxygen documentation for version 1.8. 2017-07-26 12:51:17 +02:00
Milan Broz
962bf58f8f Print error message if device exists but as other subsystem. 2017-07-26 12:42:58 +02:00
Milan Broz
6f2ff93519 Do not repeat password question if underlying function returns EINVAL.
This error code means invalid value, no point in repeating the whole sequence.
(If there is a situation that requires repeat, it should not return EINVAL.)
2017-07-26 10:44:42 +02:00
Milan Broz
e853aa2e7c Fix blockwise access functions for systems with big page size.
Initially cryptsetup expected underlying device that was, by definition,
always aligned to a sector size (and length was always multiple of sectors).

For the images in file, we can now access the image directly.
Expecting that the image is always aligned to the whole block is now false
(the last block in file image can be incomplete).

Moreover, we cannot easily detect underlying block device sector (block) size
(the storage stack can be complex with various RAID and loop block sizes),
so code uses systyem PAGE_SIZE in this situation (should be the safest way).

Unfortunately, PAGE_SIZE can be bigger (1MB) than device sector (4k) and
the blockwise functions then fails because the image in file is not
aligned to PAGE_SIZE multiple..

Fix it by checking that read/write for the last part of an image is
the exact requested size and not a full block.

(The problem is for example for an unaligned hidden Truecrypt header
on PPC64LE systems, where page size is 64k.)
2017-07-24 14:17:21 +02:00
Milan Broz
248e35036f Do not fail if wipe size is smaller than block size.
With big page size and image in file this can actually happen.

The command works in this situation but the code will be quite
ineffective (due to blockwise handling).
2017-07-24 14:15:42 +02:00
Ingo Franzki
96f1cdf687 Typo in man page
I guess this should be 'existing' not 'exiting'.

Signed-off-by: Ingo Franzki <ifranzki@linux.vnet.ibm.com>
2017-07-20 09:42:41 +02:00
Michal Virgovic
d483b6d25c Add nonroot tests for travis. 2017-07-19 11:59:24 +02:00
Milan Broz
293fa48884 Run part of test as non root user. 2017-07-19 11:57:55 +02:00
Michal Virgovic
45bd005be9 Enable python tests in travis. 2017-07-14 17:31:49 +02:00
Michal Virgovic
efe88d4979 Add tests for FEC area overlap detection. 2017-07-11 18:16:15 +02:00
Michal Virgovic
913c9aa3d3 FEC-area overlap detection. 2017-07-11 17:36:47 +02:00
Michal Virgovic
a36c53af99 Correction of integritysetup manual. 2017-07-11 11:54:58 +02:00
Michal Virgovic
8ff808c882 Update of integritysetup manual and typos correction.
[Heavily modified by mbroz]
2017-07-03 16:49:41 +02:00
Milan Broz
9ade110a25 Fix typo in tests. 2017-06-29 15:55:35 +02:00
Ondrej Kozina
2b3be9055a Disable conversion for legacy luks1 formats.
And export LUKS header size functions.
2017-06-29 15:50:42 +02:00
Ondrej Kozina
10bb186c76 lib: harden checks for null name in resume/suspend 2017-06-29 15:45:51 +02:00
Milan Broz
198f1d10c4 Point pdf links to kernel.org.
Some browsers seems to be already smarter than a 5th grader
and blocks the content on gitlab.
2017-06-29 12:19:32 +02:00
Milan Broz
5be69e92ce Check for interruption during passphrase retry. 2017-06-28 15:11:28 +02:00
Milan Broz
c80acbe4c8 Add back "Passphrase for (dev):" prompt. 2017-06-28 15:07:58 +02:00
Milan Broz
29681c0aa7 Fix access to devices under non-root user.
We cannot allocate loop device early in luksFormat,
use only device access check here.
2017-06-28 14:24:39 +02:00
Milan Broz
fdd6794ce3 Add some sleep to interactive prompt test.
Seems some distros use broken expect package.
2017-06-27 16:25:11 +02:00
Milan Broz
6c7e9608b9 Fix travis install line. 2017-06-27 15:53:41 +02:00
Milan Broz
5171f65c05 Return back password retry support for luksOpen.
Also add interactive test using expect utility.
2017-06-27 15:49:04 +02:00
Milan Broz
86f327d0f5 Add dmsetup remove retry to api test. 2017-06-27 14:14:20 +02:00
Milan Broz
b16fbde032 Add DM_UDEV_DISABLE_LIBRARY_FALLBACK to libdevmapper wrapper.
This call is required for deferred removal of device.

Morever, if the system reports that udev is running, we should not
try to "fix" problems by creating or removing nodes directly through libdevmapper.

(Non-udev case should still work.)
2017-06-27 09:12:05 +02:00
Milan Broz
9437035147 Use open/close syntax for veritysetup.
(but support create/remove aliases)
2017-06-26 15:31:47 +02:00
Milan Broz
f24fb2899e Use open/close syntax for integritysetup.
(but support create/remove aliases)
2017-06-26 15:24:58 +02:00
Milan Broz
19c5248675 Fix deferred test for old libdevmapper (deferred not compiled-in). 2017-06-24 20:05:26 +02:00
Milan Broz
2c3e0aee08 And check libdevmapper support for deferred flag as well. 2017-06-24 19:37:28 +02:00
Milan Broz
552e9c8408 Check DM support for deferred flag.
So it fails correctly on older systems.
2017-06-24 19:07:14 +02:00
Milan Broz
164bbdfcfc Add test for deferred removal.
Print more info in CLI command.
2017-06-24 10:32:48 +02:00
Milan Broz
3efa00d59a Revert deferred flag for keyslots and temp devices.
It could cause races later, replacing with error device is enough.
2017-06-24 09:57:22 +02:00
Milan Broz
ea694a4588 Fix force removal option. 2017-06-23 15:42:46 +02:00
Milan Broz
32d5e59ab6 Implement deferred removal of device.
This can be used in some automated systems and allows device
to be removed after the last user mapping closes it.
2017-06-23 14:41:54 +02:00
Milan Broz
a58ed1ada3 Better specify error codes from crypt_wipe. 2017-06-22 13:32:05 +02:00
Milan Broz
c80dbb2210 Fxi luksKill slot to work in batch mode in non-tty environment.
If there is no TTY on stdin (like nohup or service) then
batch mode should not fail to kill slot.

For more info see Issue#329.
2017-06-21 13:31:08 +02:00
Milan Broz
ce1e5374b9 Fix API tracker URL. 2017-06-18 09:00:11 +02:00
Ondrej Kozina
c4fa881303 luks1: cleanup for added checks
related to bef56af730
2017-06-16 11:09:41 +02:00
Milan Broz
d02b291e2f Remove TODO line. 2017-06-15 13:57:27 +02:00
Milan Broz
4d21f4673d Add Travis configuration file for automated testing. 2017-06-15 13:46:36 +02:00
Ondrej Kozina
6682e6b663 tests: add test for overlaping keyslots in luks1 image 2017-06-15 11:17:36 +02:00
Ondrej Kozina
bef56af730 luks1: harden checks for possibly corrupted headers
this patches improves two areas:

1) it checks for keyslot areas overlaping each other
2) it checks if all keyslot areas fit in header area of device
   (pre-data-offset area) or if it can fit file (detached header)
   it's being loaded from. Those new checks are based on real data
   found in header (offsets) rather than based on assumption calculated
   from key length
2017-06-15 11:17:28 +02:00
Milan Broz
c7de6939ae Fix ioctl argument for block size check. 2017-06-09 10:33:57 +02:00
Milan Broz
2059266a24 Never decrease device block size (for example after attaching loop device). 2017-06-08 16:22:53 +02:00
Milan Broz
edba04c978 Fix batch mode for tools progress function. 2017-06-08 15:05:28 +02:00
Milan Broz
73030aa5fb Make block size size_t type.
And fix all related comparisons and functions.
2017-06-08 14:39:54 +02:00
Milan Broz
34bf809e51 Use device alignment wrapper.
And cache the value to not call ioctl on every block read/write.
2017-06-08 09:30:53 +02:00
Milan Broz
fd6fc16001 Use tools progress print function for cryptsetup-reencrypt. 2017-06-07 21:58:19 +02:00
Milan Broz
e438acfc5f Add wipe of device to integritysetup format. 2017-06-07 15:32:24 +02:00
Milan Broz
3a27c84d98 Rewrite and export crypt_wipe function.
The crypt_wipe can be used to wipe any part of the device,
and also to initialize integrity based device (to reset checksum).
2017-06-07 15:31:13 +02:00
Milan Broz
c6408f4b31 Link tools with -lm. 2017-06-07 15:24:12 +02:00
Milan Broz
fc026a722b integritysetup: fix processing of integer options. 2017-06-06 09:47:12 +02:00
Milan Broz
573a05a10f Add Veracrypt test image with PIM setting. 2017-06-01 16:44:52 +02:00
Milan Broz
6fc383ade1 Fix detection of target presence. 2017-06-01 12:25:39 +02:00
Milan Broz
40a9178c7f Rework detection of DM target flags.
Because there are already 3 targets used, the current detection
based only on dm-crypt is not sufficient.

Add new definition of dm_flags that allows separate target version detect.

Note: we do not want to load targets explicitly; instead, we repeats
detection after operation that could trigger target load.

If dm_flags() call fails, then the target is not yet loaded.
2017-06-01 09:28:09 +02:00
Milan Broz
82f7cae22c Make FEC verity test determnistic. 2017-05-30 14:50:32 +02:00
Ondrej Mosnáček
f786ed8505 Fix strncat usage
The 'strncat' function may write up to n + 1 bytes into destination, so
the 'n' parameter must be sizeof(dest) - strlen(dest) - 1. See [1] for
a nice explanation from US CERT.

[1] https://www.us-cert.gov/bsi/articles/knowledge/coding-practices/strncpy-and-strncat
2017-05-29 12:08:21 +02:00
Milan Broz
7e06265568 Parse integrity mode directly. 2017-05-29 10:40:06 +02:00
Milan Broz
2a50be152e Increase library and symbols version. 2017-05-29 10:23:24 +02:00
Milan Broz
ba5e91e278 Skip integrity test if target not available. 2017-05-28 23:02:49 +02:00
Milan Broz
5a3e3339e0 Make integrity param optional. 2017-05-28 22:47:05 +02:00
Milan Broz
0bb7098fd8 Add integritysetup command line tool for the dm-integrity standalone setting.
The dm-integrity target is intended to be used for authenticated
encryption through LUKS and dm-crypt.

It can be used in standalone as well; for this use case there
is a simple configuration utility called integritysetup
(similar to veritysetup to dm-verity).
2017-05-28 09:22:17 +02:00
Milan Broz
290b593d0b Add runtime check for FEC availability to dm-verity test. 2017-05-15 16:07:17 +02:00
Michal Virgovic
2745be83dd Add tests for FEC dm-verity extension. 2017-05-15 12:39:06 +02:00
Tobias Stoeckmann
44d5269c0a Prevent double free with invalid verity partition.
It is possible to trigger a double free with an invalid verity
partition. All it takes is an unknown hash algorithm, which makes it
a bit more likely than a completely broken partition header. But all
it takes is an error return value of VERITY_read_sb() or strdup().

If crypt_load fails before setting cd->type, crypt_free will handle
the union as if it was of type "none", which means it will call free()
for "active_name", a field which is only properly set up when the
type was actually "none".

In all other cases, "active_name" contains the first 4 or 8 bytes of
the actually used header structure. Fortunately it can be only a
pointer or NULL, so an attacker has no direct control of the value.
Nonetheless it can easily trigger a double free.

Signed-off-by: Tobias Stoeckmann <tobias@stoeckmann.org>
2017-05-02 08:25:40 +02:00
Milan Broz
3f9346836e Get rid of old alignment code and use posix_memalign.
We require posix_memalign already for some time so it makes
no sense to keep old workarounds.
2017-04-30 13:13:46 +02:00
Michal Virgovic
5d1b6f9af3 Update veritysetup man with FEC options. 2017-04-29 15:56:49 +02:00
Milan Broz
882751b51e Update po file... 2017-04-27 12:26:47 +02:00
Milan Broz
bbd59fa314 Fix stupid version typo in release notes. 2017-04-27 10:56:12 +02:00
Milan Broz
57c9d78629 Update README.md. 2017-04-27 10:47:43 +02:00
Milan Broz
78c9004a87 Add 1.7.5 release notes. 2017-04-27 08:42:00 +02:00
Milan Broz
8df2a598a7 Align benchmark output even for longer cipher names. 2017-04-26 14:32:54 +02:00
Harald Hoyer
1691282314 dracut-reencrypt: call "udevadm settle" once more
Somehow testing in qemu resulted sometimes in an endless loop.
Either the timing or the settle fixed the issue.
When the VM was in an endless loop, an strace showed, that the first 512
and 1024 of the crypt partition was read over and over. Either it was
the udev blkid, or some device mapper udev rule.
Maybe the reencrypt tool opens and closes the device fd, where the close
triggers a udev blkid and causes the reencrypt tool to reread the device...
Anyhow.. with this settle the issue was not seen anymore.
2017-04-26 10:50:44 +02:00
Harald Hoyer
3d6bb53b31 dracut-reencrypt: add UUID handling to rd.luks.reencrypt=
This patch adds a udev rule, so that you can specify
rd.luks.reencrypt=<UUID> instead of rd.luks.reencrypt=<devname>

It also moves the job to the "settled" queue, which means, that it is
executed after udev has settled.
2017-04-26 10:50:41 +02:00
Harald Hoyer
6a8a6aea54 dracut-reencrypt: add finished hook
A finished hook prevents dracut-initqueue from exiting and lets it
finish the batched jobs. Without a "finished hook" and without
"root=<dev>" on the kernel command line, the reencrypt job would not be
executed.

Normally you want to reencrypt without a "root=<dev>" on the kernel
command and want to reboot after the reencrypt job is done.

This patch adds the missing "finished hook".
2017-04-26 10:50:36 +02:00
Milan Broz
8c5760fee7 Fix API test for FIPS mode. 2017-04-21 09:32:13 +02:00
Milan Broz
3c2135b36b Fix luksFormat if running in FIPS mode on recent kernel.
Recently introduced check for weak keys for XTS mode makes
zeroed key for algorithm check unusable.

Use random key for the test instead.
2017-04-21 08:22:29 +02:00
Milan Broz
aad597b987 Fix activation of verity device with superblock and FEC. 2017-04-20 09:10:18 +02:00
Milan Broz
5fdfc0b54a Fix AF prototypes and move then to af.h. 2017-04-14 13:25:21 +02:00
Milan Broz
ef966bd261 Fix verity FEC block memory allocation.
Fixes corruption of memory when buffer is too small.
2017-04-14 12:31:44 +02:00
Milan Broz
54cb40fce7 Fix RS algorithm rewrite typo. 2017-04-05 16:29:26 +02:00
Milan Broz
c6a0048b9b Add check for FEC support in kernel dm-verity. 2017-04-05 15:16:13 +02:00
Milan Broz
425e8b9495 Fix possible divide by zero in verity hash blocks calculation. 2017-04-05 14:35:52 +02:00
Milan Broz
82dd6c7fa2 Fix some compiler warnings. 2017-04-05 14:24:20 +02:00
Milan Broz
e4f1faa478 Restructure Reed-Solomon code for verity FEC and remove unneeded parts. 2017-04-05 13:34:26 +02:00
Milan Broz
c7907630f4 Remove some redundant header includes. 2017-04-05 12:03:30 +02:00
Milan Broz
e18a7400b4 Fix compiler warning. 2017-04-05 11:51:22 +02:00
Milan Broz
058831d88c Remove verity FEC superblock support.
It seems to be never used anywhere.
2017-04-05 11:41:08 +02:00
Milan Broz
1da785cb77 Use common function for accessing FEC devices.
TODO: the device wrappet should hanbdle EINTR better...
2017-04-05 10:58:03 +02:00
Milan Broz
3a058a4f21 Remove local fec.h. 2017-04-05 08:29:03 +02:00
Milan Broz
3d6a589a04 Fix dm-verity max-size parameter. 2017-04-04 14:27:52 +02:00
Milan Broz
6c8b3686b4 Add FEC info to init_by_name.
And use it in veritysetup dump.
2017-04-03 13:55:20 +02:00
Milan Broz
fc0bef732b Add FEC offset parameter for verity. 2017-04-03 12:34:50 +02:00
Milan Broz
e8eab081c5 Add code for activation wirh FEC device. 2017-04-03 10:21:37 +02:00
Milan Broz
00419c6c41 Introduce function to calculate verity hash device size. 2017-04-03 10:19:29 +02:00
Milan Broz
7307293c87 Use explicit 32bit value in API for FEC roots. 2017-04-03 10:15:44 +02:00
Milan Broz
912f5b8f5b Do not write FEC superblock if no-superblock option is set. 2017-04-02 15:51:40 +02:00
Sami Tolvanen
c2cf33af24 WIP: Add support for verity FEC. 2017-04-01 21:23:10 +02:00
Milan Broz
eb59311136 Fix access to unaligned hidden TrueCrypt header.
On native 4k-sector device the old hidden header is not aligned
with hw sector size and derect-io access with SEEK_END fails.

Let's extend blockwise functions to support a negative offset
and use the same logic as normal unaligned writes.

Fixes problem mentioned in
https://gitlab.com/cryptsetup/cryptsetup/merge_requests/18
2017-03-27 12:04:31 +02:00
Milan Broz
fc42f878e9 Update README.md for 1.7.4. 2017-03-15 10:54:56 +01:00
Milan Broz
98368c4770 Update copyright years. 2017-03-12 13:17:15 +01:00
Milan Broz
c9da7f9f8c Add 1.7.4. Release notes. 2017-03-12 13:01:05 +01:00
Milan Broz
e7f8727d2d Fix some compiler warnings / wipe PIM properly. 2017-03-12 12:00:38 +01:00
Milan Broz
2657746451 Used LUKS1 compiled-in defaults also in Python wrapper. 2017-03-12 10:29:46 +01:00
Milan Broz
2701993dd6 Update po files. 2017-03-12 10:18:54 +01:00
Daniel Reichelt
9a798a766e support PIM parameter for VeraCrypt compatible devices
This patch adds the --veracrypt-pim=INT and --veracrypt-query-pim command-
line parameters to support specification of or being queried for a custom
Personal Iteration Multiplier respectively. This affects the number of
iterations for key derivation from the entered password. The manpage is
also updated accordingly.

Fixes Issue #307.
2017-03-02 09:11:23 +01:00
Bastien DHIVER
36419b25aa Add hashMode parameter in CryptSetup_luksFormat() 2017-03-01 13:32:26 +01:00
Milan Broz
9da67b701d Clarify use of --size parameter. 2017-02-15 20:26:02 +01:00
Milan Broz
ef7ecb5567 Fix race while allocating free loop device.
Fixes Issue #314.

Thanks to Martin Jeřábek for the report.
2017-01-20 15:27:40 +01:00
Milan Broz
a77c609c62 Fix possible fd leaks after exec.
Thanks Natanael Copa for the report.
Fixes issue#313.
2017-01-20 13:47:14 +01:00
Milan Broz
bca2bab560 Fix OpenSSL 1.1.0 compatibility
If backward-compatible API is not defined (-DOPENSSL_API_COMPAT=0x10100000L)
deprecated symbols cannot be used.

Also see https://bugs.gentoo.org/show_bug.cgi?id=604698

Thanks eroen for reporting this.
2017-01-05 09:06:31 +01:00
Milan Broz
e129b13402 Fix TrueCrypt URL in man page. 2017-01-04 08:04:10 +01:00
Arno Wagner
520b6d7344 some typos fixed in FAQ 2017-01-01 20:39:46 +01:00
Arno Wagner
bed395d039 Updates to FAQ
- Finished section 9 initrd with examples how to do your own
- Some minor fixes elswehere
2017-01-01 20:14:21 +01:00
Milan Broz
566f8c322b Update veritysetup man page.
Thanks Michal Virgovic for patch.
2016-12-13 14:29:13 +01:00
Milan Broz
807cedf4f3 Check for data device and hash device area overlap in veritysetup.
Thanks Michal Virgovic for tests.
2016-12-13 13:52:05 +01:00
Milan Broz
ef8a7d82d8 Update Readme.md. 2016-11-16 16:14:02 +01:00
Milan Broz
b906e8d299 Merge branch 'master' into 'master'
Fix use of LibreSSL.

Libressl declares `OPENSSL_VERSION_NUMBER 	0x20000000L`.

See merge request !12
2016-11-10 07:51:12 +00:00
Aric Belsito
0e14147132 Fix use of LibreSSL. 2016-11-03 11:55:39 -07:00
Milan Broz
c10e106787 Fix missing CRYPT_ACTIVATE_SAME_CPU_CRYPT flag check in status command. 2016-11-02 19:55:51 +01:00
Milan Broz
61725ee7cc Update readme.md for version 1.7.3. 2016-10-30 15:02:21 +01:00
Milan Broz
39f88f1712 Set devel version. 2016-10-30 14:53:54 +01:00
Milan Broz
e14aba8cf1 Add 1.7.3. Release Notes. 2016-10-28 11:19:26 +02:00
Milan Broz
97e774226d Update po files. 2016-10-28 11:01:23 +02:00
Milan Broz
6220e9c6cc Update po files. 2016-10-28 10:56:27 +02:00
Milan Broz
cba2a6c87c Update po files. 2016-10-22 10:35:52 +02:00
Milan Broz
71d7383491 Merge branch 'eviche/cryptsetup-patch-1' 2016-10-22 09:28:41 +02:00
Eduardo Villanueva Che
2c833c2342 Fixed veritysetup bug with hash offsets bigger than 2gb.
The lseek in function write_blockwise() could return value
that is greater than integer for result so it can overflow
and fail the whole write.
[comment added by mbroz]
2016-10-22 09:24:09 +02:00
Milan Broz
45fa8e724f Merge branch 'master' into 'master'
Fix several minor spelling errors found by Lintian

Fixes #306 

* lib/setup.c: miliseconds -> milliseconds
* lib/utils_wipe.c: Unsuported -> Unsupported
* man/crypsetup.8: implicitely -> implicitly
* man/veritysetup.8: verion -> version
* python/pycryptsetup.c: miliseconds -> milliseconds

See merge request !11
2016-10-22 07:04:10 +00:00
Jonas Meurer
b2a6e338b5 Fix several minor spelling errors found by Lintian
* lib/setup.c: miliseconds -> milliseconds
* lib/utils_wipe.c: Unsuported -> Unsupported
* man/crypsetup.8: implicitely -> implicitly
* man/veritysetup.8: verion -> version
* python/pycryptsetup.c: miliseconds -> milliseconds
2016-10-21 21:54:08 +02:00
Milan Broz
34734395c8 Set configured default iteration time early in crypt_init constructor. 2016-10-20 14:23:28 +02:00
Milan Broz
a3ee8f9cb8 Rephrase UUID error message forc cryptsetup-reencrypt. 2016-10-20 14:10:29 +02:00
Milan Broz
7f9e33ca1e Update po files. 2016-10-20 13:47:39 +02:00
Milan Broz
d4e8033fe0 Fix error path after conversion to OpenSSL 1.1.0. 2016-10-20 08:22:38 +02:00
Milan Broz
ab61af7481 Fix Nettle crypto backend definitions. 2016-10-19 21:18:07 +02:00
Milan Broz
8f204b4e23 Support OpenSSL 1.1.0 in cryptsetup backend. 2016-10-19 15:27:01 +02:00
Milan Broz
3b40e9dc93 Try to find python$VERSION-config. 2016-10-19 12:39:14 +02:00
Per x Johansson
b181b0ef6e Fix memory leak when using openssl backend
Fixes a memory leak when using openssl backend caused by mismatched
calls to EVP_DigestInit and EVP_DigestFinal_ex.
2016-10-18 14:05:49 +02:00
Milan Broz
4083bb2c0f Verify passphrase in cryptsetup-reencrypt when encrypting new drive. 2016-09-05 14:42:39 +02:00
Milan Broz
9d004a6aa4 Add link to LUKS spec on title page. 2016-09-05 09:37:36 +02:00
Milan Broz
d30bfe8b8e Update po files. 2016-08-03 14:19:20 +02:00
Milan Broz
38fbd85004 Update po files. 2016-07-25 12:23:09 +02:00
Milan Broz
467728b535 Fix keylength = 0 (no key) case. 2016-07-02 22:42:40 +02:00
Milan Broz
0c990eb0a2 Merge branch 'stoeckmann/cryptsetup-malloc' 2016-07-02 21:06:12 +02:00
Milan Broz
23ce9aa47e Fix crypt_generate_volume_key to use size_t for keylength. 2016-07-02 21:01:25 +02:00
Tobias Stoeckmann
a0587d4307 Avoid integer overflows during memory allocation.
It is possible to overflow integers during memory allocation with
insanely large "key bytes" specified in a LUKS header.

Although it could be argued to properly validate LUKS headers while
parsing them, it's still a good idea to fix any form of possible
overflow attacks against cryptsetup in these allocation functions.
2016-07-02 20:57:10 +02:00
Milan Broz
ea5e9c9fe2 Merge branch 'stoeckmann/cryptsetup-master' 2016-07-02 20:42:32 +02:00
Tobias Stoeckmann
14ebbce280 Avoid buffer overflow in uuid_or_device.
The function uuid_or_device is prone to a buffer overflow if a very long
spec has been defined. The range check happens against PATH_MAX, with
i being set to 5 (due to "UUID=" offset of spec), but "/dev/disk/by-uuid"
has been already written into device.

The difference between "/dev/disk/by-uuid" and "UUID=" is 13, therefore
the correct range check must happen against PATH_MAX - 13.
@@ -204,7 +204,7 @@ const char *uuid_or_device(const char *spec)
                strcpy(device, "/dev/disk/by-uuid/");
2016-07-02 20:41:51 +02:00
Milan Broz
67d55d08f8 Fix PBKDF2 benchmark to not double iteration count for corner case.
If measurement function returns exactly 500 ms, the iteration
calculation loop doubles iteration count but instead of repeating
measurement it uses this value directly.

Thanks to Ondrej Mosnacek for bug report.
2016-06-23 09:47:22 +02:00
Milan Broz
4d3a501b83 Force test to read device to detect corrupted blocks.
(If udev scanning is switched off, there is no real activity on device yet.)
2016-06-23 09:45:06 +02:00
Ondrej Kozina
16fab74ab1 code cleanup related to devfd checks
alter all checks for devfd value after device_open to
less than zero insted of equals to -1. device_open will
return values different from -1 in case error happens.

In LUKSv1 device_open should always return -1 in case of
error but this check is safer.

The rest is just formating improvement.
2016-06-08 13:12:06 +02:00
Milan Broz
f397d42d73 Update Readme.md. 2016-06-04 14:22:00 +02:00
Milan Broz
576a2e5b86 Workaround for align test for scsi_debug kernel in-use issue. 2016-06-04 13:12:15 +02:00
Milan Broz
060a4fbef0 Fix possible leak if reencryption is interrupted. 2016-06-04 12:36:51 +02:00
Milan Broz
f473fb3d7d Revert soname change. 2016-06-04 12:34:43 +02:00
Milan Broz
36f6073ec5 Set devel version. 2016-06-04 11:41:46 +02:00
Milan Broz
ebf7732943 Add 1.7.2 Release notes. 2016-06-04 11:36:36 +02:00
Milan Broz
c62427fd47 Update po files. 2016-06-02 19:18:04 +02:00
Milan Broz
ff09d1c531 Update po files. 2016-05-25 15:10:12 +02:00
Milan Broz
2852a48e6a Fix error message. 2016-05-25 14:56:13 +02:00
Milan Broz
1ab1803a43 Update po files. 2016-05-19 13:12:15 +02:00
Milan Broz
8f84fb49fa Fix help text for cipher benchmark specification. 2016-05-18 09:11:52 +02:00
Ondrej Kozina
e1dca468f5 keymanage: eliminate double close() call
fix  double close() cases in LUKS_hdr_backup() and LUKS_hdr_restore()
functions. It should be harmless unless libcryptsetup is used
in multi-thread setup which is not supported anyway.
2016-05-13 13:05:46 +02:00
Milan Broz
b1b3d93c96 Add ABI tracker output link. 2016-05-07 10:19:05 +02:00
Milan Broz
7d80112d4f Update LUKS doc format.
Clarify fixed sector size and keyslots alignment.
2016-05-04 15:48:04 +02:00
Milan Broz
4dd703ea6c Support activation options for error handling modes in dm-verity.
This patch adds veritysetup support for these Linux kernel dm-verity options:

  --ignore-corruption - dm-verity just logs detected corruption
  --restart-on-corruption - dm-verity restarts the kernel if corruption is detected

  If the options above are not specified, default behaviour for dm-verity remains.
  Default is that I/O operation fails with I/O error if corrupted block is detected.

  --ignore-zero-blocks - Instructs dm-verity to not verify blocks that are expected
   to contain zeroes and always return zeroes directly instead.

NOTE that these options could have serious security or functional impacts,
do not use them without assessing the risks!
2016-05-04 10:07:47 +02:00
Milan Broz
99a254f2f6 Fix dm-verity test typo. 2016-05-04 09:14:32 +02:00
Ondrej Kozina
1b7799cb1d dracut_90reencrypt: fix warns reported by static analysis
- moddir is assigned in parent script run by dracut (warning was
  silenced)

- fix defect wrt to assignement and making variable local on
  same line. The variable cwd was first assigned by subshell
  and later any error originating in subshell was masked by
  making the variable local (which returns always 'true')
2016-04-25 15:47:18 +02:00
Milan Broz
7eba57b4c0 Avoid possible divide-by-zero warnings. 2016-04-24 12:38:19 +02:00
Milan Broz
1f51cfcf57 Set devel version. 2016-04-24 12:13:30 +02:00
Milan Broz
683e4db48b Fix warnings reported by static analysis.
- ensure that strings are \0 terminated (most of this is already
handled on higher level anyway)

- fix resource leak in error path in tcrypt.c

- fix time of check/time of use race in sysfs path processing

- insruct Coverity scanner to ignore constant expression in random.c
(it is intented to stop compile-time misconfiguration of RNG that would be fatal)
2016-04-24 12:07:31 +02:00
Milan Broz
c2ddd48f50 Avoid tar archive warnings if tests are run as superuser. 2016-04-19 14:56:43 +02:00
Milan Broz
eb8ff73595 Merge branch 'VittGam/cryptsetup-patch-1' 2016-04-19 11:24:09 +02:00
Milan Broz
54c4b1656f Include sys/sysmacros.h if present.
Needed for major/minor definitions.

Thanks Mike Frysinger for pointing this out.
2016-04-19 10:57:45 +02:00
Milan Broz
1000b40a3a Link reencryption utility to uuid library.
(Fixes last patch.)
2016-04-19 10:22:26 +02:00
VittGam
e7e5354332 Fix off-by-one error in maximum keyfile size.
Allow keyfiles up to DEFAULT_KEYFILE_SIZE_MAXKB * 1024 bytes in size, and not that value minus one.

Signed-off-by: Vittorio Gambaletta <git-cryptsetup@vittgam.net>
2016-04-19 03:58:10 +00:00
Ondrej Kozina
b5365ba13d cryptsetup-reencrypt: enable resume of decryption
to enable resume of interrupted decryption user has
to pass uuid of the former luks device. That uuid is used
to resume the operation if temporary files LUKS-* still
exist.
2016-04-13 15:01:37 +02:00
Milan Broz
f2cdc6f5f4 Update po files. 2016-04-13 14:58:55 +02:00
Arno Wagner
a0c251c7cc sync to WIKI version 2016-03-23 15:53:02 +01:00
Milan Broz
d7a224e47a Disable DIRECT_IO for LUKS header with unaligned keyslots.
Fixes issue#287.

Such a header is very rare, it is not worth to do more detection here.
2016-03-23 13:44:37 +01:00
Milan Broz
6894701392 Merge branch 'athira-rajeev/cryptsetup-fix_device_block_size_fd' 2016-03-23 10:06:40 +01:00
Athira Rajeev
8e4e898ce5 Fix device_block_size_fd to return bsize correctly incase of files.
This patch is for issue #287

In the code for returning block size ( device_block_size_fd in lib/utils_device.c ),
always returns zero in case of files and device_read_test is not executed.

This patch is to fix device_block_size_fd to return block size correctly incase of files.

Signed-off-by: Athira Rajeevatrajeev@linux.vnet.ibm.com
2016-03-19 18:57:45 +05:30
Milan Broz
add8fb8fd2 Update README for 1.7.1. 2016-02-28 14:48:41 +01:00
Milan Broz
3807dbf2f3 Add 1.7.1 release notes. 2016-02-28 13:38:42 +01:00
Milan Broz
b5d1c9241c Fix align test for new scsi_debug defaults. 2016-02-28 11:12:40 +01:00
Ondrej Kozina
3e742452cd cryptsetup-reencrypt: harden checks for hdr backups removal
There're various situations where hdr backups together with log file
may get removed even when the hdr was already marked unusable. This
patch fixes the most sever case already reported and generaly tries
harder protecting the log file and both hdr backups.
2016-02-28 09:44:22 +01:00
Ondrej Kozina
d7b127549c cryptsetup-reencrypt: drop unreachable code path
MAKE_USABLE flag is never used in device_check()
2016-02-28 09:44:07 +01:00
Milan Broz
d841f97d44 Update po files. 2016-02-28 09:31:36 +01:00
Milan Broz
0c7d947d2d Update po files. 2016-02-23 17:41:55 +01:00
Milan Broz
05604b77ea Move README back. 2016-02-23 17:40:10 +01:00
Ondrej Kozina
2c072eb6b6 Clarify the reencrypt_keyslot= option 2016-02-21 18:48:49 +01:00
Milan Broz
080a9863c1 Temporarily rename README.txt (until GitLab updates markdown README preference handling) 2016-01-30 08:33:04 +01:00
Milan Broz
22f5760d47 Update TODO. 2016-01-26 15:17:02 +01:00
Milan Broz
4dc88e8ffb Fix kernel crypto backend to set key before accept call even for HMAC. 2016-01-04 14:19:50 +01:00
Milan Broz
229497871d Fix write_lseek prototype and avoid using void in arithmetic warning. 2016-01-03 16:05:17 +01:00
Milan Broz
9ce5dd1082 Fix cipher_null key setting in kernel crypto backend. 2016-01-03 11:03:47 +01:00
Ondrej Kozina
03d9db921b Fix hang in low level device-mapper code.
udev cookies should be set right in before the dm_task_run()
call otherwise we risk a hang while waiting for a cookie
associated with not yet executed dm task.

For example: failing to add table line (dm_task_add_target())
results in such hang.
2016-01-02 21:06:15 +01:00
Milan Broz
93ed401b7c Set skcipher key before accept() call in kernel crypto backend.
Also relax input errno checking to catch all errors.
2016-01-02 20:02:28 +01:00
Milan Broz
e34938f21d Allow special "-" (standard input) keyfile hangdling even for TCRYPT devices.
Fail if there are more keyfiles specified for non-TCRYPT device.

Fixes issue#269.
2016-01-01 19:15:06 +01:00
Milan Broz
87dbaa0bd7 Update sr.po. 2015-12-25 10:55:00 +01:00
Milan Broz
119627c8cf Merge branch 'misc/cryptsetup-add_gitignore' 2015-12-25 10:53:16 +01:00
Michael Scherer
973efb63ab Add a basic .gitignore in the project 2015-12-19 22:49:16 +01:00
Milan Broz
a1511e6a86 Merge branch 'louipc/cryptsetup-master' 2015-12-13 10:07:03 +01:00
Loui Chang
1d5663ddec Update version control history url
Signed-off-by: Loui Chang <louipc.ist@gmail.com>
2015-12-13 00:17:25 -05:00
Loui Chang
5e8d92146b Man page typo
Signed-off-by: Loui Chang <louipc.ist@gmail.com>
2015-12-13 00:17:01 -05:00
Ondrej Kozina
8e160562ee read_lseek_blockwise: use void pointer 2015-12-12 17:02:27 +01:00
Milan Broz
7033105ce7 Fix password handling from stdin (it cannot use offset). 2015-12-01 12:20:39 +01:00
Ondrej Kozina
091dfa0c26 Slight code style improvements for blockwise functions. 2015-12-01 10:57:04 +01:00
Ondrej Kozina
7fc006b63b Add interrupt safe read_lseek_blockwise function. 2015-12-01 10:52:42 +01:00
Ondrej Kozina
3e653ace3e Use const for header in LUKS_keyslot_area. 2015-12-01 10:52:25 +01:00
Ondrej Kozina
64f3df44ee Use read/write buffer functions where appropriate. 2015-12-01 10:51:56 +01:00
Ondrej Kozina
42ccddeff3 Add read_buffer and write_buffer functions.
Introduce functions for proper I/O handling. These functions
are able to deal with interrupts and partial I/O.
2015-12-01 10:44:02 +01:00
Ondrej Kozina
0435fbf2e5 Avoid write with zero size.
This can happen if write buffer size is smaller than underlying
block size and initial buffer is misaligned.

Also use size_t for buffer length variables.
2015-12-01 10:42:08 +01:00
Milan Broz
34ddae154e Fix luksKillSlot to not suppress provided password in batch mode.
Batch mode should enable no-query keyslot wipe but only if user
did not provided password or keyfile explicitely.

Fixes issue #265.

Signed-off-by: Milan Broz <gmazyland@gmail.com>
2015-11-22 12:50:34 +01:00
Milan Broz
8da37ce4b0 Update test (removal of get_last_error). 2015-11-20 09:18:58 +01:00
Milan Broz
9cbe74c2db Remove last error handling (error is logged). 2015-11-20 09:18:58 +01:00
Milan Broz
002ba59ff1 Simplify tools_get_key. 2015-11-20 09:18:31 +01:00
Milan Broz
d293de579a Fix various backward incompatibilities in password processing. 2015-11-20 09:18:31 +01:00
Milan Broz
4aea3b81ee Remove password callback interface.
This was a design mistake and should not be handled inside libcryptsetup code.
2015-11-20 09:18:31 +01:00
Milan Broz
5293f5aae1 Move terminal handling to tools wrapper. 2015-11-20 09:18:31 +01:00
Milan Broz
39698fa6b7 Remove terminal input from libcryptsetup API calls. 2015-11-20 09:18:31 +01:00
Milan Broz
e80f9b5c65 Remove key_from_file wrapper. 2015-11-20 09:18:31 +01:00
Milan Broz
f0986be2e3 Export crypt_keyfile_read(). 2015-11-20 09:18:31 +01:00
Milan Broz
252cdef110 Extract keyfile read from get_key wrapper. 2015-11-20 09:18:31 +01:00
Milan Broz
8ab9c9dc68 Update po files. 2015-11-20 08:55:36 +01:00
Milan Broz
a5363f184c Set devel version. 2015-11-03 13:41:14 +01:00
Milan Broz
e2637c5d49 Prepare version 1.7.0. 2015-11-03 13:32:24 +01:00
Milan Broz
4a72695241 Update README.md. 2015-11-03 13:15:42 +01:00
Milan Broz
af31af5e3d Add 1.7.0 Release notes. 2015-11-03 13:03:55 +01:00
Milan Broz
2aa0bb7eac Update LUKS default hash and kernel crypto api hash check. 2015-11-02 21:07:49 +01:00
Milan Broz
8ae62715a8 Update po files. 2015-11-02 21:07:20 +01:00
Arno Wagner
506ba27358 Synced to Wiki version with new markup stripper. 2015-11-02 20:37:47 +01:00
Milan Broz
4384e50578 Decrease iteration time for compat tests. 2015-10-29 12:44:15 +01:00
Milan Broz
1623ee71ab Remove experimental warning for reencrypt tool. 2015-10-29 12:16:37 +01:00
Milan Broz
f425d07ec7 Switch to sha256 and 2s iteration time for LUKS devices defaults.
Note that no longer using SHA1 is just to prevent situation
when it is no longer available on hardened systems, there is
no known security problem (finding collisions is not a problem for LUKS).

Increasing iteration time is in combination with PBKDF2 benchmark
fixes try to keep PBKDF2 iteration count still high enough and
also acceptable for users.

(Long term is to replace PBKDF2 algorithm with Password Hashing
Competiton winner.).

N.B. distributions can change these defaults in compilation time.
2015-10-29 12:08:14 +01:00
Ondrej Kozina
d260be02d4 tcrypt: fix potential memory leak on error path 2015-10-29 12:06:40 +01:00
Milan Broz
4609fd87d7 Fix PBKDF2 iteration benchmark for longer key sizes.
The previous PBKDF2 benchmark code did not take into account
output key length.
For SHA1 (with 160-bits output) and 256-bit keys (and longer)
it means that the final value was higher than it should be.

For other hash algorithms (like SHA256 or SHA512) it caused
that iteration count was smaller (in comparison to SHA1) than
expected for the requested time period.

This patch fixes the code to use key size for the formatted device
(or default LUKS key size if running in informational benchmark mode).

Thanks to A.Visconti, S.Bossi, A.Calo and H.Ragab
(http://www.club.di.unimi.it/) for point this out.
(Based on "What users should know about Full Disk Encryption
based on LUKS" paper to be presented on CANS2015).
2015-10-29 11:52:18 +01:00
Milan Broz
9e90d91446 Update da.po. 2015-10-12 15:16:25 +02:00
Milan Broz
7bbf0796b5 Merge branch 'glebfm/cryptsetup-passwdqc' 2015-10-12 14:17:55 +02:00
Milan Broz
fe3148f074 Tweak passwdqc use. 2015-10-12 14:15:03 +02:00
Gleb Fotengauer-Malinovskiy
5e9c27118e Add optional libpasswdqc support for new LUKS passwords
If password is entered through terminal (no keyfile specified) and
cryptsetup is compiled with --enable-passwdqc[=/etc/passwdqc.conf],
default system passwdqc settings are used to check password quality.
2015-10-08 17:30:26 +00:00
Milan Broz
c362ba9293 Update it.po. 2015-09-24 10:20:31 +02:00
Milan Broz
e97048dd32 Set devel version. 2015-09-08 15:17:16 +02:00
Milan Broz
5ea0ba61be Add release notes for 1.6.7 link. 2015-09-08 13:11:36 +02:00
Milan Broz
7ae863e380 Prepare version 1.6.8. 2015-09-08 12:53:48 +02:00
Milan Broz
f238e8c075 Add 1.6.8 release notes. 2015-09-08 12:26:54 +02:00
Milan Broz
7d9a14fd24 Fix some signed/unsigned compiler warnings. 2015-09-08 08:12:07 +02:00
Milan Broz
2f964d95d8 Fix benign warning in clang analysis output. 2015-09-08 07:54:03 +02:00
Milan Broz
00f419e5ea Add zh_CN.po. 2015-09-05 13:07:05 +02:00
Milan Broz
cc698dcde3 Update es.po. 2015-08-31 10:08:36 +02:00
Milan Broz
edced6cfed Update nl.po. 2015-08-30 12:58:33 +02:00
Milan Broz
4fb11976d2 Update po files. 2015-08-28 12:59:59 +02:00
Milan Broz
68ba5b2b36 Update fr.po. 2015-08-27 16:22:13 +02:00
Milan Broz
65fa22ff23 Override password quality check if used cipher is cipher_null. 2015-08-27 16:21:07 +02:00
Milan Broz
c25d81d2a1 Update po files. 2015-08-27 07:53:13 +02:00
Milan Broz
57d16a7a55 Fix misleading error messages in reencrypt. 2015-08-26 16:15:11 +02:00
Milan Broz
def397d0c8 Update libcryptsetup.h comments. 2015-08-26 16:10:10 +02:00
Milan Broz
7843415243 Move string_to_size to userspace tools. 2015-08-26 12:42:25 +02:00
Milan Broz
5a8b045bdd Properly support stdin "-" handling for luksAddKey. 2015-08-26 12:41:20 +02:00
Milan Broz
ab62f45d57 Use stdin and "-" file check wrapper. 2015-08-26 10:54:33 +02:00
Milan Broz
e521edd6ca Print cryptsetup library version in crypto init. 2015-08-26 10:42:47 +02:00
Milan Broz
3a0293a299 Do not link FIPS helper to cryptsetup anymore.
Just print info about FIPS mode in RNG init.
2015-08-26 10:36:49 +02:00
Milan Broz
8a4db1ad7b Ingore Whirlpool test instead of failing. 2015-08-26 10:35:38 +02:00
Milan Broz
1aba9ab444 Cryptsetup resize will try resize also underlying device.
If encrypted device is file-backed, resize should try to resize
underlying loop device as well.
2015-08-19 14:16:42 +02:00
Milan Broz
dfa2755aba If the null cipher is used, allow only empty password for LUKS.
The cipher_null is no-encryption, it can be used for testing
or temporarily when encrypting device (cryptsetup-reencrypt).

Accepting only empty password prevents situation when you replace
a LUKS header on an unlocking device with the faked header using
null cipher (and the same UUID).
Here a system could think that the device was properly unlocked
(with any entered password) and will try to use this unencrypted
partition instead.
(IOW it prevents situation when attacker intentionaly forces
an user to boot into dirrerent system just by LUKS header manipulation.)

Properly configured systems should have an additional integrity protection
in place here (LUKS here provides only confidentiality) but it is better
to not not allow this situation in the first place.
(Despite the fact that once you allow physical tampering of your system
it cannot be properly secured anymore.)
2015-07-02 08:21:19 +02:00
Milan Broz
6e82bdd9a5 Do not use real password when unlocking "fake" header on reecryption.
If reencrypt removes encryption (or adds encryption to not yet encrypted system)
there is a temporary header using null (none) cipher.
We do not need to pass through password when unlocking these devices.
2015-07-02 08:18:44 +02:00
Milan Broz
0dc245401f Allow to enter empty password through stdin pipe.
Also always use empty passsword when using null cipher in tests.
2015-07-02 08:18:12 +02:00
Milan Broz
a57f1b1b64 Silence repeated device removal in verity test. 2015-07-02 08:13:42 +02:00
Milan Broz
1a50fee1d0 Update po files. 2015-04-19 09:55:13 +02:00
Milan Broz
046e0e5280 Update README.md. 2015-03-23 21:20:56 +01:00
Milan Broz
656b55cd4b Set devel version. 2015-03-23 20:41:33 +01:00
Milan Broz
8d7af433d8 Update po files. 2015-03-23 20:40:04 +01:00
Milan Broz
dc3de39eb7 Include prototype for stat(). 2015-03-23 20:38:14 +01:00
Milan Broz
3d403a7bd0 Bump libcryptsetup version. 2015-03-23 18:22:16 +01:00
Milan Broz
91f6296699 Prepare version 1.6.7. 2015-03-23 17:49:06 +01:00
Milan Broz
bd94eb36b3 Update po files. 2015-03-20 13:32:42 +01:00
Milan Broz
1a19329b18 Use silent rules in autoconf. 2015-03-20 13:32:13 +01:00
Milan Broz
78a43c053a Update po files. 2015-03-19 12:35:09 +01:00
Milan Broz
d7d76e72f7 Update URLs (->gitlab.com).
The code.google is going to be abandoned.
Thank you you for all the fish.
2015-03-19 11:23:16 +01:00
Milan Broz
dd0dcc05df Fix typo in URL. 2015-03-19 11:05:28 +01:00
Milan Broz
3be8731fef Add notes about releases. 2015-03-19 11:03:14 +01:00
Milan Broz
86d0ff1a2b Add README.md for project page info. 2015-03-19 10:43:40 +01:00
Milan Broz
3adfe80601 Test device read only once for O_DIRECT.
Also do not report error for disappeared device (it is reported later on real access).
2015-03-19 09:39:36 +01:00
Milan Broz
0bc437d92c Detect if O_DIRECT is usable on device allocation.
Try to read the first sector of a device when allocating
device context.

Should fix issue#247.
2015-03-18 15:01:53 +01:00
Milan Broz
6b10f30eb9 Reorder algorithms for VeraCrypt modes. 2015-02-27 10:12:54 +01:00
Milan Broz
fedd5bc969 Update de.po. 2015-02-26 08:08:16 +01:00
Milan Broz
8aee4f95fb Clarify using of VeraCrypt modes in libcryptsetup.h. 2015-02-25 10:55:24 +01:00
Milan Broz
1f2d8de95f Support VeraCrypt devices (TrueCrypt extension).
Add CRYPT_TCRYPT_VERA_MODES libcryptswtup flag and
--veracrypt option.

Fixes issue#245.
2015-02-24 22:04:15 +01:00
Milan Broz
dced269426 Update kernel version in man page. 2015-02-23 10:19:02 +01:00
Milan Broz
b834a59eaf Fix typo in man page.
Fixes issue#244.
2015-02-20 16:57:20 +01:00
Milan Broz
4f7b413638 Add low-level performance options for dmcrypt tuning.
The patch adds the two options
  --perf-same_cpu_crypt
  --perf-submit_from_crypt_cpus
that set the same named options inside dmcrypt
(available in Linux kernel 3.20 and later).
2015-02-20 16:46:34 +01:00
Milan Broz
e4355c2973 Wait for udev scan before removing device in reencrypt test. 2015-02-20 13:02:27 +01:00
Milan Broz
31a4d552a2 Support keyfile offset and keyfile size option even for plain volumes.
For historic reasons, in the plain mode the hashing is not used
if keyfile is used (with exception of --key-file=-).

Print warning if the parameters are ignored.

For other cases, uses keyfile offset, keyfile size and hash
as psecified on commandline.

Partially fixes issue#243
2015-02-20 12:55:21 +01:00
Milan Broz
6d51e8ab69 Support permanent device decryption using cryptsetup-reencrypt --decrypt. 2015-01-27 14:20:34 +01:00
Milan Broz
8157e47ad4 Support keyfile for luksAddKey if the master key is specified.
If AddKey was called with master key argument, the code always asked
for a passphrase ignoring the keyfile argument.

Now it is properly processed as the same as if no master key is specified.
2015-01-26 14:42:46 +01:00
Milan Broz
62b0138dad Allow to use --header option in all LUKS commands.
The --header always takes precedence over positional device argument.

Also allow specify UUID= for luksSuspend and luksResume if used with
detached header.
2015-01-26 13:31:37 +01:00
Milan Broz
c13a8003fa Mention that loop-AES extension cannot use real terminal for key file input.
Based on issue#242.
2015-01-15 16:03:54 +01:00
Milan Broz
979aec773e Fix activation using (UNSECURE) ECB mode.
Apparently there are some people using ECB.

This mode by design do not use any IV, unfortunately
kernel dmcrypt allows to specify them (but userspace crypto api don't).

Let support activation as it was in previous version.

Should fix issue#238.
2015-01-15 13:21:42 +01:00
Milan Broz
b789b011a2 Fix some compiler warnings introduced recently. 2015-01-15 12:27:34 +01:00
Colin Misare
ea8864badf printing unsigned fields as unsigned 2015-01-15 11:14:42 +01:00
Milan Broz
49335b600f Allow luksSuspend without explicitly specify detached header.
If LUKS device was configured to use detached header, suspend operation
required --header option. For now it is enough that active device in-kernel
UUID type is set properly.

FIxes issue#229.
2015-01-15 10:40:17 +01:00
Milan Broz
7245af59d3 Get rid of libfipscheck library.
With recent RHEL changes we need only check /sys file
and do not need to link to this FIPS monster.
2015-01-12 21:56:44 +01:00
Milan Broz
f7b61b2617 Prevent compiler to optiize-out memset for on-stack variables.
Also see
https://cryptocoding.net/index.php/Coding_rules#Prevent_compiler_interference_with_security-critical_operations

The used code is inspired by the code in Blake2 implementation.
2015-01-11 20:26:45 +01:00
Ondrej Kozina
dc40b91cdf libcryptsetup: drop FIPS power on self test
- cryptsetup library is not required to be FIPS certified anymore
  due to fact gcrypt PBKDF2 algorithm can be used instead of
  cryptsetup internal one.

- check in library constructor is no longer needed and therefore
  removed.

- all other checks regarding MK extraction or random generator
  restrictions remain the same
2015-01-10 21:09:17 +01:00
Milan Broz
eccf347568 Flush stdout when expecting user input on stdin. 2015-01-10 20:36:49 +01:00
Milan Broz
e24a72f84c Fix crash if non-GNU strerror_r is used.
The strerror_r call exists in POSIX and GNU variant,
if POSIX variant is used (like in musl libc replacement)
we cannot rely on char* pointer.

Fixes issue#237.
2015-01-10 20:33:42 +01:00
Milan Broz
2c70c057d6 Fix typo in man page. 2014-11-02 18:18:36 +01:00
Milan Broz
f16f37233f Fix partial reads and handle EINTR in reencryption code.
The partial read usually happens only on IO error,
so reencrypt at least part what is read properly.

For EINTR code must restart read completely.

Fixes issue#226.
2014-10-04 15:39:38 +02:00
Ondrej Kozina
3cffadb508 fix possible close of unrelated fd on error path
- infd var is uninitialised on error path in case where
  maxlen is less than 1
2014-10-01 20:10:23 +02:00
Ondrej Kozina
ce30d5f1fd add vfat test image 2014-09-23 21:31:18 +02:00
Ondrej Kozina
6e0f0408a0 reencrypt-compat-test: test log I/Os on various fs 2014-09-23 21:31:10 +02:00
Ondrej Kozina
3d6bcae84c reencrypt: use fsync instead of O_DIRECT flag
O_DIRECT operations directed towards filesystem are problematic:
There's no sane way how to detect specific filesystem requirements
for such operations.

This patch is replacing O_DIRECT flag with O_SYNC flag for all
open() calls related to reencrypt log. The O_SYNC flag is used
when --use-fsync option is detected.

Man page is modified accordingly.
2014-09-23 18:47:02 +02:00
Milan Broz
b8beedb621 Fix typo in man page. 2014-08-30 10:37:49 +02:00
Milan Broz
fd5c2a5000 Update po files. 2014-08-22 12:43:10 +02:00
Milan Broz
69bc154fca Update po files. 2014-08-18 20:49:11 +02:00
Milan Broz
387041ccf2 Set devel version. 2014-08-16 12:24:25 +02:00
367 changed files with 130047 additions and 20543 deletions

55
.gitignore vendored Normal file
View File

@@ -0,0 +1,55 @@
po/*gmo
*~
Makefile
Makefile.in
Makefile.in.in
*.lo
*.la
*.o
**/*.dirstamp
.deps/
.libs/
src/cryptsetup
src/veritysetup
ABOUT-NLS
aclocal.m4
autom4te.cache/
compile
config.guess
config.h
config.h.in
config.log
config.rpath
config.status
config.sub
configure
cryptsetup
cryptsetup-reencrypt
depcomp
install-sh
integritysetup
lib/libcryptsetup.pc
libtool
ltmain.sh
m4/
missing
po/Makevars.template
po/POTFILES
po/Rules-quot
po/*.header
po/*.sed
po/*.sin
po/stamp-po
scripts/cryptsetup.conf
stamp-h1
veritysetup
tests/valglog.*
*/*.dirstamp
*-debug-luks2-backup*
tests/api-test
tests/api-test-2
tests/differ
tests/luks1-images
tests/tcrypt-images
tests/unit-utils-io
tests/vectors-test

View File

@@ -0,0 +1,15 @@
### Issue description
<!-- Please, shortly describe the issue here. -->
### Steps for reproducing the issue
<!-- How it can be reproduced? Include all important steps. -->
### Additional info
<!-- Please mention what distribution you are using. -->
### Debug log
<!-- Paste a debug log of the failing command (add --debug option) between the markers below (to keep raw debug format).-->
```
Output with --debug option:
```

View File

@@ -0,0 +1,5 @@
### Documentation issue
<!-- Please, shortly describe the issue in documentation here. -->
### Additional info
<!-- Please mention what cryptsetup version you are using. -->

View File

@@ -0,0 +1,5 @@
### New feature description
<!-- Please, shortly describe the requested feature here. -->
### Additional info
<!-- Please mention what distribution and cryptsetup version you are using. -->

166
.travis-functions.sh Normal file
View File

@@ -0,0 +1,166 @@
#!/bin/bash
#
# .travis-functions.sh:
# - helper functions to be sourced from .travis.yml
# - designed to respect travis' environment but testing locally is possible
# - modified copy from util-linux project
#
if [ ! -f "configure.ac" ]; then
echo ".travis-functions.sh must be sourced from source dir" >&2
return 1 || exit 1
fi
## some config settings
# travis docs say we get 1.5 CPUs
MAKE="make -j2"
DUMP_CONFIG_LOG="short"
export TS_OPT_parsable="yes"
function configure_travis
{
./configure "$@"
err=$?
if [ "$DUMP_CONFIG_LOG" = "short" ]; then
grep -B1 -A10000 "^## Output variables" config.log | grep -v "_FALSE="
elif [ "$DUMP_CONFIG_LOG" = "full" ]; then
cat config.log
fi
return $err
}
function check_nonroot
{
local cfg_opts="$1"
[ -z "$cfg_opts" ] && return
configure_travis \
--enable-cryptsetup-reencrypt \
--enable-internal-sse-argon2 \
"$cfg_opts" \
|| return
$MAKE || return
make check
}
function check_root
{
local cfg_opts="$1"
[ -z "$cfg_opts" ] && return
configure_travis \
--enable-cryptsetup-reencrypt \
--enable-internal-sse-argon2 \
"$cfg_opts" \
|| return
$MAKE || return
# FIXME: we should use -E option here
sudo make check
}
function check_nonroot_compile_only
{
local cfg_opts="$1"
[ -z "$cfg_opts" ] && return
configure_travis \
--enable-cryptsetup-reencrypt \
--enable-internal-sse-argon2 \
"$cfg_opts" \
|| return
$MAKE
}
function travis_install_script
{
# install some packages from Ubuntu's default sources
sudo apt-get -qq update
sudo apt-get install -qq >/dev/null \
sharutils \
libgcrypt20-dev \
libssl-dev \
libdevmapper-dev \
libpopt-dev \
uuid-dev \
libsepol1-dev \
libtool \
dmsetup \
autoconf \
automake \
pkg-config \
autopoint \
gettext \
expect \
keyutils \
libjson-c-dev \
libblkid-dev \
dkms \
linux-headers-$(uname -r) \
linux-modules-extra-$(uname -r) \
|| return
# For VeraCrypt test
sudo apt-get install gost-crypto-dkms
}
function travis_before_script
{
set -o xtrace
./autogen.sh
ret=$?
set +o xtrace
return $ret
}
function travis_script
{
local ret
set -o xtrace
case "$MAKE_CHECK" in
gcrypt)
check_nonroot "--with-crypto_backend=gcrypt" && \
check_root "--with-crypto_backend=gcrypt"
;;
gcrypt_compile)
check_nonroot_compile_only "--with-crypto_backend=gcrypt"
;;
openssl)
check_nonroot "--with-crypto_backend=openssl" && \
check_root "--with-crypto_backend=openssl"
;;
openssl_compile)
check_nonroot_compile_only "--with-crypto_backend=openssl"
;;
kernel)
check_nonroot "--with-crypto_backend=kernel" && \
check_root "--with-crypto_backend=kernel"
;;
kernel_compile)
check_nonroot_compile_only "--with-crypto_backend=kernel"
;;
*)
echo "error, check environment (travis.yml)" >&2
false
;;
esac
ret=$?
set +o xtrace
return $ret
}
function travis_after_script
{
return 0
}

42
.travis.yml Normal file
View File

@@ -0,0 +1,42 @@
language: c
sudo: required
os: linux
dist: focal
group: edge
compiler:
- gcc
env:
# MAKE_CHECK="gcrypt"
- MAKE_CHECK="openssl"
# MAKE_CHECK="kernel"
branches:
only:
- master
- wip-luks2
- v2.3.x
before_install:
- uname -a
- $CC --version
- which $CC
# workaround clang not system wide, fail on sudo make install
- export CC=`which $CC`
# workaround travis-ci issue #5301
- unset PYTHON_CFLAGS
install:
- source ./.travis-functions.sh
- travis_install_script
before_script:
- travis_before_script
script:
- travis_script
after_script:
- travis_after_script

1111
ABOUT-NLS

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,4 @@
Jana Saout <jana@saout.de>
Clemens Fruhwirth <clemens@endorphin.org>
Milan Broz <gmazyland@gmail.com>
Ondrej Kozina <okozina@redhat.com>

View File

@@ -3,4 +3,4 @@ Since version 1.6 this file is no longer maintained.
See docs/*ReleaseNotes for release changes documentation.
See version control history for full commit messages.
http://code.google.com/p/cryptsetup/source/list
https://gitlab.com/cryptsetup/cryptsetup/commits/master

3942
FAQ

File diff suppressed because it is too large Load Diff

View File

@@ -44,7 +44,7 @@ The simplest way to compile this package is:
`sh ./configure' instead to prevent `csh' from trying to execute
`configure' itself.
Running `configure' takes awhile. While running, it prints some
Running `configure' takes a while. While running, it prints some
messages telling which features it is checking for.
2. Type `make' to compile the package.

View File

@@ -1,13 +1,50 @@
EXTRA_DIST = COPYING.LGPL FAQ docs misc
SUBDIRS = \
lib \
src \
man \
python \
tests \
po
SUBDIRS = po tests
CLEANFILES =
DISTCLEAN_TARGETS =
AM_CPPFLAGS = \
-include config.h \
-I$(top_srcdir)/lib \
-DDATADIR=\""$(datadir)"\" \
-DLOCALEDIR=\""$(datadir)/locale"\" \
-DLIBDIR=\""$(libdir)"\" \
-DPREFIX=\""$(prefix)"\" \
-DSYSCONFDIR=\""$(sysconfdir)"\" \
-DVERSION=\""$(VERSION)"\"
AM_CFLAGS = -Wall
AM_LDFLAGS =
LDADD = $(LTLIBINTL) -lm
tmpfilesddir = @DEFAULT_TMPFILESDIR@
noinst_LTLIBRARIES =
sbin_PROGRAMS =
man8_MANS =
tmpfilesd_DATA =
include man/Makemodule.am
include scripts/Makemodule.am
if CRYPTO_INTERNAL_ARGON2
include lib/crypto_backend/argon2/Makemodule.am
endif
include lib/crypto_backend/Makemodule.am
include lib/Makemodule.am
include src/Makemodule.am
ACLOCAL_AMFLAGS = -I m4
DISTCHECK_CONFIGURE_FLAGS = \
--with-tmpfilesdir=$$dc_install_base/usr/lib/tmpfiles.d \
--enable-internal-argon2 --enable-internal-sse-argon2
distclean-local:
-find . -name \*~ -o -name \*.orig -o -name \*.rej | xargs rm -f
rm -rf autom4te.cache
clean-local:
-rm -rf docs/doxygen_api_docs
-rm -rf docs/doxygen_api_docs libargon2.la

13
README
View File

@@ -5,16 +5,17 @@ setup cryptographic volumes for dm-crypt (including LUKS extension)
WEB PAGE:
http://code.google.com/p/cryptsetup/
https://gitlab.com/cryptsetup/cryptsetup/
FAQ:
http://code.google.com/p/cryptsetup/wiki/FrequentlyAskedQuestions
https://gitlab.com/cryptsetup/cryptsetup/wikis/FrequentlyAskedQuestions
MAILING LIST:
E-MAIL: dm-crypt@saout.de
URL: http://www.saout.de/mailman/listinfo/dm-crypt
URL: https://www.saout.de/mailman/listinfo/dm-crypt
ARCHIVE: https://lore.kernel.org/dm-crypt/
DOWNLOAD:
@@ -22,10 +23,10 @@ DOWNLOAD:
SOURCE CODE:
URL: http://code.google.com/p/cryptsetup/source/browse/
Checkout: git clone https://code.google.com/p/cryptsetup/
URL: https://gitlab.com/cryptsetup/cryptsetup/tree/master
Checkout: git clone https://gitlab.com/cryptsetup/cryptsetup.git
NLS (PO TRANSLATIONS):
PO files are maintained by:
http://translationproject.org/domain/cryptsetup.html
https://translationproject.org/domain/cryptsetup.html

80
README.md Normal file
View File

@@ -0,0 +1,80 @@
![LUKS logo](https://gitlab.com/cryptsetup/cryptsetup/wikis/luks-logo.png)
What the ...?
=============
**Cryptsetup** is a utility used to conveniently set up disk encryption based
on the [DMCrypt](https://gitlab.com/cryptsetup/cryptsetup/wikis/DMCrypt) kernel module.
These include **plain** **dm-crypt** volumes, **LUKS** volumes, **loop-AES**,
**TrueCrypt** (including **VeraCrypt** extension) and **BitLocker** formats.
The project also includes a **veritysetup** utility used to conveniently setup
[DMVerity](https://gitlab.com/cryptsetup/cryptsetup/wikis/DMVerity) block integrity checking kernel module
and, since version 2.0, **integritysetup** to setup
[DMIntegrity](https://gitlab.com/cryptsetup/cryptsetup/wikis/DMIntegrity) block integrity kernel module.
LUKS Design
-----------
**LUKS** is the standard for Linux hard disk encryption. By providing a standard on-disk-format, it does not
only facilitate compatibility among distributions, but also provides secure management of multiple user passwords.
LUKS stores all necessary setup information in the partition header, enabling to transport or migrate data seamlessly.
Last version of the LUKS2 format specification is
[available here](https://gitlab.com/cryptsetup/LUKS2-docs).
Last version of the LUKS1 format specification is
[available here](https://www.kernel.org/pub/linux/utils/cryptsetup/LUKS_docs/on-disk-format.pdf).
Why LUKS?
---------
* compatibility via standardization,
* secure against low entropy attacks,
* support for multiple keys,
* effective passphrase revocation,
* free.
[Project home page](https://gitlab.com/cryptsetup/cryptsetup/).
-----------------
[Frequently asked questions (FAQ)](https://gitlab.com/cryptsetup/cryptsetup/wikis/FrequentlyAskedQuestions)
--------------------------------
Download
--------
All release tarballs and release notes are hosted on [kernel.org](https://www.kernel.org/pub/linux/utils/cryptsetup/).
**The latest stable cryptsetup version is 2.4.3**
* [cryptsetup-2.4.3.tar.xz](https://www.kernel.org/pub/linux/utils/cryptsetup/v2.4/cryptsetup-2.4.3.tar.xz)
* Signature [cryptsetup-2.4.3.tar.sign](https://www.kernel.org/pub/linux/utils/cryptsetup/v2.4/cryptsetup-2.4.3.tar.sign)
_(You need to decompress file first to check signature.)_
* [Cryptsetup 2.4.3 Release Notes](https://www.kernel.org/pub/linux/utils/cryptsetup/v2.4/v2.4.3-ReleaseNotes).
Previous versions
* [Version 2.3.7](https://www.kernel.org/pub/linux/utils/cryptsetup/v2.3/cryptsetup-2.3.7.tar.xz) -
[Signature](https://www.kernel.org/pub/linux/utils/cryptsetup/v2.3/cryptsetup-2.3.7.tar.sign) -
[Release Notes](https://www.kernel.org/pub/linux/utils/cryptsetup/v2.3/v2.3.7-ReleaseNotes).
* [Version 1.7.5](https://www.kernel.org/pub/linux/utils/cryptsetup/v1.7/cryptsetup-1.7.5.tar.xz) -
[Signature](https://www.kernel.org/pub/linux/utils/cryptsetup/v1.7/cryptsetup-1.7.5.tar.sign) -
[Release Notes](https://www.kernel.org/pub/linux/utils/cryptsetup/v1.7/v1.7.5-ReleaseNotes).
Source and API docs
-------------------
For development version code, please refer to [source](https://gitlab.com/cryptsetup/cryptsetup/tree/master) page,
mirror on [kernel.org](https://git.kernel.org/cgit/utils/cryptsetup/cryptsetup.git/) or [GitHub](https://github.com/mbroz/cryptsetup).
For libcryptsetup documentation see [libcryptsetup API](https://mbroz.fedorapeople.org/libcryptsetup_API/) page.
The libcryptsetup API/ABI changes are tracked in [compatibility report](https://abi-laboratory.pro/tracker/timeline/cryptsetup/).
NLS PO files are maintained by [TranslationProject](https://translationproject.org/domain/cryptsetup.html).
Help!
-----
Please always read [FAQ](https://gitlab.com/cryptsetup/cryptsetup/wikis/FrequentlyAskedQuestions) first.
For cryptsetup and LUKS related questions, please use the dm-crypt mailing list, [dm-crypt@saout.de](mailto:dm-crypt@saout.de).
If you want to subscribe just send an empty mail to [dm-crypt-subscribe@saout.de](mailto:dm-crypt-subscribe@saout.de).
You can also browse [list archive](https://www.saout.de/pipermail/dm-crypt/) or read and search it through
[web interface on lore.kernel.org](https://lore.kernel.org/dm-crypt/) or alternatively on [marc.info](https://marc.info/?l=dm-crypt).

9
TODO
View File

@@ -1,8 +1 @@
Version 1.7:
- Export wipe device functions
- Support K/M suffixes for align payload (new switch?).
- TRIM for keyslots
- Do we need crypt_data_path() - path to data device (if differs)?
- Resync ETA time is not accurate, calculate it better (last minute window?).
- Extend existing LUKS header to use another KDF? (https://password-hashing.net/)
- Fix all crazy automake warnings (or switch to Cmake).
Please see issues tracked at https://gitlab.com/cryptsetup/cryptsetup/issues.

View File

@@ -9,16 +9,23 @@ DIE=0
(autopoint --version) < /dev/null > /dev/null 2>&1 || {
echo
echo "**Error**: You must have autopoint installed."
echo "Download the appropriate package for your distribution,"
echo "or see http://www.gnu.org/software/gettext"
echo "Download the appropriate package for your distribution."
DIE=1
}
(msgfmt --version) < /dev/null > /dev/null 2>&1 || {
echo
echo "**Warning**: You should have gettext installed."
echo "Download the appropriate package for your distribution."
echo "To disable translation, you can also use --disable-nls"
echo "configure option."
}
(autoconf --version) < /dev/null > /dev/null 2>&1 || {
echo
echo "**Error**: You must have autoconf installed to."
echo "Download the appropriate package for your distribution,"
echo "or get the source tarball at ftp://ftp.gnu.org/pub/gnu/"
echo "**Error**: You must have autoconf installed."
echo "Download the appropriate package for your distribution."
DIE=1
}
@@ -26,8 +33,7 @@ DIE=0
(libtool --version) < /dev/null > /dev/null 2>&1 || {
echo
echo "**Error**: You must have libtool installed."
echo "Get ftp://ftp.gnu.org/pub/gnu/"
echo "(or a newer version if it is available)"
echo "Download the appropriate package for your distribution."
DIE=1
}
}
@@ -35,8 +41,7 @@ DIE=0
(automake --version) < /dev/null > /dev/null 2>&1 || {
echo
echo "**Error**: You must have automake installed."
echo "Get ftp://ftp.gnu.org/pub/gnu/"
echo "(or a newer version if it is available)"
echo "Download the appropriate package for your distribution."
DIE=1
NO_AUTOMAKE=yes
}
@@ -47,8 +52,6 @@ test -n "$NO_AUTOMAKE" || (aclocal --version) < /dev/null > /dev/null 2>&1 || {
echo
echo "**Error**: Missing aclocal. The version of automake"
echo "installed doesn't appear recent enough."
echo "Get ftp://ftp.gnu.org/pub/gnu/"
echo "(or a newer version if it is available)"
DIE=1
}
@@ -56,13 +59,6 @@ if test "$DIE" -eq 1; then
exit 1
fi
if test -z "$*"; then
echo
echo "**Warning**: I am going to run 'configure' with no arguments."
echo "If you wish to pass any to it, please specify them on the"
echo \'$0\'" command line."
fi
echo
echo "Generate build-system by:"
echo " autopoint: $(autopoint --version | head -1)"
@@ -81,10 +77,6 @@ autoheader $AH_OPTS
automake --add-missing --copy --gnu $AM_OPTS
autoconf $AC_OPTS
if test x$NOCONFIGURE = x; then
echo Running $srcdir/configure $conf_flags "$@" ...
$srcdir/configure $conf_flags "$@" \
&& echo Now type \`make\' to compile $PKG_NAME
else
echo Skipping configure process.
fi
echo
echo "Now type '$srcdir/configure' and 'make' to compile."
echo

View File

@@ -1,13 +1,11 @@
AC_PREREQ([2.67])
AC_INIT([cryptsetup],[1.6.6])
AC_INIT([cryptsetup],[2.3.7])
dnl library version from <major>.<minor>.<release>[-<suffix>]
LIBCRYPTSETUP_VERSION=$(echo $PACKAGE_VERSION | cut -f1 -d-)
LIBCRYPTSETUP_VERSION_INFO=10:0:6
dnl library file name for FIPS selfcheck
LIBCRYPTSETUP_VERSION_FIPS="libcryptsetup.so.4"
FIPS_MODULE_FILE="/etc/system-fips"
LIBCRYPTSETUP_VERSION_INFO=18:0:6
AM_SILENT_RULES([yes])
AC_CONFIG_SRCDIR(src/cryptsetup.c)
AC_CONFIG_MACRO_DIR([m4])
@@ -17,8 +15,8 @@ AC_CONFIG_HEADERS([config.h:config.h.in])
# http://lists.gnu.org/archive/html/automake/2013-01/msg00060.html
# For old automake use this
#AM_INIT_AUTOMAKE(dist-xz)
AM_INIT_AUTOMAKE([dist-xz 1.12 serial-tests])
#AM_INIT_AUTOMAKE(dist-xz subdir-objects)
AM_INIT_AUTOMAKE([dist-xz 1.12 serial-tests subdir-objects])
if test "x$prefix" = "xNONE"; then
sysconfdir=/etc
@@ -35,24 +33,76 @@ AC_PROG_MAKE_SET
AC_ENABLE_STATIC(no)
LT_INIT
PKG_PROG_PKG_CONFIG
AM_ICONV
dnl ==========================================================================
dnl define PKG_CHECK_VAR for old pkg-config <= 0.28
m4_ifndef([AS_VAR_COPY],
[m4_define([AS_VAR_COPY],
[AS_LITERAL_IF([$1[]$2], [$1=$$2], [eval $1=\$$2])])
])
m4_ifndef([PKG_CHECK_VAR], [
AC_DEFUN([PKG_CHECK_VAR],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])
AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])
_PKG_CONFIG([$1], [variable="][$3]["], [$2])
AS_VAR_COPY([$1], [pkg_cv_][$1])
AS_VAR_IF([$1], [""], [$5], [$4])
])
])
dnl ==========================================================================
AC_C_RESTRICT
AC_HEADER_DIRENT
AC_HEADER_STDC
AC_CHECK_HEADERS(fcntl.h malloc.h inttypes.h sys/ioctl.h sys/mman.h \
ctype.h unistd.h locale.h byteswap.h endian.h)
sys/sysmacros.h sys/statvfs.h ctype.h unistd.h locale.h byteswap.h endian.h stdint.h)
AC_CHECK_DECLS([O_CLOEXEC],,[AC_DEFINE([O_CLOEXEC],[0], [Defined to 0 if not provided])],
[[
#ifdef HAVE_FCNTL_H
# include <fcntl.h>
#endif
]])
AC_CHECK_HEADERS(uuid/uuid.h,,[AC_MSG_ERROR([You need the uuid library.])])
AC_CHECK_HEADER(libdevmapper.h,,[AC_MSG_ERROR([You need the device-mapper library.])])
AC_ARG_ENABLE([keyring],
AS_HELP_STRING([--disable-keyring], [disable kernel keyring support and builtin kernel keyring token]),
[], [enable_keyring=yes])
if test "x$enable_keyring" = "xyes"; then
AC_CHECK_HEADERS(linux/keyctl.h,,[AC_MSG_ERROR([You need Linux kernel headers with kernel keyring service compiled.])])
dnl ==========================================================================
dnl check whether kernel is compiled with kernel keyring service syscalls
AC_CHECK_DECL(__NR_add_key,,[AC_MSG_ERROR([The kernel is missing add_key syscall.])], [#include <syscall.h>])
AC_CHECK_DECL(__NR_keyctl,,[AC_MSG_ERROR([The kernel is missing keyctl syscall.])], [#include <syscall.h>])
AC_CHECK_DECL(__NR_request_key,,[AC_MSG_ERROR([The kernel is missing request_key syscall.])], [#include <syscall.h>])
dnl ==========================================================================
dnl check that key_serial_t hasn't been adopted yet in stdlib
AC_CHECK_TYPES([key_serial_t], [], [], [
AC_INCLUDES_DEFAULT
#ifdef HAVE_LINUX_KEYCTL_H
# include <linux/keyctl.h>
#endif
])
AC_DEFINE(KERNEL_KEYRING, 1, [Enable kernel keyring service support])
fi
AM_CONDITIONAL(KERNEL_KEYRING, test "x$enable_keyring" = "xyes")
saved_LIBS=$LIBS
AC_CHECK_LIB(uuid, uuid_clear, ,[AC_MSG_ERROR([You need the uuid library.])])
AC_SUBST(UUID_LIBS, $LIBS)
LIBS=$saved_LIBS
AC_SEARCH_LIBS([clock_gettime],[rt posix4])
AC_CHECK_FUNCS([posix_memalign clock_gettime])
AC_CHECK_FUNCS([posix_memalign clock_gettime posix_fallocate explicit_bzero])
if test "x$enable_largefile" = "xno" ; then
if test "x$enable_largefile" = "xno"; then
AC_MSG_ERROR([Building with --disable-largefile is not supported, it can cause data corruption.])
fi
@@ -62,11 +112,12 @@ AC_TYPE_OFF_T
AC_SYS_LARGEFILE
AC_FUNC_FSEEKO
AC_PROG_GCC_TRADITIONAL
AC_FUNC_STRERROR_R
dnl ==========================================================================
AM_GNU_GETTEXT([external],[need-ngettext])
AM_GNU_GETTEXT_VERSION([0.15])
AM_GNU_GETTEXT_VERSION([0.18.3])
dnl ==========================================================================
@@ -78,42 +129,37 @@ LIBS=$saved_LIBS
dnl ==========================================================================
dnl FIPS extensions
AC_ARG_ENABLE([fips], AS_HELP_STRING([--enable-fips],[enable FIPS mode restrictions]),
[with_fips=$enableval],
[with_fips=no])
if test "x$with_fips" = "xyes"; then
AC_ARG_ENABLE([fips],
AS_HELP_STRING([--enable-fips], [enable FIPS mode restrictions]))
if test "x$enable_fips" = "xyes"; then
AC_DEFINE(ENABLE_FIPS, 1, [Enable FIPS mode restrictions])
AC_DEFINE_UNQUOTED(LIBCRYPTSETUP_VERSION_FIPS, ["$LIBCRYPTSETUP_VERSION_FIPS"],
[library file name for FIPS selfcheck])
AC_DEFINE_UNQUOTED(FIPS_MODULE_FILE, ["$FIPS_MODULE_FILE"],
[file checked to determine if running in FIPS mode])
if test "x$enable_static" = "xyes" -o "x$enable_static_cryptsetup" = "xyes" ; then
AC_MSG_ERROR([Static build is not compatible with FIPS.])
fi
saved_LIBS=$LIBS
AC_CHECK_LIB(fipscheck, FIPSCHECK_verify, ,[AC_MSG_ERROR([You need the fipscheck library.])])
AC_SUBST(FIPSCHECK_LIBS, $LIBS)
LIBS=$saved_LIBS
fi
AC_DEFUN([NO_FIPS], [
if test "x$with_fips" = "xyes"; then
if test "x$enable_fips" = "xyes"; then
AC_MSG_ERROR([This option is not compatible with FIPS.])
fi
])
dnl LUKS2 online reencryption
AC_ARG_ENABLE([luks2-reencryption],
AS_HELP_STRING([--disable-luks2-reencryption], [disable LUKS2 online reencryption extension]),
[], [enable_luks2_reencryption=yes])
if test "x$enable_luks2_reencryption" = "xyes"; then
AC_DEFINE(USE_LUKS2_REENCRYPTION, 1, [Use LUKS2 online reencryption extension])
fi
dnl ==========================================================================
dnl pwquality library (cryptsetup CLI only)
AC_ARG_ENABLE([pwquality], AS_HELP_STRING([--enable-pwquality],[enable password quality checking]),
[with_pwquality=$enableval],
[with_pwquality=no])
AC_ARG_ENABLE([pwquality],
AS_HELP_STRING([--enable-pwquality], [enable password quality checking using pwquality library]))
if test "x$with_pwquality" = "xyes"; then
AC_DEFINE(ENABLE_PWQUALITY, 1, [Enable password quality checking])
if test "x$enable_pwquality" = "xyes"; then
AC_DEFINE(ENABLE_PWQUALITY, 1, [Enable password quality checking using pwquality library])
PKG_CHECK_MODULES([PWQUALITY], [pwquality >= 1.0.0],,
AC_MSG_ERROR([You need pwquality library.]))
@@ -121,26 +167,73 @@ if test "x$with_pwquality" = "xyes"; then
PWQUALITY_STATIC_LIBS="$PWQUALITY_LIBS -lcrack -lz"
fi
dnl ==========================================================================
dnl passwdqc library (cryptsetup CLI only)
AC_ARG_ENABLE([passwdqc],
AS_HELP_STRING([--enable-passwdqc@<:@=CONFIG_PATH@:>@],
[enable password quality checking using passwdqc library (optionally with CONFIG_PATH)]))
case "$enable_passwdqc" in
""|yes|no) use_passwdqc_config="" ;;
/*) use_passwdqc_config="$enable_passwdqc"; enable_passwdqc=yes ;;
*) AC_MSG_ERROR([Unrecognized --enable-passwdqc parameter.]) ;;
esac
AC_DEFINE_UNQUOTED([PASSWDQC_CONFIG_FILE], ["$use_passwdqc_config"], [passwdqc library config file])
if test "x$enable_passwdqc" = "xyes"; then
AC_DEFINE(ENABLE_PASSWDQC, 1, [Enable password quality checking using passwdqc library])
saved_LIBS="$LIBS"
AC_SEARCH_LIBS([passwdqc_check], [passwdqc])
case "$ac_cv_search_passwdqc_check" in
no) AC_MSG_ERROR([failed to find passwdqc_check]) ;;
-l*) PASSWDQC_LIBS="$ac_cv_search_passwdqc_check" ;;
*) PASSWDQC_LIBS= ;;
esac
AC_CHECK_FUNCS([passwdqc_params_free])
LIBS="$saved_LIBS"
fi
if test "x$enable_pwquality$enable_passwdqc" = "xyesyes"; then
AC_MSG_ERROR([--enable-pwquality and --enable-passwdqc are mutually incompatible.])
fi
dnl ==========================================================================
dnl Crypto backend functions
AC_DEFUN([CONFIGURE_GCRYPT], [
if test "x$with_fips" = "xyes"; then
if test "x$enable_fips" = "xyes"; then
GCRYPT_REQ_VERSION=1.4.5
else
GCRYPT_REQ_VERSION=1.1.42
fi
dnl Check if we can use gcrypt PBKDF2 (1.6.0 supports empty password)
AC_ARG_ENABLE([gcrypt-pbkdf2], AS_HELP_STRING([--enable-gcrypt-pbkdf2],[force enable internal gcrypt PBKDF2]),
dnl libgcrypt rejects to use pkgconfig, use AM_PATH_LIBGCRYPT from gcrypt-devel here.
dnl Do not require gcrypt-devel if other crypto backend is used.
m4_ifdef([AM_PATH_LIBGCRYPT],[
AC_ARG_ENABLE([gcrypt-pbkdf2],
dnl Check if we can use gcrypt PBKDF2 (1.6.0 supports empty password)
AS_HELP_STRING([--enable-gcrypt-pbkdf2], [force enable internal gcrypt PBKDF2]),
if test "x$enableval" = "xyes"; then
[use_internal_pbkdf2=0]
else
[use_internal_pbkdf2=1]
fi,
[AM_PATH_LIBGCRYPT([1.6.1], [use_internal_pbkdf2=0], [use_internal_pbkdf2=1])])
AM_PATH_LIBGCRYPT($GCRYPT_REQ_VERSION,,[AC_MSG_ERROR([You need the gcrypt library.])])
AM_PATH_LIBGCRYPT($GCRYPT_REQ_VERSION,,[AC_MSG_ERROR([You need the gcrypt library.])])],
AC_MSG_ERROR([Missing support for gcrypt: install gcrypt and regenerate configure.]))
if test x$enable_static_cryptsetup = xyes; then
AC_MSG_CHECKING([if internal cryptsetup PBKDF2 is compiled-in])
if test $use_internal_pbkdf2 = 0; then
AC_MSG_RESULT([no])
else
AC_MSG_RESULT([yes])
NO_FIPS([])
fi
AC_CHECK_DECLS([GCRY_CIPHER_MODE_XTS], [], [], [#include <gcrypt.h>])
if test "x$enable_static_cryptsetup" = "xyes"; then
saved_LIBS=$LIBS
LIBS="$saved_LIBS $LIBGCRYPT_LIBS -static"
AC_CHECK_LIB(gcrypt, gcry_check_version,,
@@ -164,18 +257,17 @@ AC_DEFUN([CONFIGURE_OPENSSL], [
CRYPTO_LIBS=$OPENSSL_LIBS
use_internal_pbkdf2=0
if test x$enable_static_cryptsetup = xyes; then
if test "x$enable_static_cryptsetup" = "xyes"; then
saved_PKG_CONFIG=$PKG_CONFIG
PKG_CONFIG="$PKG_CONFIG --static"
PKG_CHECK_MODULES([OPENSSL_STATIC], [openssl])
CRYPTO_STATIC_LIBS=$OPENSSL_STATIC_LIBS
PKG_CONFIG=$saved_PKG_CONFIG
fi
NO_FIPS([])
])
AC_DEFUN([CONFIGURE_NSS], [
if test x$enable_static_cryptsetup = xyes; then
if test "x$enable_static_cryptsetup" = "xyes"; then
AC_MSG_ERROR([Static build of cryptsetup is not supported with NSS.])
fi
@@ -208,6 +300,7 @@ AC_DEFUN([CONFIGURE_KERNEL], [
AC_DEFUN([CONFIGURE_NETTLE], [
AC_CHECK_HEADERS(nettle/sha.h,,
[AC_MSG_ERROR([You need Nettle cryptographic library.])])
AC_CHECK_HEADERS(nettle/version.h)
saved_LIBS=$LIBS
AC_CHECK_LIB(nettle, nettle_pbkdf2_hmac_sha256,,
@@ -224,33 +317,42 @@ dnl ==========================================================================
saved_LIBS=$LIBS
AC_ARG_ENABLE([static-cryptsetup],
AS_HELP_STRING([--enable-static-cryptsetup],
[enable build of static cryptsetup binary]))
if test x$enable_static_cryptsetup = xyes; then
if test x$enable_static = xno; then
AS_HELP_STRING([--enable-static-cryptsetup], [enable build of static version of tools]))
if test "x$enable_static_cryptsetup" = "xyes"; then
if test "x$enable_static" = "xno"; then
AC_MSG_WARN([Requested static cryptsetup build, enabling static library.])
enable_static=yes
fi
fi
AM_CONDITIONAL(STATIC_TOOLS, test x$enable_static_cryptsetup = xyes)
AM_CONDITIONAL(STATIC_TOOLS, test "x$enable_static_cryptsetup" = "xyes")
AC_ARG_ENABLE(veritysetup,
AS_HELP_STRING([--disable-veritysetup],
[disable veritysetup support]),[], [enable_veritysetup=yes])
AM_CONDITIONAL(VERITYSETUP, test x$enable_veritysetup = xyes)
AC_ARG_ENABLE([cryptsetup],
AS_HELP_STRING([--disable-cryptsetup], [disable cryptsetup support]),
[], [enable_cryptsetup=yes])
AM_CONDITIONAL(CRYPTSETUP, test "x$enable_cryptsetup" = "xyes")
AC_ARG_ENABLE([veritysetup],
AS_HELP_STRING([--disable-veritysetup], [disable veritysetup support]),
[], [enable_veritysetup=yes])
AM_CONDITIONAL(VERITYSETUP, test "x$enable_veritysetup" = "xyes")
AC_ARG_ENABLE([cryptsetup-reencrypt],
AS_HELP_STRING([--enable-cryptsetup-reencrypt],
[enable cryptsetup-reencrypt tool]))
AM_CONDITIONAL(REENCRYPT, test x$enable_cryptsetup_reencrypt = xyes)
AS_HELP_STRING([--disable-cryptsetup-reencrypt], [disable cryptsetup-reencrypt tool]),
[], [enable_cryptsetup_reencrypt=yes])
AM_CONDITIONAL(REENCRYPT, test "x$enable_cryptsetup_reencrypt" = "xyes")
AC_ARG_ENABLE(selinux,
AS_HELP_STRING([--disable-selinux],
[disable selinux support [default=auto]]),[], [])
AC_ARG_ENABLE([integritysetup],
AS_HELP_STRING([--disable-integritysetup], [disable integritysetup support]),
[], [enable_integritysetup=yes])
AM_CONDITIONAL(INTEGRITYSETUP, test "x$enable_integritysetup" = "xyes")
AC_ARG_ENABLE([selinux],
AS_HELP_STRING([--disable-selinux], [disable selinux support [default=auto]]),
[], [enable_selinux=yes])
AC_ARG_ENABLE([udev],
AS_HELP_STRING([--disable-udev],
[disable udev support]),[], enable_udev=yes)
AS_HELP_STRING([--disable-udev], [disable udev support]),
[], [enable_udev=yes])
dnl Try to use pkg-config for devmapper, but fallback to old detection
PKG_CHECK_MODULES([DEVMAPPER], [devmapper >= 1.02.03],, [
@@ -265,6 +367,11 @@ LIBS=$saved_LIBS
LIBS="$LIBS $DEVMAPPER_LIBS"
AC_CHECK_DECLS([dm_task_secure_data], [], [], [#include <libdevmapper.h>])
AC_CHECK_DECLS([dm_task_retry_remove], [], [], [#include <libdevmapper.h>])
AC_CHECK_DECLS([dm_task_deferred_remove], [], [], [#include <libdevmapper.h>])
AC_CHECK_DECLS([dm_device_has_mounted_fs], [], [], [#include <libdevmapper.h>])
AC_CHECK_DECLS([dm_device_has_holders], [], [], [#include <libdevmapper.h>])
AC_CHECK_DECLS([dm_device_get_name], [], [], [#include <libdevmapper.h>])
AC_CHECK_DECLS([DM_DEVICE_GET_TARGET_VERSION], [], [], [#include <libdevmapper.h>])
AC_CHECK_DECLS([DM_UDEV_DISABLE_DISK_RULES_FLAG], [have_cookie=yes], [have_cookie=no], [#include <libdevmapper.h>])
if test "x$enable_udev" = xyes; then
if test "x$have_cookie" = xno; then
@@ -275,19 +382,22 @@ if test "x$enable_udev" = xyes; then
fi
LIBS=$saved_LIBS
dnl Check for JSON-C used in LUKS2
PKG_CHECK_MODULES([JSON_C], [json-c])
AC_CHECK_DECLS([json_object_object_add_ex], [], [], [#include <json-c/json.h>])
AC_CHECK_DECLS([json_object_deep_copy], [], [], [#include <json-c/json.h>])
dnl Crypto backend configuration.
AC_ARG_WITH([crypto_backend],
AS_HELP_STRING([--with-crypto_backend=BACKEND], [crypto backend (gcrypt/openssl/nss/kernel/nettle) [gcrypt]]),
[], with_crypto_backend=gcrypt
)
AS_HELP_STRING([--with-crypto_backend=BACKEND], [crypto backend (gcrypt/openssl/nss/kernel/nettle) [openssl]]),
[], [with_crypto_backend=openssl])
dnl Kernel crypto API backend needed for benchmark and tcrypt
AC_ARG_ENABLE([kernel_crypto], AS_HELP_STRING([--disable-kernel_crypto],
[disable kernel userspace crypto (no benchmark and tcrypt)]),
[with_kernel_crypto=$enableval],
[with_kernel_crypto=yes])
AC_ARG_ENABLE([kernel_crypto],
AS_HELP_STRING([--disable-kernel_crypto], [disable kernel userspace crypto (no benchmark and tcrypt)]),
[], [enable_kernel_crypto=yes])
if test "x$with_kernel_crypto" = "xyes"; then
if test "x$enable_kernel_crypto" = "xyes"; then
AC_CHECK_HEADERS(linux/if_alg.h,,
[AC_MSG_ERROR([You need Linux kernel headers with userspace crypto interface. (Or use --disable-kernel_crypto.)])])
AC_DEFINE(ENABLE_AF_ALG, 1, [Enable using of kernel userspace crypto])
@@ -301,17 +411,88 @@ case $with_crypto_backend in
nettle) CONFIGURE_NETTLE([]) ;;
*) AC_MSG_ERROR([Unknown crypto backend.]) ;;
esac
AM_CONDITIONAL(CRYPTO_BACKEND_GCRYPT, test $with_crypto_backend = gcrypt)
AM_CONDITIONAL(CRYPTO_BACKEND_OPENSSL, test $with_crypto_backend = openssl)
AM_CONDITIONAL(CRYPTO_BACKEND_NSS, test $with_crypto_backend = nss)
AM_CONDITIONAL(CRYPTO_BACKEND_KERNEL, test $with_crypto_backend = kernel)
AM_CONDITIONAL(CRYPTO_BACKEND_NETTLE, test $with_crypto_backend = nettle)
AM_CONDITIONAL(CRYPTO_BACKEND_GCRYPT, test "$with_crypto_backend" = "gcrypt")
AM_CONDITIONAL(CRYPTO_BACKEND_OPENSSL, test "$with_crypto_backend" = "openssl")
AM_CONDITIONAL(CRYPTO_BACKEND_NSS, test "$with_crypto_backend" = "nss")
AM_CONDITIONAL(CRYPTO_BACKEND_KERNEL, test "$with_crypto_backend" = "kernel")
AM_CONDITIONAL(CRYPTO_BACKEND_NETTLE, test "$with_crypto_backend" = "nettle")
AM_CONDITIONAL(CRYPTO_INTERNAL_PBKDF2, test $use_internal_pbkdf2 = 1)
AC_DEFINE_UNQUOTED(USE_INTERNAL_PBKDF2, [$use_internal_pbkdf2], [Use internal PBKDF2])
dnl Argon2 implementation
AC_ARG_ENABLE([internal-argon2],
AS_HELP_STRING([--disable-internal-argon2], [disable internal implementation of Argon2 PBKDF]),
[], [enable_internal_argon2=yes])
AC_ARG_ENABLE([libargon2],
AS_HELP_STRING([--enable-libargon2], [enable external libargon2 (PHC) library (disables internal bundled version)]))
if test "x$enable_libargon2" = "xyes" ; then
AC_CHECK_HEADERS(argon2.h,,
[AC_MSG_ERROR([You need libargon2 development library installed.])])
AC_CHECK_DECL(Argon2_id,,[AC_MSG_ERROR([You need more recent Argon2 library with support for Argon2id.])], [#include <argon2.h>])
PKG_CHECK_MODULES([LIBARGON2], [libargon2],,[LIBARGON2_LIBS="-largon2"])
enable_internal_argon2=no
else
AC_MSG_WARN([Argon2 bundled (slow) reference implementation will be used, please consider to use system library with --enable-libargon2.])
AC_ARG_ENABLE([internal-sse-argon2],
AS_HELP_STRING([--enable-internal-sse-argon2], [enable internal SSE implementation of Argon2 PBKDF]))
if test "x$enable_internal_sse_argon2" = "xyes"; then
AC_MSG_CHECKING(if Argon2 SSE optimization can be used)
AC_LINK_IFELSE([AC_LANG_PROGRAM([[
#include <emmintrin.h>
__m128i testfunc(__m128i *a, __m128i *b) {
return _mm_xor_si128(_mm_loadu_si128(a), _mm_loadu_si128(b));
}
]])],,[enable_internal_sse_argon2=no])
AC_MSG_RESULT($enable_internal_sse_argon2)
fi
fi
if test "x$enable_internal_argon2" = "xyes"; then
AC_DEFINE(USE_INTERNAL_ARGON2, 1, [Use internal Argon2])
fi
AM_CONDITIONAL(CRYPTO_INTERNAL_ARGON2, test "x$enable_internal_argon2" = "xyes")
AM_CONDITIONAL(CRYPTO_INTERNAL_SSE_ARGON2, test "x$enable_internal_sse_argon2" = "xyes")
dnl Link with blkid to check for other device types
AC_ARG_ENABLE([blkid],
AS_HELP_STRING([--disable-blkid], [disable use of blkid for device signature detection and wiping]),
[], [enable_blkid=yes])
if test "x$enable_blkid" = "xyes"; then
PKG_CHECK_MODULES([BLKID], [blkid],[AC_DEFINE([HAVE_BLKID], 1, [Define to 1 to use blkid for detection of disk signatures.])],[LIBBLKID_LIBS="-lblkid"])
AC_CHECK_HEADERS(blkid/blkid.h,,[AC_MSG_ERROR([You need blkid development library installed.])])
AC_CHECK_DECL([blkid_do_wipe],
[ AC_DEFINE([HAVE_BLKID_WIPE], 1, [Define to 1 to use blkid_do_wipe.])
enable_blkid_wipe=yes
],,
[#include <blkid/blkid.h>])
AC_CHECK_DECL([blkid_probe_step_back],
[ AC_DEFINE([HAVE_BLKID_STEP_BACK], 1, [Define to 1 to use blkid_probe_step_back.])
enable_blkid_step_back=yes
],,
[#include <blkid/blkid.h>])
AC_CHECK_DECLS([ blkid_reset_probe,
blkid_probe_set_device,
blkid_probe_filter_superblocks_type,
blkid_do_safeprobe,
blkid_do_probe,
blkid_probe_lookup_value
],,
[AC_MSG_ERROR([Can not compile with blkid support, disable it by --disable-blkid.])],
[#include <blkid/blkid.h>])
fi
AM_CONDITIONAL(HAVE_BLKID, test "x$enable_blkid" = "xyes")
AM_CONDITIONAL(HAVE_BLKID_WIPE, test "x$enable_blkid_wipe" = "xyes")
AM_CONDITIONAL(HAVE_BLKID_STEP_BACK, test "x$enable_blkid_step_back" = "xyes")
dnl Magic for cryptsetup.static build.
if test x$enable_static_cryptsetup = xyes; then
if test "x$enable_static_cryptsetup" = "xyes"; then
saved_PKG_CONFIG=$PKG_CONFIG
PKG_CONFIG="$PKG_CONFIG --static"
@@ -323,7 +504,7 @@ if test x$enable_static_cryptsetup = xyes; then
LIBS="$saved_LIBS -static"
PKG_CHECK_MODULES([DEVMAPPER_STATIC], [devmapper >= 1.02.27],,[
DEVMAPPER_STATIC_LIBS=$DEVMAPPER_LIBS
if test "x$enable_selinux" != xno; then
if test "x$enable_selinux" = "xyes"; then
AC_CHECK_LIB(sepol, sepol_bool_set)
AC_CHECK_LIB(selinux, is_selinux_enabled)
DEVMAPPER_STATIC_LIBS="$DEVMAPPER_STATIC_LIBS $LIBS"
@@ -342,25 +523,37 @@ if test x$enable_static_cryptsetup = xyes; then
PKG_CONFIG=$saved_PKG_CONFIG
fi
AC_MSG_CHECKING([for systemd tmpfiles config directory])
PKG_CHECK_VAR([systemd_tmpfilesdir], [systemd], [tmpfilesdir], [], [systemd_tmpfilesdir=no])
AC_MSG_RESULT([$systemd_tmpfilesdir])
AC_SUBST([DEVMAPPER_LIBS])
AC_SUBST([DEVMAPPER_STATIC_LIBS])
AC_SUBST([PWQUALITY_LIBS])
AC_SUBST([PWQUALITY_STATIC_LIBS])
AC_SUBST([PASSWDQC_LIBS])
AC_SUBST([CRYPTO_CFLAGS])
AC_SUBST([CRYPTO_LIBS])
AC_SUBST([CRYPTO_STATIC_LIBS])
AC_SUBST([JSON_C_LIBS])
AC_SUBST([LIBARGON2_LIBS])
AC_SUBST([BLKID_LIBS])
AC_SUBST([LIBCRYPTSETUP_VERSION])
AC_SUBST([LIBCRYPTSETUP_VERSION_INFO])
AC_SUBST([LIBCRYPTSETUP_VERSION_FIPS])
AC_SUBST([FIPS_MODULE_FILE])
dnl ==========================================================================
AC_ARG_ENABLE([dev-random], AS_HELP_STRING([--enable-dev-random],
[use blocking /dev/random by default for key generator (otherwise use /dev/urandom)]),
[default_rng=/dev/random], [default_rng=/dev/urandom])
AC_ARG_ENABLE([dev-random],
AS_HELP_STRING([--enable-dev-random], [use /dev/random by default for key generation (otherwise use /dev/urandom)]))
if test "x$enable_dev_random" = "xyes"; then
default_rng=/dev/random
else
default_rng=/dev/urandom
fi
AC_DEFINE_UNQUOTED(DEFAULT_RNG, ["$default_rng"], [default RNG type for key generator])
dnl ==========================================================================
@@ -380,30 +573,12 @@ AC_DEFUN([CS_NUM_WITH], [AC_ARG_WITH([$1],
[CS_DEFINE([$1], [$3], [$2])]
)])
dnl ==========================================================================
dnl Python bindings
AC_ARG_ENABLE([python], AS_HELP_STRING([--enable-python],[enable Python bindings]),
[with_python=$enableval],
[with_python=no])
AC_ARG_WITH([python_version],
AS_HELP_STRING([--with-python_version=VERSION], [required Python version [2.6]]),
[PYTHON_VERSION=$withval], [PYTHON_VERSION=2.6])
if test "x$with_python" = "xyes"; then
AM_PATH_PYTHON([$PYTHON_VERSION])
if ! test -x "$PYTHON-config" ; then
AC_MSG_ERROR([Cannot find python development packages to build bindings])
fi
PYTHON_INCLUDES=$($PYTHON-config --includes)
AC_SUBST(PYTHON_INCLUDES)
PYTHON_LIBS=$($PYTHON-config --libs)
AC_SUBST(PYTHON_LIBS)
fi
AM_CONDITIONAL([PYTHON_CRYPTSETUP], [test "x$with_python" = "xyes"])
AC_DEFUN([CS_ABSPATH], [
case "$1" in
/*) ;;
*) AC_MSG_ERROR([$2 argument must be an absolute path.]);;
esac
])
dnl ==========================================================================
CS_STR_WITH([plain-hash], [password hashing function for plain mode], [ripemd160])
@@ -411,37 +586,78 @@ CS_STR_WITH([plain-cipher], [cipher for plain mode], [aes])
CS_STR_WITH([plain-mode], [cipher mode for plain mode], [cbc-essiv:sha256])
CS_NUM_WITH([plain-keybits],[key length in bits for plain mode], [256])
CS_STR_WITH([luks1-hash], [hash function for LUKS1 header], [sha1])
CS_STR_WITH([luks1-hash], [hash function for LUKS1 header], [sha256])
CS_STR_WITH([luks1-cipher], [cipher for LUKS1], [aes])
CS_STR_WITH([luks1-mode], [cipher mode for LUKS1], [xts-plain64])
CS_NUM_WITH([luks1-keybits],[key length in bits for LUKS1], [256])
CS_NUM_WITH([luks1-iter-time],[PBKDF2 iteration time for LUKS1 (in ms)], [1000])
AC_ARG_ENABLE([luks_adjust_xts_keysize], AS_HELP_STRING([--disable-luks-adjust-xts-keysize],
[XTS mode requires two keys, double default LUKS keysize if needed]),
[], [enable_luks_adjust_xts_keysize=yes])
if test "x$enable_luks_adjust_xts_keysize" = "xyes"; then
AC_DEFINE(ENABLE_LUKS_ADJUST_XTS_KEYSIZE, 1, [XTS mode - double default LUKS keysize if needed])
fi
CS_STR_WITH([luks2-pbkdf], [Default PBKDF algorithm (pbkdf2 or argon2i/argon2id) for LUKS2], [argon2i])
CS_NUM_WITH([luks1-iter-time], [PBKDF2 iteration time for LUKS1 (in ms)], [2000])
CS_NUM_WITH([luks2-iter-time], [Argon2 PBKDF iteration time for LUKS2 (in ms)], [2000])
CS_NUM_WITH([luks2-memory-kb], [Argon2 PBKDF memory cost for LUKS2 (in kB)], [1048576])
CS_NUM_WITH([luks2-parallel-threads],[Argon2 PBKDF max parallel cost for LUKS2 (if CPUs available)], [4])
CS_STR_WITH([luks2-keyslot-cipher], [fallback cipher for LUKS2 keyslot (if data encryption is incompatible)], [aes-xts-plain64])
CS_NUM_WITH([luks2-keyslot-keybits],[fallback key size for LUKS2 keyslot (if data encryption is incompatible)], [512])
CS_STR_WITH([loopaes-cipher], [cipher for loop-AES mode], [aes])
CS_NUM_WITH([loopaes-keybits],[key length in bits for loop-AES mode], [256])
CS_NUM_WITH([keyfile-size-maxkb],[maximum keyfile size (in KiB)], [8192])
CS_NUM_WITH([passphrase-size-max],[maximum keyfile size (in characters)], [512])
CS_NUM_WITH([integrity-keyfile-size-maxkb],[maximum integritysetup keyfile size (in KiB)], [4])
CS_NUM_WITH([passphrase-size-max],[maximum passphrase size (in characters)], [512])
CS_STR_WITH([verity-hash], [hash function for verity mode], [sha256])
CS_NUM_WITH([verity-data-block], [data block size for verity mode], [4096])
CS_NUM_WITH([verity-hash-block], [hash block size for verity mode], [4096])
CS_NUM_WITH([verity-salt-size], [salt size for verity mode], [32])
CS_NUM_WITH([verity-fec-roots], [parity bytes for verity FEC], [2])
CS_STR_WITH([tmpfilesdir], [override default path to directory with systemd temporary files], [])
test -z "$with_tmpfilesdir" && with_tmpfilesdir=$systemd_tmpfilesdir
test "x$with_tmpfilesdir" = "xno" || {
CS_ABSPATH([${with_tmpfilesdir}],[with-tmpfilesdir])
DEFAULT_TMPFILESDIR=$with_tmpfilesdir
AC_SUBST(DEFAULT_TMPFILESDIR)
}
AM_CONDITIONAL(CRYPTSETUP_TMPFILE, test -n "$DEFAULT_TMPFILESDIR")
CS_STR_WITH([luks2-lock-path], [path to directory for LUKSv2 locks], [/run/cryptsetup])
test -z "$with_luks2_lock_path" && with_luks2_lock_path=/run/cryptsetup
CS_ABSPATH([${with_luks2_lock_path}],[with-luks2-lock-path])
DEFAULT_LUKS2_LOCK_PATH=$with_luks2_lock_path
AC_SUBST(DEFAULT_LUKS2_LOCK_PATH)
CS_NUM_WITH([luks2-lock-dir-perms], [default luks2 locking directory permissions], [0700])
test -z "$with_luks2_lock_dir_perms" && with_luks2_lock_dir_perms=0700
DEFAULT_LUKS2_LOCK_DIR_PERMS=$with_luks2_lock_dir_perms
AC_SUBST(DEFAULT_LUKS2_LOCK_DIR_PERMS)
dnl Override default LUKS format version (for cryptsetup or cryptsetup-reencrypt format actions only).
AC_ARG_WITH([default_luks_format],
AS_HELP_STRING([--with-default-luks-format=FORMAT], [default LUKS format version (LUKS1/LUKS2) [LUKS2]]),
[], [with_default_luks_format=LUKS2])
case $with_default_luks_format in
LUKS1) default_luks=CRYPT_LUKS1 ;;
LUKS2) default_luks=CRYPT_LUKS2 ;;
*) AC_MSG_ERROR([Unknown default LUKS format. Use LUKS1 or LUKS2 only.]) ;;
esac
AC_DEFINE_UNQUOTED([DEFAULT_LUKS_FORMAT], [$default_luks], [default LUKS format version])
dnl ==========================================================================
AC_CONFIG_FILES([ Makefile
lib/Makefile
lib/libcryptsetup.pc
lib/crypto_backend/Makefile
lib/luks1/Makefile
lib/loopaes/Makefile
lib/verity/Makefile
lib/tcrypt/Makefile
src/Makefile
po/Makefile.in
man/Makefile
scripts/cryptsetup.conf
tests/Makefile
python/Makefile
])
AC_OUTPUT

View File

@@ -178,7 +178,7 @@
* Document cryptsetup exit codes.
2011-03-18 Milan Broz <mbroz@redhat.com>
* Respect maximum keyfile size paramater.
* Respect maximum keyfile size parameter.
* Introduce maximum default keyfile size, add configure option.
* Require the whole key read from keyfile in create command (broken in 1.2.0).
* Fix offset option for loopaesOpen.
@@ -195,7 +195,7 @@
2011-03-05 Milan Broz <mbroz@redhat.com>
* Add exception to COPYING for binary distribution linked with OpenSSL library.
* Set secure data flag (wipe all ioclt buffers) if devmapper library supports it.
* Set secure data flag (wipe all ioctl buffers) if devmapper library supports it.
2011-01-29 Milan Broz <mbroz@redhat.com>
* Fix mapping removal if device disappeared but node still exists.
@@ -334,13 +334,13 @@
* Version 1.1.0.
2010-01-10 Milan Broz <mbroz@redhat.com>
* Fix initialisation of gcrypt duting luksFormat.
* Convert hash name to lower case in header (fix sha1 backward comatible header)
* Fix initialisation of gcrypt during luksFormat.
* Convert hash name to lower case in header (fix sha1 backward compatible header)
* Check for minimum required gcrypt version.
2009-12-30 Milan Broz <mbroz@redhat.com>
* Fix key slot iteration count calculation (small -i value was the same as default).
* The slot and key digest iteration minimun is now 1000.
* The slot and key digest iteration minimum is now 1000.
* The key digest iteration # is calculated from iteration time (approx 1/8 of that).
* Version 1.1.0-rc4.
@@ -395,16 +395,16 @@
* Require device device-mapper to build and do not use backend wrapper for dm calls.
* Move memory locking and dm initialization to command layer.
* Increase priority of process if memory is locked.
* Add log macros and make logging modre consitent.
* Add log macros and make logging more consistent.
* Move command successful messages to verbose level.
* Introduce --debug parameter.
* Move device utils code and provide context parameter (for log).
* Keyfile now must be provided by path, only stdin file descriptor is used (api only).
* Do not call isatty() on closed keyfile descriptor.
* Run performance check for PBKDF2 from LUKS code, do not mix hash algoritms results.
* Run performance check for PBKDF2 from LUKS code, do not mix hash algorithms results.
* Add ability to provide pre-generated master key and UUID in LUKS header format.
* Add LUKS function to verify master key digest.
* Move key slot manuipulation function into LUKS specific code.
* Move key slot manipulation function into LUKS specific code.
* Replace global options struct with separate parameters in helper functions.
* Add new libcryptsetup API (documented in libcryptsetup.h).
* Implement old API calls using new functions.
@@ -412,7 +412,7 @@
* Add --master-key-file option for luksFormat and luksAddKey.
2009-08-17 Milan Broz <mbroz@redhat.com>
* Fix PBKDF2 speed calculation for large passhrases.
* Fix PBKDF2 speed calculation for large passphrases.
* Allow using passphrase provided in options struct for LuksOpen.
* Allow restrict keys size in LuksOpen.
@@ -424,7 +424,7 @@
* Switch PBKDF2 from internal SHA1 to libgcrypt, make hash algorithm not hardcoded to SHA1 here.
* Add required parameters for changing hash used in LUKS key setup scheme.
* Do not export simple XOR helper now used only inside AF functions.
* Completely remove internal SHA1 implementanion code, not needed anymore.
* Completely remove internal SHA1 implementation code, not needed anymore.
* Enable hash algorithm selection for LUKS through -h luksFormat option.
2009-07-28 Milan Broz <mbroz@redhat.com>
@@ -636,7 +636,7 @@
2006-03-15 Clemens Fruhwirth <clemens@endorphin.org>
* configure.in: 1.0.3-rc3. Most unplease release ever.
* configure.in: 1.0.3-rc3. Most displease release ever.
* lib/setup.c (__crypt_create_device): More verbose error message.
2006-02-26 Clemens Fruhwirth <clemens@endorphin.org>
@@ -705,7 +705,7 @@
2005-12-06 Clemens Fruhwirth <clemens@endorphin.org>
* man/cryptsetup.8: Correct "seconds" to "microseconds" in the explaination for -i.
* man/cryptsetup.8: Correct "seconds" to "microseconds" in the explanation for -i.
2005-11-09 Clemens Fruhwirth <clemens@endorphin.org>
@@ -726,7 +726,7 @@
2005-09-08 Clemens Fruhwirth <clemens@endorphin.org>
* lib/setup.c (get_key): Fixed another incompatiblity with
* lib/setup.c (get_key): Fixed another incompatibility with
original cryptsetup.
2005-08-20 Clemens Fruhwirth <clemens@endorphin.org>
@@ -816,7 +816,7 @@
* man/cryptsetup.1: Add man page.
* lib/setup.c: Remove unneccessary LUKS_write_phdr call, so the
* lib/setup.c: Remove unnecessary LUKS_write_phdr call, so the
phdr is written after passphrase reading, so the user can change
his mind, and not have a partial written LUKS header on it's disk.

56
docs/Keyring.txt Normal file
View File

@@ -0,0 +1,56 @@
Integration with kernel keyring service
---------------------------------------
We have two different use cases for kernel keyring service:
I) Volume keys
Since upstream kernel 4.10 dm-crypt device mapper target allows loading volume
key (VK) in kernel keyring service. The key offloaded in kernel keyring service
is only referenced (by key description) in dm-crypt target and the VK is therefore
no longer stored directly in dm-crypt target. Starting with cryptsetup 2.0 we
load VK in kernel keyring by default for LUKSv2 devices (when dm-crypt with the
feature is available).
Currently cryptsetup loads VK in 'logon' type kernel key so that VK is passed in
the kernel and can't be read from userspace afterward. Also cryptsetup loads VK in
thread keyring (before passing the reference to dm-crypt target) so that the key
lifetime is directly bound to the process that performs the dm-crypt setup. When
cryptsetup process exits (for whatever reason) the key gets unlinked in kernel
automatically. In summary, the key description visible in dm-crypt table line is
a reference to VK that usually no longer exists in kernel keyring service if you
used cryptsetup to for device activation.
Using this feature dm-crypt no longer maintains a direct key copy (but there's
always at least one copy in kernel crypto layer).
II) Keyslot passphrase
The second use case for kernel keyring is to allow cryptsetup reading the keyslot
passphrase stored in kernel keyring instead. The user may load passphrase in kernel
keyring and notify cryptsetup to read it from there later. Currently, cryptsetup
cli supports kernel keyring for passphrase only via LUKS2 internal token
(luks2-keyring). Library also provides a general method for device activation by
reading passphrase from keyring: crypt_activate_by_keyring(). The key type
for use case II) must always be 'user' since we need to read the actual key
data from userspace unlike with VK in I). Ability to read keyslot passphrase
from kernel keyring also allows easily auto-activate LUKS2 devices.
Simple example how to use kernel keyring for keyslot passphrase:
1) create LUKS2 keyring token for keyslot 0 (in LUKS2 device/image)
cryptsetup token add --key-description my:key -S 0 /dev/device
2) Load keyslot passphrase in user keyring
read -s -p "Keyslot passphrase: "; echo -n $REPLY | keyctl padd user my:key @u
3) Activate device using passphrase stored in kernel keyring
cryptsetup open /dev/device my_unlocked_device
4a) unlink the key when no longer needed by
keyctl unlink %user:my:key @u
4b) or revoke it immediately by
keyctl revoke %user:my:key
If cryptsetup asks for passphrase in step 3) something went wrong with keyring
activation. See --debug output then.

61
docs/LUKS2-locking.txt Normal file
View File

@@ -0,0 +1,61 @@
LUKS2 device locking overview
=============================
Why
~~~
LUKS2 format keeps two identical copies of metadata stored consecutively
at the head of metadata device (file or bdev). The metadata
area (both copies) must be updated in a single atomic operation to avoid
header corruption during concurrent write.
While with LUKS1 users may have clear knowledge of when a LUKS header is
being updated (written to) or when it's being read solely the need for
locking with legacy format was not so obvious as it is with the LUKSv2 format.
With LUKS2 the boundary between read-only and read-write is blurry and what
used to be the exclusively read-only operation (i.e., cryptsetup open command) may
easily become read-update operation silently without user's knowledge.
Major feature of LUKS2 format is resilience against accidental
corruption of metadata (i.e., partial header overwrite by parted or cfdisk
while creating partition on mistaken block device).
Such header corruption is detected early on header read and auto-recovery
procedure takes place (the corrupted header with checksum mismatch is being
replaced by the secondary one if that one is intact).
On current Linux systems header load operation may be triggered without user
direct intervention for example by udev rule or from systemd service.
Such clash of header read and auto-recovery procedure could have severe
consequences with the worst case of having LUKS2 device unaccessible or being
broken beyond repair.
The whole locking of LUKSv2 device headers split into two categories depending
what backend the header is stored on:
I) block device
~~~~~~~~~~~~~~~
We perform flock() on file descriptors of files stored in a private
directory (by default /run/lock/cryptsetup). The file name is derived
from major:minor couple of affected block device. Note we recommend
that access to private locking directory is supposed to be limited
to superuser only. For this method to work the distribution needs
to install the locking directory with appropriate access rights.
II) regular files
~~~~~~~~~~~~~~~~~
First notable difference between headers stored in a file
vs. headers stored in a block device is that headers in a file may be
manipulated by the regular user unlike headers on block devices. Therefore
we perform flock() protection on file with the luks2 header directly.
Limitations
~~~~~~~~~~~
a) In general, the locking model provides serialization of I/Os targeting
the header only. It means the header is always written or read at once
while locking is enabled.
We do not suppress any other negative effect that two or more concurrent
writers of the same header may cause.
b) The locking is not cluster aware in any way.

View File

@@ -1,4 +1,4 @@
# Doxyfile 1.7.4
# Doxyfile 1.8.8
#---------------------------------------------------------------------------
# Project related configuration options
@@ -10,6 +10,7 @@ PROJECT_BRIEF = "Public cryptsetup API"
PROJECT_LOGO =
OUTPUT_DIRECTORY = doxygen_api_docs
CREATE_SUBDIRS = NO
ALLOW_UNICODE_NAMES = NO
OUTPUT_LANGUAGE = English
BRIEF_MEMBER_DESC = YES
REPEAT_BRIEF = YES
@@ -27,11 +28,14 @@ INHERIT_DOCS = YES
SEPARATE_MEMBER_PAGES = NO
TAB_SIZE = 8
ALIASES =
TCL_SUBST =
OPTIMIZE_OUTPUT_FOR_C = YES
OPTIMIZE_OUTPUT_JAVA = NO
OPTIMIZE_FOR_FORTRAN = NO
OPTIMIZE_OUTPUT_VHDL = NO
EXTENSION_MAPPING =
MARKDOWN_SUPPORT = YES
AUTOLINK_SUPPORT = YES
BUILTIN_STL_SUPPORT = NO
CPP_CLI_SUPPORT = NO
SIP_SUPPORT = NO
@@ -39,13 +43,15 @@ IDL_PROPERTY_SUPPORT = YES
DISTRIBUTE_GROUP_DOC = NO
SUBGROUPING = YES
INLINE_GROUPED_CLASSES = NO
INLINE_SIMPLE_STRUCTS = NO
TYPEDEF_HIDES_STRUCT = YES
SYMBOL_CACHE_SIZE = 0
LOOKUP_CACHE_SIZE = 0
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
EXTRACT_ALL = NO
EXTRACT_PRIVATE = NO
EXTRACT_PACKAGE = NO
EXTRACT_STATIC = NO
EXTRACT_LOCAL_CLASSES = YES
EXTRACT_LOCAL_METHODS = NO
@@ -58,6 +64,7 @@ INTERNAL_DOCS = NO
CASE_SENSE_NAMES = YES
HIDE_SCOPE_NAMES = NO
SHOW_INCLUDE_FILES = YES
SHOW_GROUPED_MEMB_INC = NO
FORCE_LOCAL_INCLUDES = NO
INLINE_INFO = YES
SORT_MEMBER_DOCS = YES
@@ -73,13 +80,13 @@ GENERATE_DEPRECATEDLIST= YES
ENABLED_SECTIONS =
MAX_INITIALIZER_LINES = 30
SHOW_USED_FILES = YES
SHOW_DIRECTORIES = NO
SHOW_FILES = YES
SHOW_NAMESPACES = YES
FILE_VERSION_FILTER =
LAYOUT_FILE =
CITE_BIB_FILES =
#---------------------------------------------------------------------------
# configuration options related to warning and progress messages
# Configuration options related to warning and progress messages
#---------------------------------------------------------------------------
QUIET = NO
WARNINGS = YES
@@ -89,9 +96,10 @@ WARN_NO_PARAMDOC = NO
WARN_FORMAT = "$file:$line: $text"
WARN_LOGFILE =
#---------------------------------------------------------------------------
# configuration options related to the input files
# Configuration options related to the input files
#---------------------------------------------------------------------------
INPUT = "doxygen_index" "../lib/libcryptsetup.h"
INPUT = "doxygen_index.h" \
"../lib/libcryptsetup.h"
INPUT_ENCODING = UTF-8
FILE_PATTERNS =
RECURSIVE = NO
@@ -107,8 +115,9 @@ INPUT_FILTER =
FILTER_PATTERNS =
FILTER_SOURCE_FILES = NO
FILTER_SOURCE_PATTERNS =
USE_MDFILE_AS_MAINPAGE =
#---------------------------------------------------------------------------
# configuration options related to source browsing
# Configuration options related to source browsing
#---------------------------------------------------------------------------
SOURCE_BROWSER = NO
INLINE_SOURCES = NO
@@ -116,16 +125,19 @@ STRIP_CODE_COMMENTS = YES
REFERENCED_BY_RELATION = NO
REFERENCES_RELATION = NO
REFERENCES_LINK_SOURCE = YES
SOURCE_TOOLTIPS = YES
USE_HTAGS = NO
VERBATIM_HEADERS = YES
CLANG_ASSISTED_PARSING = NO
CLANG_OPTIONS =
#---------------------------------------------------------------------------
# configuration options related to the alphabetical class index
# Configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
ALPHABETICAL_INDEX = YES
COLS_IN_ALPHA_INDEX = 5
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# configuration options related to the HTML output
# Configuration options related to the HTML output
#---------------------------------------------------------------------------
GENERATE_HTML = YES
HTML_OUTPUT = html
@@ -133,13 +145,14 @@ HTML_FILE_EXTENSION = .html
HTML_HEADER =
HTML_FOOTER =
HTML_STYLESHEET =
HTML_EXTRA_STYLESHEET =
HTML_EXTRA_FILES =
HTML_COLORSTYLE_HUE = 220
HTML_COLORSTYLE_SAT = 100
HTML_COLORSTYLE_GAMMA = 80
HTML_TIMESTAMP = YES
HTML_ALIGN_MEMBERS = YES
HTML_DYNAMIC_SECTIONS = NO
HTML_INDEX_NUM_ENTRIES = 100
GENERATE_DOCSET = NO
DOCSET_FEEDNAME = "Doxygen generated docs"
DOCSET_BUNDLE_ID = org.doxygen.Project
@@ -163,19 +176,26 @@ QHG_LOCATION =
GENERATE_ECLIPSEHELP = NO
ECLIPSE_DOC_ID = org.doxygen.Project
DISABLE_INDEX = NO
ENUM_VALUES_PER_LINE = 4
GENERATE_TREEVIEW = NO
USE_INLINE_TREES = NO
ENUM_VALUES_PER_LINE = 4
TREEVIEW_WIDTH = 250
EXT_LINKS_IN_WINDOW = NO
FORMULA_FONTSIZE = 10
FORMULA_TRANSPARENT = YES
USE_MATHJAX = NO
MATHJAX_FORMAT = HTML-CSS
MATHJAX_RELPATH = http://www.mathjax.org/mathjax
MATHJAX_EXTENSIONS =
MATHJAX_CODEFILE =
SEARCHENGINE = YES
SERVER_BASED_SEARCH = NO
EXTERNAL_SEARCH = NO
SEARCHENGINE_URL =
SEARCHDATA_FILE = searchdata.xml
EXTERNAL_SEARCH_ID =
EXTRA_SEARCH_MAPPINGS =
#---------------------------------------------------------------------------
# configuration options related to the LaTeX output
# Configuration options related to the LaTeX output
#---------------------------------------------------------------------------
GENERATE_LATEX = YES
LATEX_OUTPUT = latex
@@ -186,13 +206,15 @@ PAPER_TYPE = a4
EXTRA_PACKAGES =
LATEX_HEADER =
LATEX_FOOTER =
LATEX_EXTRA_FILES =
PDF_HYPERLINKS = YES
USE_PDFLATEX = YES
LATEX_BATCHMODE = NO
LATEX_HIDE_INDICES = NO
LATEX_SOURCE_CODE = NO
LATEX_BIB_STYLE = plain
#---------------------------------------------------------------------------
# configuration options related to the RTF output
# Configuration options related to the RTF output
#---------------------------------------------------------------------------
GENERATE_RTF = NO
RTF_OUTPUT = rtf
@@ -201,26 +223,31 @@ RTF_HYPERLINKS = NO
RTF_STYLESHEET_FILE =
RTF_EXTENSIONS_FILE =
#---------------------------------------------------------------------------
# configuration options related to the man page output
# Configuration options related to the man page output
#---------------------------------------------------------------------------
GENERATE_MAN = NO
MAN_OUTPUT = man
MAN_EXTENSION = .3
MAN_SUBDIR =
MAN_LINKS = NO
#---------------------------------------------------------------------------
# configuration options related to the XML output
# Configuration options related to the XML output
#---------------------------------------------------------------------------
GENERATE_XML = NO
XML_OUTPUT = xml
XML_SCHEMA =
XML_DTD =
XML_PROGRAMLISTING = YES
#---------------------------------------------------------------------------
# configuration options for the AutoGen Definitions output
# Configuration options related to the DOCBOOK output
#---------------------------------------------------------------------------
GENERATE_DOCBOOK = NO
DOCBOOK_OUTPUT = docbook
DOCBOOK_PROGRAMLISTING = NO
#---------------------------------------------------------------------------
# Configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
GENERATE_AUTOGEN_DEF = NO
#---------------------------------------------------------------------------
# configuration options related to the Perl module output
# Configuration options related to the Perl module output
#---------------------------------------------------------------------------
GENERATE_PERLMOD = NO
PERLMOD_LATEX = NO
@@ -239,18 +266,20 @@ PREDEFINED =
EXPAND_AS_DEFINED =
SKIP_FUNCTION_MACROS = YES
#---------------------------------------------------------------------------
# Configuration::additions related to external references
# Configuration options related to external references
#---------------------------------------------------------------------------
TAGFILES =
GENERATE_TAGFILE =
ALLEXTERNALS = NO
EXTERNAL_GROUPS = YES
EXTERNAL_PAGES = YES
PERL_PATH =
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
CLASS_DIAGRAMS = YES
MSCGEN_PATH =
DIA_PATH =
HIDE_UNDOC_RELATIONS = YES
HAVE_DOT = NO
DOT_NUM_THREADS = 0
@@ -261,6 +290,7 @@ CLASS_GRAPH = YES
COLLABORATION_GRAPH = YES
GROUP_GRAPHS = YES
UML_LOOK = NO
UML_LIMIT_NUM_FIELDS = 10
TEMPLATE_RELATIONS = NO
INCLUDE_GRAPH = YES
INCLUDED_BY_GRAPH = YES
@@ -269,9 +299,12 @@ CALLER_GRAPH = NO
GRAPHICAL_HIERARCHY = YES
DIRECTORY_GRAPH = YES
DOT_IMAGE_FORMAT = png
INTERACTIVE_SVG = NO
DOT_PATH =
DOTFILE_DIRS =
MSCFILE_DIRS =
DIAFILE_DIRS =
PLANTUML_JAR_PATH =
DOT_GRAPH_MAX_NODES = 50
MAX_DOT_GRAPH_DEPTH = 0
DOT_TRANSPARENT = NO

View File

@@ -1,10 +1,9 @@
/**
* @mainpage Cryptsetup API
/*! \mainpage Cryptsetup API
*
* The documentation covers public parts of cryptsetup API. In the following sections you'll find
* <b>The</b> documentation covers public parts of cryptsetup API. In the following sections you'll find
* the examples that describe some features of cryptsetup API.
* For more info about libcryptsetup API versions see
* <a href="http://upstream-tracker.org/versions/libcryptsetup.html">Upstream Tracker</a>.
* <a href="https://gitlab.com/cryptsetup/cryptsetup/wikis/ABI-tracker/timeline/libcryptsetup/index.html">API Tracker</a>.
*
* <OL type="A">
* <LI>@ref cexamples "Cryptsetup API examples"</LI>
@@ -32,18 +31,16 @@
* @section cexamples Cryptsetup API examples
* @section cluks crypt_luks_usage - cryptsetup LUKS device type usage
* @subsection cinit crypt_init()
*
* Every time you need to do something with cryptsetup or dmcrypt device
* Every time you need to do something with cryptsetup or dmcrypt device
* you need a valid context. The first step to start your work is
* @ref crypt_init call. You can call it either with path
* to the block device or path to the regular file. If you don't supply the path,
* empty context is initialized.
*
* @subsection cformat crypt_format() - header and payload on mutual device
*
* This section covers basic use cases for formatting LUKS devices. Format operation
* sets device type in context and in case of LUKS header is written at the beginning
* of block device. In the example bellow we use the scenario where LUKS header and data
* of block device. In the example below we use the scenario where LUKS header and data
* are both stored on the same device. There's also a possibility to store header and
* data separately.
*
@@ -51,42 +48,35 @@
* overwrites part of the backing block device.
*
* @subsection ckeys Keyslot operations examples
*
* After successful @ref crypt_format of LUKS device, volume key is not stored
* in a persistent way on the device. Keyslot area is an array beyond LUKS header, where
* volume key is stored in the encrypted form using user input passphrase. For more info about
* LUKS keyslots and how it's actually protected, please look at
* <A HREF="http://code.google.com/p/cryptsetup/wiki/Specification">LUKS specification</A>.
* <A HREF="https://gitlab.com/cryptsetup/cryptsetup/wikis/Specification">LUKS specification</A>.
* There are two basic methods to create a new keyslot:
*
* @subsection ckeyslot_vol crypt_keyslot_add_by_volume_key()
*
* Creates a new keyslot directly by encrypting volume_key stored in the device
* context. Passphrase should be supplied or user is prompted if passphrase param is
* NULL.
*
* @subsection ckeyslot_pass crypt_keyslot_add_by_passphrase()
*
* Creates a new keyslot for the volume key by opening existing active keyslot,
* extracting volume key from it and storing it into a new keyslot
* protected by a new passphrase
*
* @subsection cload crypt_load()
*
* Function loads header from backing block device into device context.
*
* @subsection cactivate crypt_activate_by_passphrase()
*
* Activates crypt device by user supplied password for keyslot containing the volume_key.
* If <I>keyslot</I> parameter is set to <I>CRYPT_ANY_SLOT</I> then all active keyslots
* are tried one by one until the volume key is found.
*
* @subsection cactive_pars crypt_get_active_device()
*
* This call returns structure containing runtime attributes of active device.
*
* @subsection cinit_by_name crypt_init_by_name()
*
* In case you need to do operations with active device (device which already
* has its corresponding mapping) and you miss valid device context stored in
* *crypt_device reference, you should use this call. Function tries to
@@ -94,22 +84,18 @@
* header.
*
* @subsection cdeactivate crypt_deactivate()
*
* Deactivates crypt device (removes DM mapping and safely erases volume key from kernel).
*
* @subsection cluks_ex crypt_luks_usage.c - Complex example
*
* To compile and run use following commands in examples directory:
*
* @code
* make
* ./crypt_luks_usage _path_to_[block_device]_file
* @endcode
*
* Note that you need to have the cryptsetup library compiled. @include crypt_luks_usage.c
*
* @section clog crypt_log_usage - cryptsetup logging API example
*
* Example describes basic use case for cryptsetup logging. To compile and run
* use following commands in examples directory:
*
@@ -117,7 +103,6 @@
* make
* ./crypt_log_usage
* @endcode
*
* Note that you need to have the cryptsetup library compiled. @include crypt_log_usage.c
*
* @example crypt_luks_usage.c

View File

@@ -1,7 +1,7 @@
/*
* An example of using logging through libcryptsetup API
* libcryptsetup API log example
*
* Copyright (C) 2011, Red Hat, Inc. All rights reserved.
* Copyright (C) 2011-2021 Red Hat, Inc. All rights reserved.
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -25,10 +25,8 @@
#include <libcryptsetup.h>
/*
* This is an example of function that can be registered using crypt_set_log_callback API.
* This is an example of crypt_set_log_callback API callback.
*
* Its prototype is void (*log)(int level, const char *msg, void *usrptr) as defined
* in crypt_set_log_callback
*/
static void simple_syslog_wrapper(int level, const char *msg, void *usrptr)
{
@@ -71,7 +69,7 @@ int main(void)
return 2;
}
/* crypt_set_log_callback() - register a log function for crypt context */
/* crypt_set_log_callback() - register a log callback for crypt context */
crypt_set_log_callback(cd, &simple_syslog_wrapper, (void *)usrprefix);
/* send messages ithrough the crypt_log() interface */
@@ -83,7 +81,7 @@ int main(void)
/* release crypt context */
crypt_free(cd);
/* Initialize default (global) log function */
/* Initialize default (global) log callback */
crypt_set_log_callback(NULL, &simple_syslog_wrapper, NULL);
crypt_log(NULL, CRYPT_LOG_NORMAL, "This is normal log message");

View File

@@ -1,7 +1,7 @@
/*
* An example of using LUKS device through libcryptsetup API
* libcryptsetup API - using LUKS device example
*
* Copyright (C) 2011, Red Hat, Inc. All rights reserved.
* Copyright (C) 2011-2021 Red Hat, Inc. All rights reserved.
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -29,23 +29,18 @@
static int format_and_add_keyslots(const char *path)
{
struct crypt_device *cd;
struct crypt_params_luks1 params;
int r;
/*
* crypt_init() call precedes most of operations of cryptsetup API. The call is used
* to initialize crypt device context stored in structure referenced by _cd_ in
* the example. Second parameter is used to pass underlaying device path.
* The crypt_init() call is used to initialize crypt_device context,
* The path parameter specifies a device path.
*
* Note:
* If path refers to a regular file it'll be attached to a first free loop device.
* crypt_init() operation fails in case there's no more loop device available.
* Also, loop device will have the AUTOCLEAR flag set, so the file loopback will
* be detached automatically.
* For path, you can use either link to a file or block device.
* The loopback device will be detached automatically.
*/
r = crypt_init(&cd, path);
if (r < 0 ) {
if (r < 0) {
printf("crypt_init() failed for %s.\n", path);
return r;
}
@@ -53,73 +48,37 @@ static int format_and_add_keyslots(const char *path)
printf("Context is attached to block device %s.\n", crypt_get_device_name(cd));
/*
* So far no data were written on your device. This will change with call of
* crypt_format() only if you specify CRYPT_LUKS1 as device type.
* So far, no data were written to the device.
*/
printf("Device %s will be formatted to LUKS device after 5 seconds.\n"
printf("Device %s will be formatted as a LUKS device after 5 seconds.\n"
"Press CTRL+C now if you want to cancel this operation.\n", path);
sleep(5);
/*
* Prepare LUKS format parameters
*
* hash parameter defines PBKDF2 hash algorithm used in LUKS header.
* For compatibility reason we use SHA1 here.
*/
params.hash = "sha1";
/*
* data_alignment parameter is relevant only in case of the luks header
* and the payload are both stored on same device.
*
* if you set data_alignment = 0, cryptsetup will autodetect
* data_alignment according to underlaying device topology.
*/
params.data_alignment = 0;
/*
* data_device parameter defines that no external device
* for luks header will be used
*/
params.data_device = NULL;
/*
* NULLs for uuid and volume_key means that these attributes will be
* generated during crypt_format(). Volume key is generated with respect
* to key size parameter passed to function.
*
* crypt_format() checks device size (LUKS header must fit there).
* generated during crypt_format().
*/
r = crypt_format(cd, /* crypt context */
CRYPT_LUKS1, /* LUKS1 is standard LUKS header */
CRYPT_LUKS2, /* LUKS2 is a new LUKS format; use CRYPT_LUKS1 for LUKS1 */
"aes", /* used cipher */
"xts-plain64", /* used block mode and IV generator*/
"xts-plain64", /* used block mode and IV */
NULL, /* generate UUID */
NULL, /* generate volume key from RNG */
256 / 8, /* 256bit key - here AES-128 in XTS mode, size is in bytes */
&params); /* parameters above */
512 / 8, /* 512bit key - here AES-256 in XTS mode, size is in bytes */
NULL); /* default parameters */
if(r < 0) {
if (r < 0) {
printf("crypt_format() failed on device %s\n", crypt_get_device_name(cd));
crypt_free(cd);
return r;
}
/*
* The device now contains LUKS1 header, but there is
* no active keyslot with encrypted volume key yet.
*/
/*
* cryptt_kesylot_add_* call stores volume_key in encrypted form into keyslot.
* Without keyslot you can't manipulate with LUKS device after the context will be freed.
* The device now contains a LUKS header, but there is no active keyslot.
*
* To create a new keyslot you need to supply the existing one (to get the volume key from) or
* you need to supply the volume key.
* crypt_keyslot_add_* call stores the volume_key in the encrypted form into the keyslot.
*
* After format, we have volume key stored internally in context so add new keyslot
* using this internal volume key.
* After format, the volume key is stored internally.
*/
r = crypt_keyslot_add_by_volume_key(cd, /* crypt context */
CRYPT_ANY_SLOT, /* just use first free slot */
@@ -137,8 +96,8 @@ static int format_and_add_keyslots(const char *path)
printf("The first keyslot is initialized.\n");
/*
* Add another keyslot, now using the first keyslot.
* It will decrypt volume key from the first keyslot and creates new one with another passphrase.
* Add another keyslot, now authenticating with the first keyslot.
* It decrypts the volume key from the first keyslot and creates a new one with the specified passphrase.
*/
r = crypt_keyslot_add_by_passphrase(cd, /* crypt context */
CRYPT_ANY_SLOT, /* just use first free slot */
@@ -164,21 +123,18 @@ static int activate_and_check_status(const char *path, const char *device_name)
/*
* LUKS device activation example.
* It's sequence of sub-steps: device initialization, LUKS header load
* and the device activation itself.
*/
r = crypt_init(&cd, path);
if (r < 0 ) {
if (r < 0) {
printf("crypt_init() failed for %s.\n", path);
return r;
}
/*
* crypt_load() is used to load the LUKS header from block device
* into crypt_device context.
* crypt_load() is used to load existing LUKS header from a block device
*/
r = crypt_load(cd, /* crypt context */
CRYPT_LUKS1, /* requested type */
CRYPT_LUKS, /* requested type - here LUKS of any type */
NULL); /* additional parameters (not used) */
if (r < 0) {
@@ -188,11 +144,11 @@ static int activate_and_check_status(const char *path, const char *device_name)
}
/*
* Device activation creates device-mapper devie mapping with name device_name.
* Device activation creates a device-mapper device with the specified name.
*/
r = crypt_activate_by_passphrase(cd, /* crypt context */
device_name, /* device name to activate */
CRYPT_ANY_SLOT,/* which slot use (ANY - try all) */
CRYPT_ANY_SLOT,/* the keyslot use (try all here) */
"foo", 3, /* passphrase */
CRYPT_ACTIVATE_READONLY); /* flags */
if (r < 0) {
@@ -201,13 +157,13 @@ static int activate_and_check_status(const char *path, const char *device_name)
return r;
}
printf("LUKS device %s/%s is active.\n", crypt_get_dir(), device_name);
printf("%s device %s/%s is active.\n", crypt_get_type(cd), crypt_get_dir(), device_name);
printf("\tcipher used: %s\n", crypt_get_cipher(cd));
printf("\tcipher mode: %s\n", crypt_get_cipher_mode(cd));
printf("\tdevice UUID: %s\n", crypt_get_uuid(cd));
/*
* Get info about active device (query DM backend)
* Get info about the active device.
*/
r = crypt_get_active_device(cd, device_name, &cad);
if (r < 0) {
@@ -235,7 +191,7 @@ static int handle_active_device(const char *device_name)
int r;
/*
* crypt_init_by_name() initializes device context and loads LUKS header from backing device
* crypt_init_by_name() initializes context by an active device-mapper name
*/
r = crypt_init_by_name(&cd, device_name);
if (r < 0) {
@@ -252,7 +208,7 @@ static int handle_active_device(const char *device_name)
}
/*
* crypt_deactivate() is used to deactivate device
* crypt_deactivate() is used to deactivate a device
*/
r = crypt_deactivate(cd, device_name);
if (r < 0) {

Binary file not shown.

Binary file not shown.

View File

@@ -15,7 +15,7 @@ Important changes
* NSS (because of missing ripemd160 it cannot provide full backward compatibility)
* kernel userspace API (provided by kernel 2.6.38 and above)
(Note that kernel userspace backend is very slow for this type of operation.
But it can be usefull for embedded systems, because you can avoid userspace
But it can be useful for embedded systems, because you can avoid userspace
crypto library completely.)
Backend is selected during configure time, using --with-crypto_backend option.

View File

@@ -89,7 +89,7 @@ WARNING: This release removes old deprecated API from libcryptsetup
(It can be used to simulate trivial hidden disk concepts.)
libcryptsetup API changes:
* Added options to suport detached metadata device
* Added options to support detached metadata device
crypt_init_by_name_and_header()
crypt_set_data_device()
* Add crypt_last_error() API call.

View File

@@ -46,7 +46,7 @@ Side effect of reencryption is that final device will contain
only ciphertext (for all sectors) so even if device was not properly
wiped by random data, after reencryption you cannot distinguish
which sectors are used.
(Reecryption is done always for the whole device.)
(Reencryption is done always for the whole device.)
There are for sure bugs, please TEST IT IN TEST ENVIRONMENT before
use for your data.

84
docs/v1.6.7-ReleaseNotes Normal file
View File

@@ -0,0 +1,84 @@
Cryptsetup 1.6.7 Release Notes
==============================
Changes since version 1.6.6
* Cryptsetup git and wiki are now hosted on GitLab.
https://gitlab.com/cryptsetup/cryptsetup
Repository of stable releases remains on kernel.org site
https://www.kernel.org/pub/linux/utils/cryptsetup/
For more info please see README file.
* Cryptsetup TCRYPT mode now supports VeraCrypt devices (TrueCrypt extension).
The VeraCrypt extension only increases iteration count for the key
derivation function (on-disk format is the same as TrueCrypt format).
Note that unlocking of a VeraCrypt device can take very long time if used
on slow machines.
To use this extension, add --veracrypt option, for example
cryptsetup open --type tcrypt --veracrypt <container> <name>
For use through libcryptsetup, just add CRYPT_TCRYPT_VERA_MODES flag.
* Support keyfile-offset and keyfile-size options even for plain volumes.
* Support keyfile option for luksAddKey if the master key is specified.
* For historic reasons, hashing in the plain mode is not used
if keyfile is specified (with exception of --key-file=-).
Print a warning if these parameters are ignored.
* Support permanent device decryption for cryptsetup-reencrypt.
To remove LUKS encryption from a device, you can now use --decrypt option.
* Allow to use --header option in all LUKS commands.
The --header always takes precedence over positional device argument.
* Allow luksSuspend without need to specify a detached header.
* Detect if O_DIRECT is usable on a device allocation.
There are some strange storage stack configurations which wrongly allows
to open devices with direct-io but fails on all IO operations later.
Cryptsetup now tries to read the device first sector to ensure it can use
direct-io.
* Add low-level performance options tuning for dmcrypt (for Linux 4.0 and later).
Linux kernel 4.0 contains rewritten dmcrypt code which tries to better utilize
encryption on parallel CPU cores.
While tests show that this change increases performance on most configurations,
dmcrypt now provides some switches to change its new behavior.
You can use them (per-device) with these cryptsetup switches:
--perf-same_cpu_crypt
--perf-submit_from_crypt_cpus
Please use these only in the case of serious performance problems.
Refer to the cryptsetup man page and dm-crypt documentation
(for same_cpu_crypt and submit_from_crypt_cpus options).
https://gitlab.com/cryptsetup/cryptsetup/wikis/DMCrypt
* Get rid of libfipscheck library.
(Note that this option was used only for Red Hat and derived distributions.)
With recent FIPS changes we do not need to link to this FIPS monster anymore.
Also drop some no longer needed FIPS mode checks.
* Many fixes and clarifications to man pages.
* Prevent compiler to optimize-out zeroing of buffers for on-stack variables.
* Fix a crash if non-GNU strerror_r is used.
Cryptsetup API NOTE:
The direct terminal handling for passphrase entry will be removed from
libcryptsetup in next major version (application should handle it itself).
It means that you have to always either provide password in buffer or set
your own password callback function through crypt_set_password_callback().
See API documentation (or libcryptsetup.h) for more info.

47
docs/v1.6.8-ReleaseNotes Normal file
View File

@@ -0,0 +1,47 @@
Cryptsetup 1.6.8 Release Notes
==============================
Changes since version 1.6.7
* If the null cipher (no encryption) is used, allow only empty password for LUKS.
(Previously cryptsetup accepted any password in this case.)
The null cipher can be used only for testing and it is used temporarily during
offline encrypting not yet encrypted device (cryptsetup-reencrypt tool).
Accepting only empty password prevents situation when someone adds another
LUKS device using the same UUID (UUID of existing LUKS device) with faked
header containing null cipher.
This could force user to use different LUKS device (with no encryption)
without noticing.
(IOW it prevents situation when attacker intentionally forces
user to boot into different system just by LUKS header manipulation.)
Properly configured systems should have an additional integrity protection
in place here (LUKS here provides only confidentiality) but it is better
to not allow this situation in the first place.
(For more info see QubesOS Security Bulletin QSB-019-2015.)
* Properly support stdin "-" handling for luksAddKey for both new and old
keyfile parameters.
* If encrypted device is file-backed (it uses underlying loop device),
cryptsetup resize will try to resize underlying loop device as well.
(It can be used to grow up file-backed device in one step.)
* Cryptsetup now allows to use empty password through stdin pipe.
(Intended only for testing in scripts.)
Cryptsetup API NOTE:
Direct terminal handling and password calling callback for passphrase
entry will be removed from libcryptsetup in next major (2.x) version
(application should handle it itself).
It means that application have to always provide password in API calls.
Functions returning last error will be removed in next major version (2.x).
These functions did not work properly for early initialization errors
and application can implement better function easily using own error callback.
See comments in libcryptsetup.h for more info about deprecated functions.

81
docs/v1.7.0-ReleaseNotes Normal file
View File

@@ -0,0 +1,81 @@
Cryptsetup 1.7.0 Release Notes
==============================
The cryptsetup 1.7 release changes defaults for LUKS,
there are no API changes.
Changes since version 1.6.8
* Default hash function is now SHA256 (used in key derivation function
and anti-forensic splitter).
Note that replacing SHA1 with SHA256 is not for security reasons.
(LUKS does not have problems even if collisions are found for SHA1,
for details see FAQ item 5.20).
Using SHA256 as default is mainly to prevent compatibility problems
on hardened systems where SHA1 is already be phased out.
Note that all checks (kernel crypto API availability check) now uses
SHA256 as well.
* Default iteration time for PBKDF2 is now 2 seconds.
Increasing iteration time is in combination with PBKDF2 benchmark
fixes a try to keep PBKDF2 iteration count still high enough and
also still acceptable for users.
N.B. Long term is to replace PBKDF2 algorithm with Password Hashing
Competition winner - Argon2.
Distributions can still change these defaults in compilation time.
You can change iteration time and used hash function in existing LUKS
header with cryptsetup-reencrypt utility even without full reencryption
of device (see --keep-key option).
* Fix PBKDF2 iteration benchmark for longer key sizes.
The previous PBKDF2 benchmark code did not take into account
output key length properly.
For SHA1 (with 160-bits output) and 256-bit keys (and longer)
it means that the final iteration value was higher than it should be.
For other hash algorithms (like SHA256 or SHA512) it caused
that iteration count was lower (in comparison to SHA1) than
expected for the requested time period.
The PBKDF2 benchmark code is now fixed to use the key size for
the formatted device (or default LUKS key size if running in informational
benchmark mode).
Thanks to A.Visconti, S.Bossi, A.Calo and H.Ragab
(http://www.club.di.unimi.it/) for point this out.
(Based on "What users should know about Full Disk Encryption
based on LUKS" paper to be presented on CANS2015).
* Remove experimental warning for reencrypt tool.
The strong request for full backup before using reencryption utility
still applies :)
* Add optional libpasswdqc support for new LUKS passwords.
If password is entered through terminal (no keyfile specified) and
cryptsetup is compiled with --enable-passwdqc[=/etc/passwdqc.conf],
configured system passwdqc settings are used to check password quality.
* Update FAQ document.
Cryptsetup API NOTE:
Direct terminal handling and password calling callback for passphrase
entry will be removed from libcryptsetup in next major (2.x) version
(application should handle it itself).
It means that application have to always provide password in API calls.
Functions returning last error will be removed in next major version (2.x).
These functions did not work properly for early initialization errors
and application can implement better function easily using own error callback.
See comments in libcryptsetup.h for more info about deprecated functions.

36
docs/v1.7.1-ReleaseNotes Normal file
View File

@@ -0,0 +1,36 @@
Cryptsetup 1.7.1 Release Notes
==============================
Changes since version 1.7.0
* Code now uses kernel crypto API backend according to new
changes introduced in mainline kernel
While mainline kernel should contain backward compatible
changes, some stable series kernels do not contain fully
backported compatibility patches.
Without these patches most of cryptsetup operations
(like unlocking device) fail.
This change in cryptsetup ensures that all operations using
kernel crypto API works even on these kernels.
* The cryptsetup-reencrypt utility now properly detects removal
of underlying link to block device and does not remove
ongoing re-encryption log.
This allows proper recovery (resume) of reencrypt operation later.
NOTE: Never use /dev/disk/by-uuid/ path for reencryption utility,
this link disappears once the device metadata is temporarily
removed from device.
* Cryptsetup now allows special "-" (standard input) keyfile handling
even for TCRYPT (TrueCrypt and VeraCrypt compatible) devices.
* Cryptsetup now fails if there are more keyfiles specified
for non-TCRYPT device.
* The luksKillSlot command now does not suppress provided password
in batch mode (if password is wrong slot is not destroyed).
Note that not providing password in batch mode means that keyslot
is destroyed unconditionally.

37
docs/v1.7.2-ReleaseNotes Normal file
View File

@@ -0,0 +1,37 @@
Cryptsetup 1.7.2 Release Notes
==============================
Changes since version 1.7.1
* Update LUKS documentation format.
Clarify fixed sector size and keyslots alignment.
* Support activation options for error handling modes in Linux kernel
dm-verity module:
--ignore-corruption - dm-verity just logs detected corruption
--restart-on-corruption - dm-verity restarts the kernel if corruption is detected
If the options above are not specified, default behavior for dm-verity remains.
Default is that I/O operation fails with I/O error if corrupted block is detected.
--ignore-zero-blocks - Instructs dm-verity to not verify blocks that are expected
to contain zeroes and always return zeroes directly instead.
NOTE that these options could have security or functional impacts,
do not use them without assessing the risks!
* Fix help text for cipher benchmark specification (mention --cipher option).
* Fix off-by-one error in maximum keyfile size.
Allow keyfiles up to compiled-in default and not that value minus one.
* Support resume of interrupted decryption in cryptsetup-reencrypt utility.
To resume decryption, LUKS device UUID (--uuid option) option must be used.
* Do not use direct-io for LUKS header with unaligned keyslots.
Such headers were used only by the first cryptsetup-luks-1.0.0 release (2005).
* Fix device block size detection to properly work on particular file-based
containers over underlying devices with 4k sectors.

20
docs/v1.7.3-ReleaseNotes Normal file
View File

@@ -0,0 +1,20 @@
Cryptsetup 1.7.3 Release Notes
==============================
Changes since version 1.7.2
* Fix device access to hash offsets located beyond the 2GB device boundary in veritysetup.
* Set configured (compile-time) default iteration time for devices created directly through
libcryptsetup (default was hardcoded 1 second, the configured value applied only
for cryptsetup application).
* Fix PBKDF2 benchmark to not double iteration count for specific corner case.
If the measurement function returns exactly 500 ms, the iteration calculation loop
doubled iteration count but instead of repeating measurement it used this value directly.
* OpenSSL backend: fix memory leak if hash context was repeatedly reused.
* OpenSSL backend: add support for OpenSSL 1.1.0.
* Fix several minor spelling errors.

22
docs/v1.7.4-ReleaseNotes Normal file
View File

@@ -0,0 +1,22 @@
Cryptsetup 1.7.4 Release Notes
==============================
Changes since version 1.7.3
* Allow to specify LUKS1 hash algorithm in Python luksFormat wrapper.
* Use LUKS1 compiled-in defaults also in Python wrapper.
* OpenSSL backend: Fix OpenSSL 1.1.0 support without backward compatible API.
* OpenSSL backend: Fix LibreSSL compatibility.
* Check for data device and hash device area overlap in veritysetup.
* Fix a possible race while allocating a free loop device.
* Fix possible file descriptor leaks if libcryptsetup is run from a forked process.
* Fix missing same_cpu_crypt flag in status command.
* Various updates to FAQ and man pages.

22
docs/v1.7.5-ReleaseNotes Normal file
View File

@@ -0,0 +1,22 @@
Cryptsetup 1.7.5 Release Notes
==============================
Changes since version 1.7.4
* Fixes to luksFormat to properly support recent kernel running in FIPS mode.
Cryptsetup must never use a weak key even if it is just used for testing
of algorithm availability. In FIPS mode, weak keys are always rejected.
A weak key is for example detected if the XTS encryption mode use
the same key for the tweak and the encryption part.
* Fixes accesses to unaligned hidden legacy TrueCrypt header.
On a native 4k-sector device the old hidden TrueCrypt header is not
aligned with the hw sector size (this problem was fixed in later TrueCrypt
on-disk format versions).
Cryptsetup now properly aligns the read so it does not fail.
* Fixes to optional dracut ramdisk scripts for offline re-encryption on initial boot.

605
docs/v2.0.0-ReleaseNotes Normal file
View File

@@ -0,0 +1,605 @@
Cryptsetup 2.0.0 Release Notes
==============================
Stable release with experimental features.
This version introduces a new on-disk LUKS2 format.
The legacy LUKS (referenced as LUKS1) will be fully supported
forever as well as a traditional and fully backward compatible format.
NOTE: This version changes soname of libcryptsetup library and increases
major version for all public symbols.
Most of the old functions are fully backward compatible, so only
recompilation of programs should be needed.
Please note that authenticated disk encryption, non-cryptographic
data integrity protection (dm-integrity), use of Argon2 Password-Based
Key Derivation Function and the LUKS2 on-disk format itself are new
features and can contain some bugs.
To provide all security features of authenticated encryption we need
better nonce-reuse resistant algorithm in kernel (see note below).
For now, please use authenticated encryption as experimental feature.
Please do not use LUKS2 without properly configured backup or in
production systems that need to be compatible with older systems.
Changes since version 2.0.0-RC1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Limit KDF requested (for format) memory by available physical memory.
On some systems too high requested amount of memory causes OOM killer
to kill the process (instead of returning ENOMEM).
We never try to use more than half of available physical memory.
* Ignore device alignment if it is not multiple of minimal-io.
Some USB enclosures seems to report bogus topology info that
prevents to use LUKS detached header.
Changes since version 2.0.0-RC0
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Enable to use system libargon2 instead of bundled version.
Renames --disable-argon2 to --disable-internal-argon2 option
and adds --enable-libargon2 flag to allow system libargon2.
* Changes in build system (Automake)
- The build system now uses non-recursive automake (except for tests).
(Tools binaries are now located in buildroot directory.)
- New --disable-cryptsetup option to disable build of cryptsetup tool.
- Enable build of cryptsetup-reencrypt by default.
* Install tmpfiles.d configuration for LUKS2 locking directory.
You can overwrite this using --with-tmpfilesdir configure option.
If your distro does not support tmpfiles.d directory, you have
to create locking directory (/run/lock/cryptsetup) in cryptsetup
package (or init scripts).
* Adds limited support for offline reencryption of LUKS2 format.
* Decrease size of testing images (and the whole release archive).
* Fixes for several memory leaks found by Valgrind and Coverity tools.
* Fixes for several typos in man pages and error messages.
* LUKS header file in luksFormat is now automatically created
if it does not exist.
* Do not allow resize if device size is not aligned to sector size.
Cryptsetup 2.0.0 RC0 Release Notes
==================================
Important features
~~~~~~~~~~~~~~~~~~
* New command integritysetup: support for the new dm-integrity kernel target.
The dm-integrity is a new kernel device-mapper target that introduces
software emulation of per-sector integrity fields on the disk sector level.
It is available since Linux kernel version 4.12.
The provided per-sector metadata fields can be used for storing a data
integrity checksum (for example CRC32).
The dm-integrity implements data journal that enforces atomic update
of a sector and its integrity metadata.
Integritysetup is a CLI utility that can setup standalone dm-integrity
devices (that internally check integrity of data).
Integritysetup is intended to be used for settings that require
non-cryptographic data integrity protection with no data encryption.
Fo setting integrity protected encrypted devices, see disk authenticated
encryption below.
Note that after formatting the checksums need to be initialized;
otherwise device reads will fail because of integrity errors.
Integritysetup by default tries to wipe the device with zero blocks
to avoid this problem. Device wipe can be time-consuming, you can skip
this step by specifying --no-wipe option.
(But note that not wiping device can cause some operations to fail
if a write is not multiple of page size and kernel page cache tries
to read sectors with not yet initialized checksums.)
The default setting is tag size 4 bytes per-sector and CRC32C protection.
To format device with these defaults:
$ integritysetup format <device>
$ integritysetup open <device> <name>
Note that used algorithm (unlike tag size) is NOT stored in device
kernel superblock and if you use different algorithm, you MUST specify
it in every open command, for example:
$ integritysetup format <device> --tag-size 32 --integrity sha256
$ integritysetup open <device> <name> --integrity sha256
For more info, see integrity man page.
* Veritysetup command can now format and activate dm-verity devices
that contain Forward Error Correction (FEC) (Reed-Solomon code is used).
This feature is used on most of Android devices already (available since
Linux kernel 4.5).
There are new options --fec-device, --fec-offset to specify data area
with correction code and --fec-roots that set Redd-Solomon generator roots.
This setting can be used for format command (veritysetup will calculate
and store RS codes) or open command (veritysetup configures kernel
dm-verity to use RS codes).
For more info see veritysetup man page.
* Support for larger sector sizes for crypt devices.
LUKS2 and plain crypt devices can be now configured with larger encryption
sector (typically 4096 bytes, sector size must be the power of two,
maximal sector size is 4096 bytes for portability).
Large sector size can decrease encryption overhead and can also help
with some specific crypto hardware accelerators that perform very
badly with 512 bytes sectors.
Note that if you configure such a larger sector of the device that does use
smaller physical sector, there is a possibility of a data corruption during
power fail (partial sector writes).
WARNING: If you use different sector size for a plain device after data were
stored, the decryption will produce garbage.
For LUKS2, the sector size is stored in metadata and cannot be changed later.
LUKS2 format and features
~~~~~~~~~~~~~~~~~~~~~~~~~
The LUKS2 is an on-disk storage format designed to provide simple key
management, primarily intended for Full Disk Encryption based on dm-crypt.
The LUKS2 is inspired by LUKS1 format and in some specific situations (most
of the default configurations) can be converted in-place from LUKS1.
The LUKS2 format is designed to allow future updates of various
parts without the need to modify binary structures and internally
uses JSON text format for metadata. Compilation now requires the json-c library
that is used for JSON data processing.
On-disk format provides redundancy of metadata, detection
of metadata corruption and automatic repair from metadata copy.
NOTE: For security reasons, there is no redundancy in keyslots binary data
(encrypted keys) but the format allows adding such a feature in future.
NOTE: to operate correctly, LUKS2 requires locking of metadata.
Locking is performed by using flock() system call for images in file
and for block device by using a specific lock file in /run/lock/cryptsetup.
This directory must be created by distribution (do not rely on internal
fallback). For systemd-based distribution, you can simply install
scripts/cryptsetup.conf into tmpfiles.d directory.
For more details see LUKS2-format.txt and LUKS2-locking.txt in the docs
directory. (Please note this is just overview, there will be more formal
documentation later.)
LUKS2 use
~~~~~~~~~
LUKS2 allows using all possible configurations as LUKS1.
To format device as LUKS2, you have to add "--type luks2" during format:
$ cryptsetup luksFormat --type luks2 <device>
All commands issued later will recognize the new format automatically.
The newly added features in LUKS2 include:
* Authenticated disk (sector) encryption (EXPERIMENTAL)
Legacy Full disk encryption (FDE), for example, LUKS1, is a length-preserving
encryption (plaintext is the same size as a ciphertext).
Such FDE can provide data confidentiality, but cannot provide sound data
integrity protection.
Full disk authenticated encryption is a way how to provide both
confidentiality and data integrity protection. Integrity protection here means
not only detection of random data corruption (silent data corruption) but also
prevention of an unauthorized intentional change of disk sector content.
NOTE: Integrity protection of this type cannot prevent a replay attack.
An attacker can replace the device or its part of the old content, and it
cannot be detected.
If you need such protection, better use integrity protection on a higher layer.
For data integrity protection on the sector level, we need additional
per-sector metadata space. In LUKS2 this space is provided by a new
device-mapper dm-integrity target (available since kernel 4.12).
Here the integrity target provides only reliable per-sector metadata store,
and the whole authenticated encryption is performed inside dm-crypt stacked
over the dm-integrity device.
For encryption, Authenticated Encryption with Additional Data (AEAD) is used.
Every sector is processed as a encryption request of this format:
|----- AAD -------|------ DATA -------|-- AUTH TAG --|
| (authenticated) | (auth+encryption) | |
| sector_LE | IV | sector in/out | tag in/out |
AEAD encrypts the whole sector and also authenticates sector number
(to detect sector relocation) and also authenticates Initialization Vector.
AEAD encryption produces encrypted data and authentication tag.
The authenticated tag is then stored in per-sector metadata space provided
by dm-integrity.
Most of the current AEAD algorithms requires IV as a nonce, value that is
never reused. Because sector number, as an IV, cannot be used in this
environment, we use a new random IV (IV is a random value generated by system
RNG on every write). This random IV is then stored in the per-sector metadata
as well.
Because the authentication tag (and IV) requires additional space, the device
provided for a user has less capacity. Also, the data journalling means that
writes are performed twice, decreasing throughput.
This integrity protection works better with SSDs. If you want to ignore
dm-integrity data journal (because journalling is performed on some higher
layer or you just want to trade-off performance to safe recovery), you can
switch journal off with --integrity-no-journal option.
(This flag can be stored persistently as well.)
Note that (similar to integritysetup) the device read will fail if
authentication tag is not initialized (no previous write).
By default cryptsetup run wipe of a device (writing zeroes) to initialize
authentication tags. This operation can be very time-consuming.
You can skip device wipe using --integrity-no-wipe option.
To format LUKS2 device with integrity protection, use new --integrity option.
For now, there are very few AEAD algorithms that can be used, and some
of them are known to be problematic. In this release we support only
a few of AEAD algorithms (options are for now hard coded), later this
extension will be completely algorithm-agnostic.
For testing of authenticated encryption, these algorithms work for now:
1) aes-xts-plain64 with hmac-sha256 or hmac-sha512 as the authentication tag.
(Common FDE mode + independent authentication tag. Authentication key
for HMAC is independently generated. This mode is very slow.)
$ cryptsetup luksFormat --type luks2 <device> --cipher aes-xts-plain64 --integrity hmac-sha256
2) aes-gcm-random (native AEAD mode)
DO NOT USE in production! The GCM mode uses only 96-bit nonce,
and possible collision means fatal security problem.
GCM mode has very good hardware support through AES-NI, so it is useful
for performance testing.
$ cryptsetup luksFormat --type luks2 <device> --cipher aes-gcm-random --integrity aead
3) ChaCha20 with Poly1305 authenticator (according to RFC7539)
$ cryptsetup luksFormat --type luks2 <device> --cipher chacha20-random --integrity poly1305
To specify AES128/AES256 just specify proper key size (without possible
authentication key). Other symmetric ciphers, like Serpent or Twofish,
should work as well. The mode 1) and 2) should be compatible with IEEE 1619.1
standard recommendation.
There will be better suitable authenticated modes available soon
For now we are just preparing framework to enable it (and hopefully improve security of FDE).
FDE authenticated encryption is not a replacement for filesystem layer
authenticated encryption. The goal is to provide at least something because
data integrity protection is often completely ignored in today systems.
* New memory-hard PBKDF
LUKS1 introduced Password-Based Key Derivation Function v2 as a tool to
increase attacker cost for a dictionary and brute force attacks.
The PBKDF2 uses iteration count to increase time of key derivation.
Unfortunately, with modern GPUs, the PBKDF2 calculations can be run
in parallel and PBKDF2 can no longer provide the best available protection.
Increasing iteration count just cannot prevent massive parallel dictionary
password attacks in long-term.
To solve this problem, a new PBKDF, based on so-called memory-hard functions
can be used. Key derivation with memory-hard function requires a certain
amount of memory to compute its output. The memory requirement is very
costly for GPUs and prevents these systems to operate effectively,
increasing cost for attackers.
LUKS2 introduces support for Argon2i and Argon2id as a PBKDF.
Argon2 is the winner of Password Hashing Competition and is currently
in final RFC draft specification.
For now, libcryptsetup contains the embedded copy of reference implementation
of Argon2 (that is easily portable to all architectures).
Later, once this function is available in common crypto libraries, it will
switch to external implementation. (This happened for LUKS1 and PBKDF2
as well years ago.)
With using reference implementation (that is not optimized for speed), there
is some performance penalty. However, using memory-hard PBKDF should still
significantly complicate GPU-optimized dictionary and brute force attacks.
The Argon2 uses three costs: memory, time (number of iterations) and parallel
(number of threads).
Note that time and memory cost highly influences each other (accessing a lot
of memory takes more time).
There is a new benchmark that tries to calculate costs to take similar way as
in LUKS1 (where iteration is measured to take 1-2 seconds on user system).
Because now there are more cost variables, it prefers time cost (iterations)
and tries to find required memory that fits. (IOW required memory cost can be
lower if the benchmarks are not able to find required parameters.)
The benchmark cannot run too long, so it tries to approximate next step
for benchmarking.
For now, default LUKS2 PBKDF algorithm is Argon2i (data independent variant)
with memory cost set to 128MB, time to 800ms and parallel thread according
to available CPU cores but no more than 4.
All default parameters can be set during compile time and also set on
the command line by using --pbkdf, --pbkdf-memory, --pbkdf-parallel and
--iter-time options.
(Or without benchmark directly by using --pbkdf-force-iterations, see below.)
You can still use PBKDF2 even for LUKS2 by specifying --pbkdf pbkdf2 option.
(Then only iteration count is applied.)
* Use of kernel keyring
Kernel keyring is a storage for sensitive material (like cryptographic keys)
inside Linux kernel.
LUKS2 uses keyring for two major functions:
- To store volume key for dm-crypt where it avoids sending volume key in
every device-mapper ioctl structure. Volume key is also no longer directly
visible in a dm-crypt mapping table. The key is not available for the user
after dm-crypt configuration (obviously except direct memory scan).
Use of kernel keyring can be disabled in runtime by --disable-keyring option.
- As a tool to automatically unlock LUKS device if a passphrase is put into
kernel keyring and proper keyring token is configured.
This allows storing a secret (passphrase) to kernel per-user keyring by
some external tool (for example some TPM handler) and LUKS2, if configured,
will automatically search in the keyring and unlock the system.
For more info see Tokens section below.
* Persistent flags
The activation flags (like allow-discards) can be stored in metadata and used
automatically by all later activations (even without using crypttab).
To store activation flags permanently, use activation command with required
flags and add --persistent option.
For example, to mark device to always activate with TRIM enabled,
use (for LUKS2 type):
$ cryptsetup open <device> <name> --allow-discards --persistent
You can check persistent flags in dump command output:
$ cryptsetup luksDump <device>
* Tokens and auto-activation
A LUKS2 token is an object that can be described "how to get passphrase or key"
to unlock particular keyslot.
(Also it can be used to store any additional metadata, and with
the libcryptsetup interface it can be used to define user token types.)
Cryptsetup internally implements keyring token. Cryptsetup tries to use
available tokens before asking for the passphrase. For keyring token,
it means that if the passphrase is available under specified identifier
inside kernel keyring, the device is automatically activated using this
stored passphrase.
Example of using LUKS2 keyring token:
# Adding token to metadata with "my_token" identifier (by default it applies to all keyslots).
$ cryptsetup token add --key-description "my_token" <device>
# Storing passphrase to user keyring (this can be done by an external application)
$ echo -n <passphrase> | keyctl padd user my_token @u
# Now cryptsetup activates automatically if it finds correct passphrase
$ cryptsetup open <device> <name>
The main reason to use tokens this way is to separate possible hardware
handlers from cryptsetup code.
* Keyslot priorities
LUKS2 keyslot can have a new priority attribute.
The default is "normal". The "prefer" priority tell the keyslot to be tried
before other keyslots. Priority "ignore" means that keyslot will never be
used if not specified explicitly (it can be used for backup administrator
passwords that are used only situations when a user forgets own passphrase).
The priority of keyslot can be set with new config command, for example
$ cryptsetup config <device> --key-slot 1 --priority prefer
Setting priority to normal will reset slot to normal state.
* LUKS2 label and subsystem
The header now contains additional fields for label and subsystem (additional
label). These fields can be used similar to filesystem label and will be
visible in udev rules to possible filtering. (Note that blkid do not yet
contain the LUKS scanning code).
By default both labels are empty. Label and subsystem are always set together
(no option means clear the label) with the config command:
$ cryptsetup config <device> --label my_device --subsystem ""
* In-place conversion form LUKS1
To allow easy testing and transition to the new LUKS2 format, there is a new
convert command that allows in-place conversion from the LUKS1 format and,
if there are no incompatible options, also conversion back from LUKS2
to LUKS1 format.
Note this command can be used only on some LUKS1 devices (some device header
sizes are not supported).
This command is dangerous, never run it without header backup!
If something fails in the middle of conversion (IO error), the header
is destroyed. (Note that conversion requires move of keyslot data area to
a different offset.)
To convert header in-place to LUKS2 format, use
$ cryptsetup convert <device> --type luks2
To convert it back to LUKS1 format, use
$ cryptsetup convert <device> --type luks1
You can verify LUKS version with luksDump command.
$ cryptsetup luksDump <device>
Note that some LUKS2 features will make header incompatible with LUKS1 and
conversion will be rejected (for example using new Argon2 PBKDF or integrity
extensions). Some minor attributes can be lost in conversion.
Other changes
~~~~~~~~~~~~~
* Explicit KDF iterations count setting
With new PBKDF interface, there is also the possibility to setup PBKDF costs
directly, avoiding benchmarks. This can be useful if device is formatted to be
primarily used on a different system.
The option --pbkdf-force-iterations is available for both LUKS1 and LUKS2
format. Using this option can cause device to have either very low or very
high PBKDF costs.
In the first case it means bad protection to dictionary attacks, in the second
case, it can mean extremely high unlocking time or memory requirements.
Use only if you are sure what you are doing!
Not that this setting also affects iteration count for the key digest.
For LUKS1 iteration count for digest will be approximately 1/8 of requested
value, for LUKS2 and "pbkdf2" digest minimal PBKDF2 iteration count (1000)
will be used. You cannot set lower iteration count than the internal minimum
(1000 for PBKDF2).
To format LUKS1 device with forced iteration count (and no benchmarking), use
$ cryptsetup luksFormat <device> --pbkdf-force-iterations 22222
For LUKS2 it is always better to specify full settings (do not rely on default
cost values).
For example, we can set to use Argon2id with iteration cost 5, memory 128000
and parallel set 1:
$ cryptsetup luksFormat --type luks2 <device> \
--pbkdf argon2id --pbkdf-force-iterations 5 --pbkdf-memory 128000 --pbkdf-parallel 1
* VeraCrypt PIM
Cryptsetup can now also open VeraCrypt device that uses Personal Iteration
Multiplier (PIM). PIM is an integer value that user must remember additionally
to passphrase and influences PBKDF2 iteration count (without it VeraCrypt uses
a fixed number of iterations).
To open VeraCrypt device with PIM settings, use --veracrypt-pim (to specify
PIM on the command line) or --veracrypt-query-pim to query PIM interactively.
* Support for plain64be IV
The plain64be is big-endian variant of plain64 Initialization Vector. It is
used in some images of hardware-based disk encryption systems. Supporting this
variant allows using dm-crypt to map such images through cryptsetup.
* Deferral removal
Cryptsetup now can mark device for deferred removal by using a new option
--deferred. This means that close command will not fail if the device is still
in use, but will instruct the kernel to remove the device automatically after
use count drops to zero (for example, once the filesystem is unmounted).
* A lot of updates to man pages and many minor changes that would make this
release notes too long ;-)
Libcryptsetup API changes
~~~~~~~~~~~~~~~~~~~~~~~~~
These API functions were removed, libcryptsetup no longer handles password
retries from terminal (application should handle terminal operations itself):
crypt_set_password_callback;
crypt_set_timeout;
crypt_set_password_retry;
crypt_set_password_verify;
This call is removed (no need to keep typo backward compatibility,
the proper function is crypt_set_iteration_time :-)
crypt_set_iterarion_time;
These calls were removed because are not safe, use per-context
error callbacks instead:
crypt_last_error;
crypt_get_error;
The PBKDF benchmark was replaced by a new function that uses new KDF structure
crypt_benchmark_kdf; (removed)
crypt_benchmark_pbkdf; (new API call)
These new calls are now exported, for details see libcryptsetup.h:
crypt_keyslot_add_by_key;
crypt_keyslot_set_priority;
crypt_keyslot_get_priority;
crypt_token_json_get;
crypt_token_json_set;
crypt_token_status;
crypt_token_luks2_keyring_get;
crypt_token_luks2_keyring_set;
crypt_token_assign_keyslot;
crypt_token_unassign_keyslot;
crypt_token_register;
crypt_activate_by_token;
crypt_activate_by_keyring;
crypt_deactivate_by_name;
crypt_metadata_locking;
crypt_volume_key_keyring;
crypt_get_integrity_info;
crypt_get_sector_size;
crypt_persistent_flags_set;
crypt_persistent_flags_get;
crypt_set_pbkdf_type;
crypt_get_pbkdf_type;
crypt_convert;
crypt_keyfile_read;
crypt_wipe;
Unfinished things & TODO for next releases
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* There will be better documentation and examples.
* There will be some more formal definition of the threat model for integrity
protection. (And a link to some papers discussing integrity protection,
once it is, hopefully, accepted and published.)
* Offline re-encrypt tool LUKS2 support is currently limited.
There will be online LUKS2 re-encryption tool in future.
* Authenticated encryption will use new algorithms from CAESAR competition
(https://competitions.cr.yp.to/caesar.html) once these algorithms are available
in kernel (more on this later).
NOTE: Currently available authenticated modes (GCM, Chacha20-poly1305)
in kernel have too small 96-bit nonces that are problematic with
randomly generated IVs (the collison probability is not negligible).
For the GCM, nonce collision is a fatal problem.
* Authenticated encryption do not set encryption for dm-integrity journal.
While it does not influence data confidentiality or integrity protection,
an attacker can get some more information from data journal or cause that
system will corrupt sectors after journal replay. (That corruption will be
detected though.)
* Some utilities (blkid, systemd-cryptsetup) have already support for LUKS
but not yet in released version (support in crypttab etc).
* There are some examples of user-defined tokens inside misc/luks2_keyslot_example
directory (like a simple external program that uses libssh to unlock LUKS2
using remote keyfile).
* The python binding (pycryptsetup) contains only basic functionality for LUKS1
(it is not updated for new features) and will be deprecated soon in favor
of python bindings to libblockdev library (that can already handle LUKS1 devices).

109
docs/v2.0.1-ReleaseNotes Normal file
View File

@@ -0,0 +1,109 @@
Cryptsetup 2.0.1 Release Notes
==============================
Stable and bug-fix release with experimental features.
This version introduces a new on-disk LUKS2 format.
The legacy LUKS (referenced as LUKS1) will be fully supported
forever as well as a traditional and fully backward compatible format.
Please note that authenticated disk encryption, non-cryptographic
data integrity protection (dm-integrity), use of Argon2 Password-Based
Key Derivation Function and the LUKS2 on-disk format itself are new
features and can contain some bugs.
To provide all security features of authenticated encryption we need
a better nonce-reuse resistant algorithm in the kernel (see note below).
For now, please use authenticated encryption as an experimental feature.
Please do not use LUKS2 without properly configured backup or in
production systems that need to be compatible with older systems.
Changes since version 2.0.0
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* To store volume key into kernel keyring, kernel 4.15 with dm-crypt 1.18.1
is required. If a volume key is stored in keyring (LUKS2 only),
the dm-crypt v1.15.0 through v1.18.0 contains a serious bug that may cause
data corruption for ciphers with ESSIV.
(The key for ESSIV is zeroed because of code misplacement.)
This bug is not present for LUKS1 or any other IVs used in LUKS modes.
This change is not visible to the user (except dmsetup output).
* Increase maximum allowed PBKDF memory-cost limit to 4 GiB.
The Argon2 PBKDF uses 1GiB by default; this is also limited by the amount
of physical memory available (maximum is half of the physical memory).
* Use /run/cryptsetup as default for cryptsetup locking dir.
There were problems with sharing /run/lock with lockdev, and in the early
boot, the directory was missing.
The directory can be changed with --with-luks2-lock-path and
--with-luks2-lock-dir-perms configure switches.
* Introduce new 64-bit byte-offset *keyfile_device_offset functions.
The keyfile interface was designed, well, for keyfiles. Unfortunately,
there are user cases where a keyfile can be placed on a device, and
size_t offset can overflow on 32-bit systems.
New set of functions that allow 64-bit offsets even on 32bit systems
are now available:
- crypt_resume_by_keyfile_device_offset
- crypt_keyslot_add_by_keyfile_device_offset
- crypt_activate_by_keyfile_device_offset
- crypt_keyfile_device_read
The new functions have added the _device_ in name.
Old functions are just internal wrappers around these.
Also cryptsetup --keyfile-offset and --new-keyfile-offset now allows
64-bit offsets as parameters.
* Add error hint for wrongly formatted cipher strings in LUKS1 and
properly fail in luksFormat if cipher format is missing required IV.
For now, crypto API quietly used cipher without IV if a cipher
algorithm without IV specification was used (e.g., aes-xts).
This caused fail later during activation.
* Configure check for a recent Argon2 lib to support mandatory Argon2id.
* Fix for the cryptsetup-reencrypt static build if pwquality is enabled.
* Update LUKS1 standard doc (https links in the bibliography).
Unfinished things & TODO for next releases
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* There will be better documentation and examples.
* There will be some more formal definition of the threat model for integrity
protection. (And a link to some papers discussing integrity protection,
once it is, hopefully, accepted and published.)
* Offline re-encrypt tool LUKS2 support is currently limited.
There will be online LUKS2 re-encryption tool in future.
* Authenticated encryption will use new algorithms from CAESAR competition
(https://competitions.cr.yp.to/caesar.html) once these algorithms are
available in the kernel (more on this later).
NOTE: Currently available authenticated modes (GCM, Chacha20-poly1305)
in the kernel have too small 96-bit nonces that are problematic with
randomly generated IVs (the collision probability is not negligible).
For the GCM, nonce collision is a fatal problem.
* Authenticated encryption do not set encryption for a dm-integrity journal.
While it does not influence data confidentiality or integrity protection,
an attacker can get some more information from data journal or cause that
system will corrupt sectors after journal replay. (That corruption will be
detected though.)
* There are examples of user-defined tokens inside misc/luks2_keyslot_example
directory (like a simple external program that uses libssh to unlock LUKS2
using remote keyfile).
* The python binding (pycryptsetup) contains only basic functionality for LUKS1
(it is not updated for new features) and will be deprecated soon in favor
of python bindings to the libblockdev library (that can already handle LUKS1
devices).

93
docs/v2.0.2-ReleaseNotes Normal file
View File

@@ -0,0 +1,93 @@
Cryptsetup 2.0.2 Release Notes
==============================
Stable and bug-fix release with experimental features.
Cryptsetup 2.x version introduces a new on-disk LUKS2 format.
The legacy LUKS (referenced as LUKS1) will be fully supported
forever as well as a traditional and fully backward compatible format.
Please note that authenticated disk encryption, non-cryptographic
data integrity protection (dm-integrity), use of Argon2 Password-Based
Key Derivation Function and the LUKS2 on-disk format itself are new
features and can contain some bugs.
To provide all security features of authenticated encryption, we need
a better nonce-reuse resistant algorithm in the kernel (see note below).
For now, please use authenticated encryption as an experimental feature.
Please do not use LUKS2 without properly configured backup or in
production systems that need to be compatible with older systems.
Changes since version 2.0.1
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Fix a regression in early detection of inactive keyslot for luksKillSlot.
It tried to ask for passphrase even for already erased keyslot.
* Fix a regression in loopaesOpen processing for keyfile on standard input.
Use of "-" argument was not working properly.
* Add LUKS2 specific options for cryptsetup-reencrypt.
Tokens and persistent flags are now transferred during reencryption;
change of PBKDF keyslot parameters is now supported and allows
to set precalculated values (no benchmarks).
* Do not allow LUKS2 --persistent and --test-passphrase cryptsetup flags
combination. Persistent flags are now stored only if the device was
successfully activated with the specified flags.
* Fix integritysetup format after recent Linux kernel changes that
requires to setup key for HMAC in all cases.
Previously integritysetup allowed HMAC with zero key that behaves
like a plain hash.
* Fix VeraCrypt PIM handling that modified internal iteration counts
even for subsequent activations. The PIM count is no longer printed
in debug log as it is sensitive information.
Also, the code now skips legacy TrueCrypt algorithms if a PIM
is specified (they cannot be used with PIM anyway).
* PBKDF values cannot be set (even with force parameters) below
hardcoded minimums. For PBKDF2 is it 1000 iterations, for Argon2
it is 4 iterations and 32 KiB of memory cost.
* Introduce new crypt_token_is_assigned() API function for reporting
the binding between token and keyslots.
* Allow crypt_token_json_set() API function to create internal token types.
Do not allow unknown fields in internal token objects.
* Print message in cryptsetup that about was aborted if a user did not
answer YES in a query.
Unfinished things & TODO for next releases
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* There will be better documentation and examples.
* There will be some more formal definition of the threat model for integrity
protection. (And a link to some papers discussing integrity protection,
once it is, hopefully, accepted and published.)
* Authenticated encryption will use new algorithms from CAESAR competition
https://competitions.cr.yp.to/caesar-submissions.html.
We plan to use AEGIS and MORUS, as CAESAR finalists.
NOTE: Currently available authenticated modes (GCM, Chacha20-poly1305)
in the kernel have too small 96-bit nonces that are problematic with
randomly generated IVs (the collision probability is not negligible).
* Authenticated encryption do not set encryption for a dm-integrity journal.
While it does not influence data confidentiality or integrity protection,
an attacker can get some more information from data journal or cause that
system will corrupt sectors after journal replay. (That corruption will be
detected though.)
* There are examples of user-defined tokens inside misc/luks2_keyslot_example
directory (like a simple external program that uses libssh to unlock LUKS2
using remote keyfile).
* The python binding (pycryptsetup) contains only basic functionality for LUKS1
(it is not updated for new features) and will be deprecated in version 2.1
in favor of python bindings to the libblockdev library.

121
docs/v2.0.3-ReleaseNotes Normal file
View File

@@ -0,0 +1,121 @@
Cryptsetup 2.0.3 Release Notes
==============================
Stable bug-fix release with new features.
Cryptsetup 2.x version introduces a new on-disk LUKS2 format.
The legacy LUKS (referenced as LUKS1) will be fully supported
forever as well as a traditional and fully backward compatible format.
Please note that authenticated disk encryption, non-cryptographic
data integrity protection (dm-integrity), use of Argon2 Password-Based
Key Derivation Function and the LUKS2 on-disk format itself are new
features and can contain some bugs.
To provide all security features of authenticated encryption, we need
a better nonce-reuse resistant algorithm in the kernel (see note below).
For now, please use authenticated encryption as an experimental feature.
Please do not use LUKS2 without properly configured backup or in
production systems that need to be compatible with older systems.
Changes since version 2.0.2
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Expose interface to unbound LUKS2 keyslots.
Unbound LUKS2 keyslot allows storing a key material that is independent
of master volume key (it is not bound to encrypted data segment).
* New API extensions for unbound keyslots (LUKS2 only)
crypt_keyslot_get_key_size() and crypt_volume_key_get()
These functions allow to get key and key size for unbound keyslots.
* New enum value CRYPT_SLOT_UNBOUND for keyslot status (LUKS2 only).
* Add --unbound keyslot option to the cryptsetup luksAddKey command.
* Add crypt_get_active_integrity_failures() call to get integrity
failure count for dm-integrity devices.
* Add crypt_get_pbkdf_default() function to get per-type PBKDF default
setting.
* Add new flag to crypt_keyslot_add_by_key() to force update device
volume key. This call is mainly intended for a wrapped key change.
* Allow volume key store in a file with cryptsetup.
The --dump-master-key together with --master-key-file allows cryptsetup
to store the binary volume key to a file instead of standard output.
* Add support detached header for cryptsetup-reencrypt command.
* Fix VeraCrypt PIM handling - use proper iterations count formula
for PBKDF2-SHA512 and PBKDF2-Whirlpool used in system volumes.
* Fix cryptsetup tcryptDump for VeraCrypt PIM (support --veracrypt-pim).
* Add --with-default-luks-format configure time option.
(Option to override default LUKS format version.)
* Fix LUKS version conversion for detached (and trimmed) LUKS headers.
* Add luksConvertKey cryptsetup command that converts specific keyslot
from one PBKDF to another.
* Do not allow conversion to LUKS2 if LUKSMETA (external tool metadata)
header is detected.
* More cleanup and hardening of LUKS2 keyslot specific validation options.
Add more checks for cipher validity before writing metadata on-disk.
* Do not allow LUKS1 version downconversion if the header contains tokens.
* Add "paes" family ciphers (AES wrapped key scheme for mainframes)
to allowed ciphers.
Specific wrapped ley configuration logic must be done by 3rd party tool,
LUKS2 stores only keyslot material and allow activation of the device.
* Add support for --check-at-most-once option (kernel 4.17) to veritysetup.
This flag can be dangerous; if you can control underlying device
(you can change its content after it was verified) it will no longer
prevent reading tampered data and also it does not prevent silent
data corruptions that appear after the block was once read.
* Fix return code (EPERM instead of EINVAL) and retry count for bad
passphrase on non-tty input.
* Enable support for FEC decoding in veritysetup to check dm-verity devices
with additional Reed-Solomon code in userspace (verify command).
Unfinished things & TODO for next releases
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* There will be better documentation and examples (planned for 2.0.4).
* There will be some more formal definition of the threat model for integrity
protection. (And a link to some papers discussing integrity protection,
once it is, hopefully, accepted and published.)
* Authenticated encryption will use new algorithms from CAESAR competition
https://competitions.cr.yp.to/caesar-submissions.html.
We plan to use AEGIS and MORUS, as CAESAR finalists.
NOTE: Currently available authenticated modes (GCM, Chacha20-poly1305)
in the kernel have too small 96-bit nonces that are problematic with
randomly generated IVs (the collision probability is not negligible).
* Authenticated encryption do not set encryption for a dm-integrity journal.
While it does not influence data confidentiality or integrity protection,
an attacker can get some more information from data journal or cause that
system will corrupt sectors after journal replay. (That corruption will be
detected though.)
* There are examples of user-defined tokens inside misc/luks2_keyslot_example
directory (like a simple external program that uses libssh to unlock LUKS2
using remote keyfile).
* The python binding (pycryptsetup) contains only basic functionality for LUKS1
(it is not updated for new features) and will be REMOVED in version 2.1
in favor of python bindings to the libblockdev library.
See https://github.com/storaged-project/libblockdev/releases/tag/2.17-1 that
already supports LUKS2 and VeraCrypt devices handling through libcryptsetup.

119
docs/v2.0.4-ReleaseNotes Normal file
View File

@@ -0,0 +1,119 @@
Cryptsetup 2.0.4 Release Notes
==============================
Stable bug-fix release with new features.
Cryptsetup 2.x version introduces a new on-disk LUKS2 format.
The legacy LUKS (referenced as LUKS1) will be fully supported
forever as well as a traditional and fully backward compatible format.
Please note that authenticated disk encryption, non-cryptographic
data integrity protection (dm-integrity), use of Argon2 Password-Based
Key Derivation Function and the LUKS2 on-disk format itself are new
features and can contain some bugs.
To provide all security features of authenticated encryption, we need
a better nonce-reuse resistant algorithm in the kernel (see note below).
For now, please use authenticated encryption as an experimental feature.
Please do not use LUKS2 without properly configured backup or in
production systems that need to be compatible with older systems.
Changes since version 2.0.3
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Use the libblkid (blockid) library to detect foreign signatures
on a device before LUKS format and LUKS2 auto-recovery.
This change fixes an unexpected recovery using the secondary
LUKS2 header after a device was already overwritten with
another format (filesystem or LVM physical volume).
LUKS2 will not recreate a primary header if it detects a valid
foreign signature. In this situation, a user must always
use cryptsetup repair command for the recovery.
Note that libcryptsetup and utilities are now linked to libblkid
as a new dependence.
To compile code without blockid support (strongly discouraged),
use --disable-blkid configure switch.
* Add prompt for format and repair actions in cryptsetup and
integritysetup if foreign signatures are detected on the device
through the blockid library.
After the confirmation, all known signatures are then wiped as
part of the format or repair procedure.
* Print consistent verbose message about keyslot and token numbers.
For keyslot actions: Key slot <number> unlocked/created/removed.
For token actions: Token <number> created/removed.
* Print error, if a non-existent token is tried to be removed.
* Add support for LUKS2 token definition export and import.
The token command now can export/import customized token JSON file
directly from command line. See the man page for more details.
* Add support for new dm-integrity superblock version 2.
* Add an error message when nothing was read from a key file.
* Update cryptsetup man pages, including --type option usage.
* Add a snapshot of LUKS2 format specification to documentation
and accordingly fix supported secondary header offsets.
* Add bundled optimized Argon2 SSE (X86_64 platform) code.
If the bundled Argon2 code is used and the new configure switch
--enable-internal-sse-argon2 option is present, and compiler flags
support required optimization, the code will try to use optimized
and faster variant.
Always use the shared library (--enable-libargon2) if possible.
This option was added because an enterprise distribution
rejected to support the shared Argon2 library and native support
in generic cryptographic libraries is not ready yet.
* Fix compilation with crypto backend for LibreSSL >= 2.7.0.
LibreSSL introduced OpenSSL 1.1.x API functions, so compatibility
wrapper must be commented out.
* Fix on-disk header size calculation for LUKS2 format if a specific
data alignment is requested. Until now, the code used default size
that could be wrong for converted devices.
Unfinished things & TODO for next releases
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Authenticated encryption will use new algorithms from CAESAR competition
https://competitions.cr.yp.to/caesar-submissions.html.
We plan to use AEGIS and MORUS (in kernel 4.18), as CAESAR finalists.
NOTE: Currently available authenticated modes (GCM, Chacha20-poly1305)
in the kernel have too small 96-bit nonces that are problematic with
randomly generated IVs (the collision probability is not negligible).
For more info about LUKS2 authenticated encryption, please see our paper
https://arxiv.org/abs/1807.00309
* Authenticated encryption do not set encryption for a dm-integrity journal.
While it does not influence data confidentiality or integrity protection,
an attacker can get some more information from data journal or cause that
system will corrupt sectors after journal replay. (That corruption will be
detected though.)
* There are examples of user-defined tokens inside misc/luks2_keyslot_example
directory (like a simple external program that uses libssh to unlock LUKS2
using remote keyfile).
* The python binding (pycryptsetup) contains only basic functionality for LUKS1
(it is not updated for new features) and will be REMOVED in version 2.1
in favor of python bindings to the libblockdev library.
See https://github.com/storaged-project/libblockdev/releases that
already supports LUKS2 and VeraCrypt devices handling through libcryptsetup.

102
docs/v2.0.5-ReleaseNotes Normal file
View File

@@ -0,0 +1,102 @@
Cryptsetup 2.0.5 Release Notes
==============================
Stable bug-fix release with new features.
Cryptsetup 2.x version introduces a new on-disk LUKS2 format.
The legacy LUKS (referenced as LUKS1) will be fully supported
forever as well as a traditional and fully backward compatible format.
Please note that authenticated disk encryption, non-cryptographic
data integrity protection (dm-integrity), use of Argon2 Password-Based
Key Derivation Function and the LUKS2 on-disk format itself are new
features and can contain some bugs.
Please do not use LUKS2 without properly configured backup or in
production systems that need to be compatible with older systems.
Changes since version 2.0.4
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Wipe full header areas (including unused) during LUKS format.
Since this version, the whole area up to the data offset is zeroed,
and subsequently, all keyslots areas are wiped with random data.
This ensures that no remaining old data remains in the LUKS header
areas, but it could slow down format operation on some devices.
Previously only first 4k (or 32k for LUKS2) and the used keyslot
was overwritten in the format operation.
* Several fixes to error messages that were unintentionally replaced
in previous versions with a silent exit code.
More descriptive error messages were added, including error
messages if
- a device is unusable (not a block device, no access, etc.),
- a LUKS device is not detected,
- LUKS header load code detects unsupported version,
- a keyslot decryption fails (also happens in the cipher check),
- converting an inactive keyslot.
* Device activation fails if data area overlaps with LUKS header.
* Code now uses explicit_bzero to wipe memory if available
(instead of own implementation).
* Additional VeraCrypt modes are now supported, including Camellia
and Kuznyechik symmetric ciphers (and cipher chains) and Streebog
hash function. These were introduced in a recent VeraCrypt upstream.
Note that Kuznyechik requires out-of-tree kernel module and
Streebog hash function is available only with the gcrypt cryptographic
backend for now.
* Fixes static build for integritysetup if the pwquality library is used.
* Allows passphrase change for unbound keyslots.
* Fixes removed keyslot number in verbose message for luksKillSlot,
luksRemoveKey and erase command.
* Adds blkid scan when attempting to open a plain device and warn the user
about existing device signatures in a ciphertext device.
* Remove LUKS header signature if luksFormat fails to add the first keyslot.
* Remove O_SYNC from device open and use fsync() to speed up
wipe operation considerably.
* Create --master-key-file in luksDump and fail if the file already exists.
* Fixes a bug when LUKS2 authenticated encryption with a detached header
wiped the header device instead of dm-integrity data device area (causing
unnecessary LUKS2 header auto recovery).
Unfinished things & TODO for next releases
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Authenticated encryption should use new algorithms from CAESAR competition
https://competitions.cr.yp.to/caesar-submissions.html.
AEGIS and MORUS are already available in kernel 4.18.
For more info about LUKS2 authenticated encryption, please see our paper
https://arxiv.org/abs/1807.00309
Please note that authenticated encryption is still an experimental feature
and can have performance problems for hish-speed devices and device
with larger IO blocks (like RAID).
* Authenticated encryption do not set encryption for a dm-integrity journal.
While it does not influence data confidentiality or integrity protection,
an attacker can get some more information from data journal or cause that
system will corrupt sectors after journal replay. (That corruption will be
detected though.)
* There are examples of user-defined tokens inside misc/luks2_keyslot_example
directory (like a simple external program that uses libssh to unlock LUKS2
using remote keyfile).
* The python binding (pycryptsetup) contains only basic functionality for LUKS1
(it is not updated for new features) and will be REMOVED in version 2.1
in favor of python bindings to the libblockdev library.
See https://github.com/storaged-project/libblockdev/releases that
already supports LUKS2 and VeraCrypt devices handling through libcryptsetup.

97
docs/v2.0.6-ReleaseNotes Normal file
View File

@@ -0,0 +1,97 @@
Cryptsetup 2.0.6 Release Notes
==============================
Stable bug-fix release.
All users of cryptsetup 2.0.x should upgrade to this version.
Cryptsetup 2.x version introduces a new on-disk LUKS2 format.
The legacy LUKS (referenced as LUKS1) will be fully supported
forever as well as a traditional and fully backward compatible format.
Please note that authenticated disk encryption, non-cryptographic
data integrity protection (dm-integrity), use of Argon2 Password-Based
Key Derivation Function and the LUKS2 on-disk format itself are new
features and can contain some bugs.
Please do not use LUKS2 without properly configured backup or in
production systems that need to be compatible with older systems.
Changes since version 2.0.5
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Fix support of larger metadata areas in LUKS2 header.
This release properly supports all specified metadata areas, as documented
in LUKS2 format description (see docs/on-disk-format-luks2.pdf in archive).
Currently, only default metadata area size is used (in format or convert).
Later cryptsetup versions will allow increasing this metadata area size.
* If AEAD (authenticated encryption) is used, cryptsetup now tries to check
if the requested AEAD algorithm with specified key size is available
in kernel crypto API.
This change avoids formatting a device that cannot be later activated.
For this function, the kernel must be compiled with the
CONFIG_CRYPTO_USER_API_AEAD option enabled.
Note that kernel user crypto API options (CONFIG_CRYPTO_USER_API and
CONFIG_CRYPTO_USER_API_SKCIPHER) are already mandatory for LUKS2.
* Fix setting of integrity no-journal flag.
Now you can store this flag to metadata using --persistent option.
* Fix cryptsetup-reencrypt to not keep temporary reencryption headers
if interrupted during initial password prompt.
* Adds early check to plain and LUKS2 formats to disallow device format
if device size is not aligned to requested sector size.
Previously it was possible, and the device was rejected to activate by
kernel later.
* Fix checking of hash algorithms availability for PBKDF early.
Previously LUKS2 format allowed non-existent hash algorithm with
invalid keyslot preventing the device from activation.
* Allow Adiantum cipher construction (a non-authenticated length-preserving
fast encryption scheme), so it can be used both for data encryption and
keyslot encryption in LUKS1/2 devices.
For benchmark, use:
# cryptsetup benchmark -c xchacha12,aes-adiantum
# cryptsetup benchmark -c xchacha20,aes-adiantum
For LUKS format:
# cryptsetup luksFormat -c xchacha20,aes-adiantum-plain64 -s 256 <device>
The support for Adiantum will be merged in Linux kernel 4.21.
For more info see the paper https://eprint.iacr.org/2018/720.
Unfinished things & TODO for next releases
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Authenticated encryption should use new algorithms from CAESAR competition
https://competitions.cr.yp.to/caesar-submissions.html.
AEGIS and MORUS are already available in kernel 4.18.
For more info about LUKS2 authenticated encryption, please see our paper
https://arxiv.org/abs/1807.00309
Please note that authenticated encryption is still an experimental feature
and can have performance problems for high-speed devices and device
with larger IO blocks (like RAID).
* Authenticated encryption do not set encryption for a dm-integrity journal.
While it does not influence data confidentiality or integrity protection,
an attacker can get some more information from data journal or cause that
system will corrupt sectors after journal replay. (That corruption will be
detected though.)
* There are examples of user-defined tokens inside misc/luks2_keyslot_example
directory (like a simple external program that uses libssh to unlock LUKS2
using remote keyfile).
* The python binding (pycryptsetup) contains only basic functionality for LUKS1
(it is not updated for new features) and will be REMOVED in version 2.1
in favor of python bindings to the libblockdev library.
See https://github.com/storaged-project/libblockdev/releases that
already supports LUKS2 and VeraCrypt devices handling through libcryptsetup.

210
docs/v2.1.0-ReleaseNotes Normal file
View File

@@ -0,0 +1,210 @@
Cryptsetup 2.1.0 Release Notes
==============================
Stable release with new features and bug fixes.
Cryptsetup 2.1 version uses a new on-disk LUKS2 format as the default
LUKS format and increases default LUKS2 header size.
The legacy LUKS (referenced as LUKS1) will be fully supported forever
as well as a traditional and fully backward compatible format.
When upgrading a stable distribution, please use configure option
--with-default-luks-format=LUKS1 to maintain backward compatibility.
This release also switches to OpenSSL as a default cryptographic
backend for LUKS header processing. Use --with-crypto_backend=gcrypt
configure option if you need to preserve legacy libgcrypt backend.
Please do not use LUKS2 without properly configured backup or
in production systems that need to be compatible with older systems.
Changes since version 2.0.6
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* The default for cryptsetup LUKS format action is now LUKS2.
You can use LUKS1 with cryptsetup option --type luks1.
* The default size of the LUKS2 header is increased to 16 MB.
It includes metadata and the area used for binary keyslots;
it means that LUKS header backup is now 16MB in size.
Note, that used keyslot area is much smaller, but this increase
of reserved space allows implementation of later extensions
(like online reencryption).
It is fully compatible with older cryptsetup 2.0.x versions.
If you require to create LUKS2 header with the same size as
in the 2.0.x version, use --offset 8192 option for luksFormat
(units are in 512-bytes sectors; see notes below).
* Cryptsetup now doubles LUKS default key size if XTS mode is used
(XTS mode uses two internal keys). This does not apply if key size
is explicitly specified on the command line and it does not apply
for the plain mode.
This fixes a confusion with AES and 256bit key in XTS mode where
code used AES128 and not AES256 as often expected.
Also, the default keyslot encryption algorithm (if cannot be derived
from data encryption algorithm) is now available as configure
options --with-luks2-keyslot-cipher and --with-luks2-keyslot-keybits.
The default is aes-xts-plain64 with 2 * 256-bits key.
* Default cryptographic backend used for LUKS header processing is now
OpenSSL. For years, OpenSSL provided better performance for PBKDF.
NOTE: Cryptsetup/libcryptsetup supports several cryptographic
library backends. The fully supported are libgcrypt, OpenSSL and
kernel crypto API. FIPS mode extensions are maintained only for
libgcrypt and OpenSSL. Nettle and NSS are usable only for some
subset of algorithms and cannot provide full backward compatibility.
You can always switch to other backends by using a configure switch,
for libgcrypt (compatibility for older distributions) use:
--with-crypto_backend=gcrypt
* The Python bindings are no longer supported and the code was removed
from cryptsetup distribution. Please use the libblockdev project
that already covers most of the libcryptsetup functionality
including LUKS2.
* Cryptsetup now allows using --offset option also for luksFormat.
It means that the specified offset value is used for data offset.
LUKS2 header areas are automatically adjusted according to this value.
(Note units are in 512-byte sectors due to the previous definition
of this option in plain mode.)
This option can replace --align-payload with absolute alignment value.
* Cryptsetup now supports new refresh action (that is the alias for
"open --refresh").
It allows changes of parameters for an active device (like root
device mapping), for example, it can enable or disable TRIM support
on-the-fly.
It is supported for LUKS1, LUKS2, plain and loop-AES devices.
* Integritysetup now supports mode with detached data device through
new --data-device option.
Since kernel 4.18 there is a possibility to specify external data
device for dm-integrity that stores all integrity tags.
* Integritysetup now supports automatic integrity recalculation
through new --integrity-recalculate option.
Linux kernel since version 4.18 supports automatic background
recalculation of integrity tags for dm-integrity.
Other changes and fixes
~~~~~~~~~~~~~~~~~~~~~~~
* Fix for crypt_wipe call to allocate space if the header is backed
by a file. This means that if you use detached header file, it will
now have always the full size after luksFormat, even if only
a few keyslots are used.
* Fixes to offline cryptsetup-reencrypt to preserve LUKS2 keyslots
area sizes after reencryption and fixes for some other issues when
creating temporary reencryption headers.
* Added some FIPS mode workarounds. We cannot (yet) use Argon2 in
FIPS mode, libcryptsetup now fallbacks to use PBKDF2 in FIPS mode.
* Rejects conversion to LUKS1 if PBKDF2 hash algorithms
in keyslots differ.
* The hash setting on command line now applies also to LUKS2 PBKDF2
digest. In previous versions, the LUKS2 key digest used PBKDF2-SHA256
(except for converted headers).
* Allow LUKS2 keyslots area to increase if data offset allows it.
Cryptsetup can fine-tune LUKS2 metadata area sizes through
--luks2-metadata-size=BYTES and --luks2-keyslots-size=BYTES.
Please DO NOT use these low-level options until you need it for
some very specific additional feature.
Also, the code now prints these LUKS2 header area sizes in dump
command.
* For LUKS2, keyslot can use different encryption that data with
new options --keyslot-key-size=BITS and --keyslot-cipher=STRING
in all commands that create new LUKS keyslot.
Please DO NOT use these low-level options until you need it for
some very specific additional feature.
* Code now avoids data flush when reading device status through
device-mapper.
* The Nettle crypto backend and the userspace kernel crypto API
backend were enhanced to allow more available hash functions
(like SHA3 variants).
* Upstream code now does not require libgcrypt-devel
for autoconfigure, because OpenSSL is the default.
The libgcrypt does not use standard pkgconfig detection and
requires specific macro (part of libgcrypt development files)
to be always present during autoconfigure.
With other crypto backends, like OpenSSL, this makes no sense,
so this part of autoconfigure is now optional.
* Cryptsetup now understands new --debug-json option that allows
an additional dump of some JSON information. These are no longer
present in standard debug output because it could contain some
specific LUKS header parameters.
* The luksDump contains the hash algorithm used in Anti-Forensic
function.
* All debug messages are now sent through configured log callback
functions, so an application can easily use own debug messages
handling. In previous versions debug messages were printed directly
to standard output.)
Libcryptsetup API additions
~~~~~~~~~~~~~~~~~~~~~~~~~~~
These new calls are now exported, for details see libcryptsetup.h:
* crypt_init_data_device
* crypt_get_metadata_device_name
functions to init devices with separate metadata and data device
before a format function is called.
* crypt_set_data_offset
sets the data offset for LUKS to the specified value
in 512-byte sectors.
It should replace alignment calculation in LUKS param structures.
* crypt_get_metadata_size
* crypt_set_metadata_size
allows to set/get area sizes in LUKS header
(according to specification).
* crypt_get_default_type
get default compiled-in LUKS type (version).
* crypt_get_pbkdf_type_params
allows to get compiled-in PBKDF parameters.
* crypt_keyslot_set_encryption
* crypt_keyslot_get_encryption
allows to set/get per-keyslot encryption algorithm for LUKS2.
* crypt_keyslot_get_pbkdf
allows to get PBKDF parameters per-keyslot.
and these new defines:
* CRYPT_LOG_DEBUG_JSON (message type for JSON debug)
* CRYPT_DEBUG_JSON (log level for JSON debug)
* CRYPT_ACTIVATE_RECALCULATE (dm-integrity recalculate flag)
* CRYPT_ACTIVATE_REFRESH (new open with refresh flag)
All existing API calls should remain backward compatible.
Unfinished things & TODO for next releases
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Optional authenticated encryption is still an experimental feature
and can have performance problems for high-speed devices and device
with larger IO blocks (like RAID).
* Authenticated encryption does not use encryption for a dm-integrity
journal. While it does not influence data confidentiality or
integrity protection, an attacker can get some more information
from data journal or cause that system will corrupt sectors after
journal replay. (That corruption will be detected though.)
* The LUKS2 metadata area increase is mainly needed for the new online
reencryption as the major feature for the next release.

279
docs/v2.2.0-ReleaseNotes Normal file
View File

@@ -0,0 +1,279 @@
Cryptsetup 2.2.0 Release Notes
==============================
Stable release with new experimental features and bug fixes.
Cryptsetup 2.2 version introduces a new LUKS2 online reencryption
extension that allows reencryption of mounted LUKS2 devices
(device in use) in the background.
Online reencryption is a complex feature. Please be sure you
have a full data backup before using this feature.
Changes since version 2.1.0
~~~~~~~~~~~~~~~~~~~~~~~~~~~
LUKS2 online reencryption
~~~~~~~~~~~~~~~~~~~~~~~~~
The reencryption is intended to provide a reliable way to change
volume key or an algorithm change while the encrypted device is still
in use.
It is based on userspace-only approach (no kernel changes needed)
that uses the device-mapper subsystem to remap active devices on-the-fly
dynamically. The device is split into several segments (encrypted by old
key, new key and so-called hotzone, where reencryption is actively running).
The flexible LUKS2 metadata format is used to store intermediate states
(segment mappings) and both version of keyslots (old and new keys).
Also, it provides a binary area (in the unused keyslot area space)
to provide recovery metadata in the case of unexpected failure during
reencryption. LUKS2 header is during the reencryption marked with
"online-reencryption" keyword. After the reencryption is finished,
this keyword is removed, and the device is backward compatible with all
older cryptsetup tools (that support LUKS2).
The recovery supports three resilience modes:
- checksum: default mode, where individual checksums of ciphertext hotzone
sectors are stored, so the recovery process can detect which sectors were
already reencrypted. It requires that the device sector write is atomic.
- journal: the hotzone is journaled in the binary area
(so the data are written twice)
- none: performance mode; there is no protection
(similar to old offline reencryption)
These resilience modes are not available if reencryption uses data shift.
Note: until we have full documentation (both of the process and metadata),
please refer to Ondrej's slides (some slight details are no longer relevant)
https://okozina.fedorapeople.org/online-disk-reencryption-with-luks2-compact.pdf
The offline reencryption tool (cryptsetup-reencrypt) is still supported
for both LUKS1 and LUKS2 format.
Cryptsetup examples for reencryption
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The reencryption feature is integrated directly into cryptsetup utility
as the new "reencrypt" action (command).
There are three basic modes - to perform reencryption (change of already
existing LUKS2 device), to add encryption to plaintext device and to remove
encryption from a device (decryption).
In all cases, if existing LUKS2 metadata contains information about
the ongoing reencryption process, following reencrypt command continues
with the ongoing reencryption process until it is finished.
You can activate a device with ongoing reencryption as the standard LUKS2
device, but the reencryption process will not continue until the cryptsetup
reencrypt command is issued.
1) Reencryption
~~~~~~~~~~~~~~~
This mode is intended to change any attribute of the data encryption
(change of the volume key, algorithm or sector size).
Note that authenticated encryption is not yet supported.
You can start the reencryption process by specifying a LUKS2 device or with
a detached LUKS2 header.
The code should automatically recognize if the device is in use (and if it
should use online mode of reencryption).
If you do not specify parameters, only volume key is changed
(a new random key is generated).
# cryptsetup reencrypt <device> [--header <hdr>]
You can also start reencryption using active mapped device name:
# cryptsetup reencrypt --active-name <name>
You can also specify the resilience mode (none, checksum, journal) with
--resilience=<mode> option, for checksum mode also the hash algorithm with
--resilience-hash=<alg> (only hash algorithms supported by cryptographic
backend are available).
The maximal size of reencryption hotzone can be limited by
--hotzone-size=<size> option and applies to all reencryption modes.
Note that for checksum and journal mode hotzone size is also limited
by available space in binary keyslot area.
2) Encryption
~~~~~~~~~~~~~
This mode provides a way to encrypt a plaintext device to LUKS2 format.
This option requires reduction of device size (for LUKS2 header) or new
detached header.
# cryptsetup reencrypt <device> --encrypt --reduce-device-size <size>
Or with detached header:
# cryptsetup reencrypt <device> --encrypt --header <hdr>
3) Decryption
~~~~~~~~~~~~~
This mode provides the removal of existing LUKS2 encryption and replacing
a device with plaintext content only.
For now, we support only decryption with a detached header.
# cryptsetup reencrypt <device> --decrypt --header <hdr>
For all three modes, you can split the process to metadata initialization
(prepare keyslots and segments but do not run reencryption yet) and the data
reencryption step by using --init-only option.
Prepares metadata:
# cryptsetup reencrypt --init-only <parameters>
Starts the data processing:
# cryptsetup reencrypt <device>
Please note, that due to the Linux kernel limitation, the encryption or
decryption process cannot be run entirely online - there must be at least
short offline window where operation adds/removes device-mapper crypt (LUKS2) layer.
This step should also include modification of /etc/crypttab and fstab UUIDs,
but it is out of the scope of cryptsetup tools.
Limitations
~~~~~~~~~~~
Most of these limitations will be (hopefully) fixed in next versions.
* Only one active keyslot is supported (all old keyslots will be removed
after reencryption).
* Only block devices are now supported as parameters. As a workaround
for images in a file, please explicitly map a loop device over the image
and use the loop device as the parameter.
* Devices with authenticated encryption are not supported. (Later it will
be limited by the fixed per-sector metadata, per-sector metadata size
cannot be changed without a new device format operation.)
* The reencryption uses userspace crypto library, with fallback to
the kernel (if available). There can be some specific configurations
where the fallback does not provide optimal performance.
* There are no translations of error messages until the final release
(some messages can be rephrased as well).
* The repair command is not finished; the recovery of interrupted
reencryption is made automatically on the first device activation.
* Reencryption triggers too many udev scans on metadata updates (on closing
write enabled file descriptors). This has a negative performance impact on the whole
reencryption and generates excessive I/O load on the system.
New libcryptsetup reencryption API
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The libcryptsetup contains new API calls that are used to setup and
run the reencryption.
Note that there can be some changes in API implementation of these functions
and/or some new function can be introduced in final cryptsetup 2.2 release.
New API symbols (see documentation in libcryptsetup.h)
* struct crypt_params_reencrypt - reencryption parameters
* crypt_reencrypt_init_by_passphrase
* crypt_reencrypt_init_by_keyring
- function to configure LUKS2 metadata for reencryption;
if metadata already exists, it configures the context from this metadata
* crypt_reencrypt
- run the reencryption process (processing the data)
- the optional callback function can be used to interrupt the reencryption
or report the progress.
* crypt_reencrypt_status
- function to query LUKS2 metadata about the reencryption state
Other changes and fixes
~~~~~~~~~~~~~~~~~~~~~~~
* Add optional global serialization lock for memory hard PBKDF.
(The --serialize-memory-hard-pbkdf option in cryptsetup and
CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF in activation flag.)
This is an "ugly" optional workaround for a situation when multiple devices
are being activated in parallel (like systemd crypttab activation).
The system instead of returning ENOMEM (no memory available) starts
out-of-memory (OOM) killer to kill processes randomly.
Until we find a reliable way how to work with memory-hard function
in these situations, cryptsetup provide a way how to serialize memory-hard
unlocking among parallel cryptsetup instances to workaround this problem.
This flag is intended to be used only in very specific situations,
never use it directly :-)
* Abort conversion to LUKS1 with incompatible sector size that is
not supported in LUKS1.
* Report error (-ENOENT) if no LUKS keyslots are available. User can now
distinguish between a wrong passphrase and no keyslot available.
* Fix a possible segfault in detached header handling (double free).
* Add integritysetup support for bitmap mode introduced in Linux kernel 5.2.
Integritysetup now supports --integrity-bitmap-mode option and
--bitmap-sector-per-bit and --bitmap-flush-time commandline options.
In the bitmap operation mode, if a bit in the bitmap is 1, the corresponding
region's data and integrity tags are not synchronized - if the machine
crashes, the unsynchronized regions will be recalculated.
The bitmap mode is faster than the journal mode because we don't have
to write the data twice, but it is also less reliable, because if data
corruption happens when the machine crashes, it may not be detected.
This can be used only for standalone devices, not with dm-crypt.
* The libcryptsetup now keeps all file descriptors to underlying device
open during the whole lifetime of crypt device context to avoid excessive
scanning in udev (udev run scan on every descriptor close).
* The luksDump command now prints more info for reencryption keyslot
(when a device is in-reencryption).
* New --device-size parameter is supported for LUKS2 reencryption.
It may be used to encrypt/reencrypt only the initial part of the data
device if the user is aware that the rest of the device is empty.
Note: This change causes API break since the last rc0 release
(crypt_params_reencrypt structure contains additional field).
* New --resume-only parameter is supported for LUKS2 reencryption.
This flag resumes reencryption process if it exists (not starting
new reencryption).
* The repair command now tries LUKS2 reencryption recovery if needed.
* If reencryption device is a file image, an interactive dialog now
asks if reencryption should be run safely in offline mode
(if autodetection of active devices failed).
* Fix activation through a token where dm-crypt volume key was not
set through keyring (but using old device-mapper table parameter mode).
* Online reencryption can now retain all keyslots (if all passphrases
are provided). Note that keyslot numbers will change in this case.
* Allow volume key file to be used if no LUKS2 keyslots are present.
If all keyslots are removed, LUKS2 has no longer information about
the volume key size (there is only key digest present).
Please use --key-size option to open the device or add a new keyslot
in these cases.
* Print a warning if online reencrypt is called over LUKS1 (not supported).
* Fix TCRYPT KDF failure in FIPS mode.
Some crypto backends support plain hash in FIPS mode but not for PBKDF2.
* Remove FIPS mode restriction for crypt_volume_key_get.
It is an application responsibility to use this API in the proper context.
* Reduce keyslots area size in luksFormat when the header device is too small.
Unless user explicitly asks for keyslots areas size (either via
--luks2-keyslots-size or --offset) reduce keyslots size so that it fits
in metadata device.
* Make resize action accept --device-size parameter (supports units suffix).

36
docs/v2.2.1-ReleaseNotes Normal file
View File

@@ -0,0 +1,36 @@
Cryptsetup 2.2.1 Release Notes
==============================
Stable bug-fix release.
This version contains a fix for a possible data corruption bug
on 32-bit platforms.
All users of cryptsetup 2.1 and 2.2 should upgrade to this version.
Changes since version 2.2.0
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Fix possible data length and IV offset overflow on 32bit architectures.
Other 64-bit architectures are not affected.
The flawed helper function prototypes (introduced in version 2.1.0) used
size_t type, that is 32-bit integer on 32-bit systems.
This patch fixes the problem to properly use 64-bit types.
If the offset parameter addresses devices larger than 2TB, the value
overflows and stores incorrect information in the metadata.
For example, integrity device is smaller than expected size if used
over large disk on 32-bit architecture.
This issue is not present with the standard LUKS1/LUKS2 devices without
integrity extensions.
* Fix a regression in TrueCrypt/VeraCrypt system partition activation.
* Reinstate missing backing file hint for loop device.
If the encrypted device is backed by a file (loopback), cryptsetup now
shows the path to the backing file in passphrase query (as in 1.x version).
* LUKS2 reencryption block size is now aligned to reported optimal IO size.
This change eliminates possible non-aligned device warnings in kernel log
during reencryption.

56
docs/v2.2.2-ReleaseNotes Normal file
View File

@@ -0,0 +1,56 @@
Cryptsetup 2.2.2 Release Notes
==============================
Stable bug-fix release.
All users of cryptsetup 2.1 and 2.2 should upgrade to this version.
Changes since version 2.2.1
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Print error message if a keyslot open failed for a different reason
than wrong passwords (for example there is not enough memory).
Only an exit code was present in this case.
* The progress function switches unit sizes (B/s to GiB/s) according
to the actual speed. Also, it properly calculates speed in the case
of a resumed reencryption operation.
* The --version now supports short -V short option and better handles
common option priorities.
* If cryptsetup wipes signatures during format actions through blkid,
it also prints signature device offsets.
* Compilation now properly uses LTLIBINTL gettext setting in Makefiles.
* Device-mapper backend now supports new DM_GET_TARGET_VERSION ioctl
(available since Linux kernel 5.4).
This should help to detect some kernel/userspace incompatibilities
earlier later after a failed device activation.
* Fixes LUKS2 reencryption on systems without kernel keyring.
* Fixes unlocking prompt for partitions mapped through loop devices
(to properly show the backing device).
* For LUKS2 decryption, a device is now marked for deferred removal
to be automatically deactivated.
* Reencryption now limits hotzone size to be maximal 1 GiB or 1/4
system memory (if lower).
* Reencryption now retains activation flags during online reencryption.
* Reencryption now allows LUKS2 device to activate device right after
LUKS2 encryption is initialized through optional active device name
for cryptsetup reencrypt --encrypt command.
This could help with automated encryption during boot.
NOTE: It means that part of the device is still not encrypted during
activation. Use with care!
* Fixes failure in resize and plain format activation if activated device
size was not aligned to underlying logical device size.
* Fixes conversion to LUKS2 format with detached header if a detached
header size was smaller than the expected aligned LUKS1 header size.

209
docs/v2.3.0-ReleaseNotes Normal file
View File

@@ -0,0 +1,209 @@
Cryptsetup 2.3.0 Release Notes
==============================
Stable release with new experimental features and bug fixes.
Cryptsetup 2.3 version introduces support for BitLocker-compatible
devices (BITLK format). This format is used in Windows systems,
and in combination with a filesystem driver, cryptsetup now provides
native read-write access to BitLocker Full Disk Encryption devices.
The BITLK implementation is based on publicly available information
and it is an independent and opensource implementation that allows
to access this proprietary disk encryption.
Changes since version 2.2.2
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* BITLK (Windows BitLocker compatible) device access
BITLK userspace implementation is based on the master thesis and code
provided by Vojtech Trefny. Also, thanks to other opensource projects
like libbde (that provide alternative approach to decode this format)
we were able to verify cryptsetup implementation.
NOTE: Support for the BITLK device is EXPERIMENTAL and will require
a lot of testing. If you get some error message (mainly unsupported
metadata in the on-disk header), please help us by submitting an issue
to cryptsetup project, so we can fix it. Thank you!
Cryptsetup supports BITLK activation through passphrase or recovery
passphrase for existing devices (BitLocker and Bitlocker to Go).
Activation through TPM, SmartCard, or any other key protector
is not supported. And in some situations, mainly for TPM bind to some
PCR registers, it could be even impossible on Linux in the future.
All metadata (key protectors) are handled read-only, cryptsetup cannot
create or modify them. Except for old devices (created in old Vista
systems), all format variants should be recognized.
Data devices can be activated read-write (followed by mounting through
the proper filesystem driver). To access filesystem on the decrypted device
you need properly installed driver (vfat, NTFS or exFAT).
Foe AES-XTS, activation is supported on all recent Linux kernels.
For older AES-CBC encryption, Linux Kernel version 5.3 is required
(support for special IV variant); for AES-CBC with Elephant diffuser,
Linux Kernel 5.6 is required.
Please note that CBC variants are legacy, and we provide it only
for backward compatibility (to be able to access old drives).
Cryptsetup command now supports the new "bitlk" format and implement dump,
open, status, and close actions.
To activate a BITLK device, use
# cryptsetup open --type bitlk <device> <name>
or with alias
# cryptsetup bitlkOpen <device> <name>
Then with properly installed fs driver (usually NTFS, vfat or exFAT),
you can mount the plaintext device /dev/mapper<name> device as a common
filesystem.
To print metadata information about BITLK device, use
# crypotsetup bitlkDump <device>
To print information about the active device, use
# cryptsetup status <name>
Example (activation of disk image):
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Recent blkid recognizes BitLocker device,just to verity
# blkid bitlocker_xts_ntfs.img
bitlocker_xts_ntfs.img: TYPE="BitLocker"
# Print visible metadata information (on-disk, form the image)
# cryptsetup bitlkDump bitlocker_xts_ntfs.img
Info for BITLK device bitlocker_xts_ntfs.img.
Version: 2
GUID: ...
Created: Wed Oct 23 17:38:15 2019
Description: DESKTOP-xxxxxxx E: 23.10.2019
Cipher name: aes
Cipher mode: xts-plain64
Cipher key: 128 bits
Keyslots:
0: VMK
GUID: ...
Protection: VMK protected with passphrase
Salt: ...
Key data size: 44 [bytes]
1: VMK
GUID: ...
Protection: VMK protected with recovery passphrase
Salt: ...
Key data size: 44 [bytes]
2: FVEK
Key data size: 44 [bytes]
# Activation (recovery passphrase works the same as password)
# cryptsetup bitlkOpen bitlocker_xts_ntfs.img test -v
Enter passphrase for bitlocker_xts_ntfs.img:
Command successful.
# Information about the active device
# cryptsetup status test
/dev/mapper/test is active.
type: BITLK
cipher: aes-xts-plain64
keysize: 128 bits
...
# Plaintext device should now contain decrypted NTFS filesystem
# blkid /dev/mapper/test
/dev/mapper/test: UUID="..." TYPE="ntfs"
# And can be mounted
# mount /dev/mapper/test /mnt/tst
# Deactivation
# umount /mnt/tst
# cryptsetup close test
* Veritysetup now supports activation with additional PKCS7 signature
of root hash through --root-hash-signature option.
The signature uses an in-kernel trusted key to validate the signature
of the root hash during activation. This option requires Linux kernel
5.4 with DM_VERITY_VERIFY_ROOTHASH_SIG option.
Verity devices activated with signature now has a special flag
(with signature) active in device status (veritysetup status <name>).
Usage:
# veritysetup open <data_device> name <hash_device> <root_hash> \
--root-hash-signature=<roothash_p7_sig_file>
* Integritysetup now calculates hash integrity size according to algorithm
instead of requiring an explicit tag size.
Previously, when integritysetup formats a device with hash or
HMAC integrity checksums, it required explicitly tag size entry from
a user (or used default value).
This led to confusion and unexpected shortened tag sizes.
Now, libcryptsetup calculates tag size according to real hash output.
Tag size can also be specified, then it warns if these values differ.
* Integritysetup now supports fixed padding for dm-integrity devices.
There was an in-kernel bug that wasted a lot of space when using metadata
areas for integrity-protected devices if a larger sector size than
512 bytes was used.
This problem affects both stand-alone dm-integrity and also LUKS2 with
authenticated encryption and larger sector size.
The new extension to dm-integrity superblock is needed, so devices
with the new optimal padding cannot be activated on older systems.
Integritysetup/Cryptsetup will use new padding automatically if it
detects the proper kernel. To create a compatible device with
the old padding, use --integrity-legacy-padding option.
* A lot of fixes to online LUKS2 reecryption.
* Add crypt_resume_by_volume_key() function to libcryptsetup.
If a user has a volume key available, the LUKS device can be resumed
directly using the provided volume key.
No keyslot derivation is needed, only the key digest is checked.
* Implement active device suspend info.
Add CRYPT_ACTIVATE_SUSPENDED bit to crypt_get_active_device() flags
that informs the caller that device is suspended (luksSuspend).
* Allow --test-passphrase for a detached header.
Before this fix, we required a data device specified on the command
line even though it was not necessary for the passphrase check.
* Allow --key-file option in legacy offline encryption.
The option was ignored for LUKS1 encryption initialization.
* Export memory safe functions.
To make developing of some extensions simpler, we now export
functions to handle memory with proper wipe on deallocation.
* Fail crypt_keyslot_get_pbkdf for inactive LUKS1 keyslot.
Libcryptsetup API extensions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The libcryptsetup API is backward compatible for existing symbols.
New symbols
crypt_set_compatibility
crypt_get_compatibility;
crypt_resume_by_volume_key;
crypt_activate_by_signed_key;
crypt_safe_alloc;
crypt_safe_realloc;
crypt_safe_free;
crypt_safe_memzero;
New defines introduced :
CRYPT_BITLK "BITLK" - BITLK (BitLocker-compatible mode
CRYPT_COMPAT_LEGACY_INTEGRITY_PADDING - dm-integrity legacy padding
CRYPT_VERITY_ROOT_HASH_SIGNATURE - dm-verity root hash signature
CRYPT_ACTIVATE_SUSPENDED - device suspended info flag

45
docs/v2.3.1-ReleaseNotes Normal file
View File

@@ -0,0 +1,45 @@
Cryptsetup 2.3.1 Release Notes
==============================
Stable bug-fix release.
All users of cryptsetup 2.x should upgrade to this version.
Changes since version 2.3.0
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Support VeraCrypt 128 bytes passwords.
VeraCrypt now allows passwords of maximal length 128 bytes
(compared to legacy TrueCrypt where it was limited by 64 bytes).
* Strip extra newline from BitLocker recovery keys
There might be a trailing newline added by the text editor when
the recovery passphrase was passed using the --key-file option.
* Detect separate libiconv library.
It should fix compilation issues on distributions with iconv
implemented in a separate library.
* Various fixes and workarounds to build on old Linux distributions.
* Split lines with hexadecimal digest printing for large key-sizes.
* Do not wipe the device with no integrity profile.
With --integrity none we performed useless full device wipe.
* Workaround for dm-integrity kernel table bug.
Some kernels show an invalid dm-integrity mapping table
if superblock contains the "recalculate" bit. This causes
integritysetup to not recognize the dm-integrity device.
Integritysetup now specifies kernel options such a way that
even on unpatched kernels mapping table is correct.
* Print error message if LUKS1 keyslot cannot be processed.
If the crypto backend is missing support for hash algorithms
used in PBKDF2, the error message was not visible.
* Properly align LUKS2 keyslots area on conversion.
If the LUKS1 payload offset (data offset) is not aligned
to 4 KiB boundary, new LUKS2 keyslots area in now aligned properly.
* Validate LUKS2 earlier on conversion to not corrupt the device
if binary keyslots areas metadata are not correct.

42
docs/v2.3.2-ReleaseNotes Normal file
View File

@@ -0,0 +1,42 @@
Cryptsetup 2.3.2 Release Notes
==============================
Stable bug-fix release.
All users of cryptsetup 2.x should upgrade to this version.
Changes since version 2.3.1
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Support compilation with json-c library version 0.14.
* Update FAQ document for some LUKS2 specific information.
* Add option to dump content of LUKS2 unbound keyslot:
cryptsetup luksDump --unbound -S <slot> <device>
or optionally with --master-key-file option.
The slot number --key-slot (-S) option is mandatory here.
An unbound keyslot store a key is that is not assigned to data
area on disk (LUKS2 allows to store arbitrary keys).
* Rephrase some error messages and remove redundant end-of-lines.
* Add support for discards (TRIM) for standalone dm-integrity devices.
Linux kernel 5.7 adds support for optional discard/TRIM operation
over dm-integrity devices.
It is now supported through --allow-discards integritysetup option.
Note you need to add this flag in all activation calls.
Note that this option cannot be used for LUKS2 authenticated encryption
(that uses dm-integrity for storing additional per-sector metadata).
* Fix cryptsetup-reencrypt to work on devices that do not allow
direct-io device access.
* Fix a crash in the BitLocker-compatible code error path.
* Fix Veracrypt compatible support for longer (>64 bytes) passphrases.
It allows some older images to be correctly opened again.
The issue was introduced in version 2.3.1.

42
docs/v2.3.3-ReleaseNotes Normal file
View File

@@ -0,0 +1,42 @@
Cryptsetup 2.3.3 Release Notes
==============================
Stable bug-fix release.
All users of cryptsetup 2.x should upgrade to this version.
Changes since version 2.3.2
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Fix BitLocker compatible device access that uses native 4kB sectors.
Devices formatted with storage that natively support 4096-bytes
sectors can also use this sector size for encryption units.
* Support large IV count (--iv-large-sectors) cryptsetup option
for plain device mapping.
The large IV count is supported in dm-crypt together with larger
sector encryption. It counts the Initialization Vector (IV) in
a larger sector size instead of 512-bytes sectors.
This option does not have any performance or security impact,
but it can be used for accessing incompatible existing disk images
from other systems.
Only open action with plain device type and sector size > 512 bytes
are supported.
* Fix a memory leak in BitLocker compatible handling.
* Allow EBOIV (Initialization Vector algorithm) use.
The EBOIV initialization vector is intended to be used internally
with BitLocker devices (for CBC mode). It can now be used also
outside of the BitLocker compatible code.
* Require both keyslot cipher and key size options.
If these LUKS2 keyslot parameters were not specified together,
cryptsetup silently failed.
* Update to man pages and FAQ.

112
docs/v2.3.4-ReleaseNotes Normal file
View File

@@ -0,0 +1,112 @@
Cryptsetup 2.3.4 Release Notes
==============================
Stable bug-fix release with a security fix (32-bit only).
All users of cryptsetup 2.2.x and later should upgrade to this version.
Changes since version 2.3.3
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Fix a possible out-of-bounds memory write while validating LUKS2 data
segments metadata (CVE-2020-14382).
This problem can be triggered only on 32-bit builds (64-bit systems
are not affected).
LUKS2 format validation code contains a bug in segments validation code
where the code does not check for possible overflow on memory allocation.
Due to the bug, the libcryptsetup can be tricked to expect such allocation
was successful. Later it may read data from image crafted by an attacker and
actually write such data beyond allocated memory.
The bug was introduced in cryptsetup 2.2.0. All later releases until 2.3.4
are affected.
If you only backport the fix for this CVE, these master branch git commits
should be backported:
52f5cb8cedf22fb3e14c744814ec8af7614146c7
46ee71edcd13e1dad50815ad65c28779aa6f7503
752c9a52798f11d3b765b673ebaa3058eb25316e
Thanks to Tobias Stoeckmann for discovering this issue.
* Ignore reported optimal IO size if not aligned to minimal page size.
Some USB enclosures report bogus block device topology (see lsblk -t) that
prevents LUKS2 format with 4k sector size (reported values are not correctly
aligned). The code now ignores such values and uses the default alignment.
* Added support for new no_read/write_wrokqueue dm-crypt options (kernel 5.9).
These performance options, introduced in kernel 5.9, configure dm-crypt
to bypass read or write workqueues and run encryption synchronously.
Use --perf-no_read_workqueue or --perf-no_write_workqueue cryptsetup arguments
to use these dm-crypt flags.
These options are available only for low-level dm-crypt performance tuning,
use only if you need a change to default dm-crypt behavior.
For LUKS2, these flags can be persistently stored in metadata with
the --persistent option.
* Added support panic_on_corruption option for dm-verity devices (kernel 5.9).
Veritysetup now supports --panic-on-corruption argument that configures
the dm-verity device to panics kernel if a corruption is detected.
This option is intended for specific configurations, do not use it in
standard configurations.
* Support --master-key-file option for online LUKS2 reencryption
This can be used for reencryption of devices that uses protected key AES cipher
on some mainframes crypto accelerators.
* Always return EEXIST error code if a device already exists.
Some libcryptsetup functions (activate_by*) now return EEXIST error code,
so the caller can distinguish that call fails because some parallel process
already activated the device.
Previously all fails returned EINVAL (invalid value).
* Fix a problem in integritysetup if a hash algorithm has dash in the name.
If users want to use blake2b/blake2s, the kernel algorithm name includes
a dash (like "blake2s-256").
Theses algorithms can now be used for integritysetup devices.
* Fix crypto backend to properly handle ECB mode.
Even though it should never be used, it should still work for testing :)
This fixes a bug introduced in cryptsetup version 2.3.2.
* TrueCrypt/VeraCrypt compatible mode now supports the activation of devices
with a larger sector.
TrueCrypt/VeraCrypt always uses 512-byte sector for encryption, but for devices
with a larger native sector, it stores this value in the header.
This patch allows activation of such devices, basically ignoring
the mentioned sector size.
* LUKS2: Do not create excessively large headers.
When creating a LUKS2 header with a specified --offset larger than
the LUKS2 header size, do not create a larger file than needed.
* Fix unspecified sector size for BitLocker compatible mode.
Some BitLocker devices can contain zeroed sector size in the header.
In this case, the 512-byte sector should be used.
The bug was introduced in version 2.3.3.
* Fix reading key data size in metadata for BitLocker compatible mode.
Such devices with an unexpected entry in metadata can now be activated.
Thanks to all users reporting these problems, BitLocker metadata documentation
is not publicly available, and we depend only on these reports.
* Fix typos in documentation.

181
docs/v2.3.5-ReleaseNotes Normal file
View File

@@ -0,0 +1,181 @@
Cryptsetup 2.3.5 Release Notes
==============================
Stable bug-fix release with minor extensions.
All users of cryptsetup 2.x and later should upgrade to this version.
Changes since version 2.3.4
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Fix partial reads of passphrase from an interactive terminal.
Some stable kernels (5.3.11) started to return buffer from a terminal
in parts of maximal size 64 bytes.
This breaks the reading of passphrases longer than 64 characters
entered through an interactive terminal. The change is already fixed
in later kernel releases, but tools now support such partial read from
terminal properly.
* Fix maximal length of password entered through a terminal.
Now the maximal interactive passphrase length is exactly
512 characters (not 511).
* integritysetup: support new dm-integrity HMAC recalculation options.
In older kernels (since version 4.19), an attacker can force
an automatic recalculation of integrity tags by modifying
the dm-integrity superblock.
This is a problem with a keyed algorithms (HMAC), where it expects
nobody can trigger such recalculation without the key.
(Automatic recalculation will start after the next activation.)
Note that dm-integrity in standalone mode was *not* supposed
to provide cryptographic data integrity protection.
Despite that, we try to keep the system secure if keyed algorithms
are used.
Thank Daniel Glöckner for the original report of this problem.
Authenticated encryption that provides data integrity protection (in
combination with dm-crypt and LUKS2) is not affected by this problem.
The fix in the kernel for this problem contains two parts.
Firstly, the dm-integrity kernel module disables integrity
recalculation if keyed algorithms (HMAC) are used.
This change is included in long-term stable kernels.
Secondly, since the kernel version 5.11, dm-integrity introduces
modified protection where a journal-integrity algorithm guards
superblock; also, journal sections are protected. An attacker cannot
copy sectors from one journal section to another, and the superblock
also contains salt to prevent header replacement from another device.
If you want to protect data with HMAC, you should always also use HMAC
for --journal-integrity. Keys can be independent.
If HMAC is used for data but not for the journal, the recalculation
option is disabled.
If you need to use (insecure) backward compatibility implementation,
two new integritysetup options are introduced:
- Use --integrity-legacy-recalc (instead of --integrity-recalc)
to allow recalculation on legacy devices.
- Use --integrity-legacy-hmac in format action to force old insecure
HMAC format.
Libcryptsetup API also introduces flags
CRYPT_COMPAT_LEGACY_INTEGRITY_HMAC and
CRYPT_COMPAT_LEGACY_INTEGRITY_RECALC
to set these through crypt_set_compatibility() call.
* integritysetup: display of recalculating sector in dump command.
* veritysetup: fix verity FEC if stored in the same image with hashes.
Optional FEC (Forward Error Correction) data should cover the whole
data area, hashes (Merkle tree), and optionally additional metadata
(located after hash area).
Unfortunately, if FEC data is stored in the same file as hash,
the calculation wrongly used the whole file size, thus overlaps with
the FEC area itself. This produced unusable and too large FEC data.
There is no problem if the FEC image is a separate image.
The problem is now fixed, introducing FEC blocks calculation as:
- If the hash device is in a separate image, metadata covers the
whole rest of the image after the hash area. (Unchanged behavior.)
- If hash and FEC device is in the image, metadata ends on the FEC
area offset.
Note: there is also a fix for FEC in the dm-verity kernel (on the way
to stable kernels) that fixes error correction with larger RS roots.
* veritysetup: run FEC repair check even if root hash fails.
Note: The userspace FEC verify command reports are only informational
for now. Code does not check verity hash after FEC recovery in
userspace. The Reed-Solomon decoder can then report the possibility
that it fixed data even if parity is too damaged.
This will be fixed in the next major release.
* veritysetup: do not process hash image if hash area is empty.
Sometimes the device is so small that there is only a root hash
needed, and the hash area is not used.
Also, the size of the hash image is not increased for hash block
alignment in this case.
* veritysetup: store verity hash algorithm in superblock in lowercase.
Otherwise, the kernel could refuse the activation of the device.
* bitlk: fix a crash if the device disappears during BitLocker scan.
* bitlk: show a better error when trying to open an NTFS device.
Both BitLocker version 1 and NTFS have the same signature.
If a user opens an NTFS device without BitLocker, it now correctly
informs that it is not a BITLK device.
* bitlk: add support for startup key protected VMKs.
The startup key can be provided in --key-file option for open command.
* Fix LUKS1 repair code (regression since version 1.7.x).
We cannot trust possibly broken keyslots metadata in repair, so the
code recalculates them instead.
This makes the repair code working again when the master boot record
signature overwrites the LUKS header.
* Fix luksKeyChange for LUKS2 with assigned tokens.
The token references are now correctly assigned to the new keyslot
number.
* Fix cryptsetup resize using LUKS2 tokens.
Code needlessly asked for passphrase even though volume key was
already unlocked via LUKS2 token.
* Print a visible error if device resize is not supported.
* Add error message when suspending wrong non-LUKS device.
* Fix default XTS mode key size in reencryption.
The same luksFormat logic (double key size because XTS uses two keys)
is applied in the reencryption code.
* Rephrase missing locking directory warning and move it to debug level.
The system should later provide a safe transition to tempdir
configuration, so creating locking directory inside libcryptsetup
call is safe.
* Many fixes for the use of cipher_null (empty debug cipher).
Support for this empty cipher was intended as a debug feature and for
measuring performance overhead. Unfortunately, many systems started to
use it as an "empty shell" for LUKS (to enable encryption later).
This use is very dangerous and it creates a false sense of security.
Anyway, to not break such systems, we try to support these
configurations.
Using cipher_null in any production system is strongly discouraged!
Fixes include:
- allow LUKS resume for a device with cipher_null.
- do not upload key in keyring when data cipher is null.
- switch to default cipher when reencrypting cipher_null device.
- replace possible bogus cipher_null keyslots before reencryption.
- fix broken detection of null cipher in LUKS2.
cipher_null is no longer possible to be used in keyslot encryption
in LUKS2, it can be used only for data for debugging purposes.
* Fixes for libpasswdqc 2.0.x (optional passphrase quality check).
* Fixes for problems discovered by various tools for code analysis.
Fixes include a rework of libpopt command line option string leaks.
* Various fixes to man pages.

56
docs/v2.3.6-ReleaseNotes Normal file
View File

@@ -0,0 +1,56 @@
Cryptsetup 2.3.6 Release Notes
==============================
Stable bug-fix release with minor extensions.
All users of cryptsetup 2.x and later should upgrade to this version.
Changes since version 2.3.5
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* integritysetup: Fix possible dm-integrity mapping table truncation.
While integritysetup in standalone mode (no encryption) was not
designed to provide keyed (and cryptographically strong) data
integrity protection, some options can use such algorithms (HMAC).
If a key is used, it is directly sent to the kernel dm-integrity as
a mapping table option (no key derivation is performed).
For HMAC, such a key could be quite long (up to 4096 bytes in
integritysetup CLI).
Unfortunately, due to fixed buffers and not correctly checking string
truncation, some parameter combinations could cause truncation
of the dm-integrity mapping table.
In most cases, the table was rejected by the kernel.
The worst possible case was key truncation for HMAC options
(internal_hash and journal_mac dm-integrity table options).
This release fixes possible truncation and also adds more sanity
checks to reject truncated options.
Also, integritysetup now mentions maximal allowed key size
in --help output.
For old standalone dm-integrity devices where the key length was
truncated, you have to modify (shorten) --integrity-key-size
resp. --journal-integrity-key-size option now.
This bug is _not_ present for dm-crypt/LUKS, LUKS2 (including
integrity protection), or dm-verity devices; it affects only
standalone dm-integrity with HMAC integrity protection.
* cryptsetup: Backup header can be used to activate TCRYPT device.
Use --header option to specify the header.
* cryptsetup: Avoid LUKS2 decryption without detached header.
This feature will be added later and is currently not supported.
* Additional fixes and workarounds for common warnings produced
by some static analysis tools (like gcc-11 analyzer) and additional
code hardening.
* Fix standalone libintl detection for compiled tests.
* Add Blake2b and Blake2s hash support for crypto backends.
Kernel and gcrypt crypto backend support all variants.
OpenSSL supports only Blake2b-512 and Blake2s-256.
Crypto backend supports kernel notation e.g. "blake2b-512".

95
docs/v2.3.7-ReleaseNotes Normal file
View File

@@ -0,0 +1,95 @@
Cryptsetup 2.3.7 Release Notes
==============================
Stable security bug-fix release that fixes CVE-2021-4122.
All users of cryptsetup 2.3.x must upgrade to this version.
Changes since version 2.3.6
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Fix possible attacks against data confidentiality through LUKS2 online
reencryption extension crash recovery (CVE-2021-4122).
An attacker can modify on-disk metadata to simulate decryption in
progress with crashed (unfinished) reencryption step and persistently
decrypt part of the LUKS device.
This attack requires repeated physical access to the LUKS device but
no knowledge of user passphrases.
The decryption step is performed after a valid user activates
the device with a correct passphrase and modified metadata.
There are no visible warnings for the user that such recovery happened
(except using the luksDump command). The attack can also be reversed
afterward (simulating crashed encryption from a plaintext) with
possible modification of revealed plaintext.
The size of possible decrypted data depends on configured LUKS2 header
size (metadata size is configurable for LUKS2).
With the default parameters (16 MiB LUKS2 header) and only one
allocated keyslot (512 bit key for AES-XTS), simulated decryption with
checksum resilience SHA1 (20 bytes checksum for 4096-byte blocks),
the maximal decrypted size can be over 3GiB.
The attack is not applicable to LUKS1 format, but the attacker can
update metadata in place to LUKS2 format as an additional step.
For such a converted LUKS2 header, the keyslot area is limited to
decrypted size (with SHA1 checksums) over 300 MiB.
The issue is present in all cryptsetup releases since 2.2.0.
Versions 1.x, 2.0.x, and 2.1.x are not affected, as these do not
contain LUKS2 reencryption extension.
The problem was caused by reusing a mechanism designed for actual
reencryption operation without reassessing the security impact for new
encryption and decryption operations. While the reencryption requires
calculating and verifying both key digests, no digest was needed to
initiate decryption recovery if the destination is plaintext (no
encryption key). Also, some metadata (like encryption cipher) is not
protected, and an attacker could change it. Note that LUKS2 protects
visible metadata only when a random change occurs. It does not protect
against intentional modification but such modification must not cause
a violation of data confidentiality.
The fix introduces additional digest protection of reencryption
metadata. The digest is calculated from known keys and critical
reencryption metadata. Now an attacker cannot create correct metadata
digest without knowledge of a passphrase for used keyslots.
For more details, see LUKS2 On-Disk Format Specification version 1.1.0.
The former reencryption operation (without the additional digest) is no
longer supported (reencryption with the digest is not backward
compatible). You need to finish in-progress reencryption before
updating to new packages. The alternative approach is to perform
a repair command from the updated package to recalculate reencryption
digest and fix metadata.
The reencryption repair operation always require a user passphrase.
WARNING: Devices with older reencryption in progress can be no longer
activated without performing the action mentioned above.
Encryption in progress can be detected by running the luksDump command
(output includes reencrypt keyslot with reencryption parameters). Also,
during the active reencryption, no keyslot operations are available
(change of passphrases, etc.).
The issue was found by Milan Broz as cryptsetup maintainer.
Other changes
~~~~~~~~~~~~~
* Add configure option --disable-luks2-reencryption to completely disable
LUKS2 reencryption code.
When used, the libcryptsetup library can read metadata with
reencryption code, but all reencryption API calls and cryptsetup
reencrypt commands are disabled.
Devices with online reencryption in progress cannot be activated.
This option can cause some incompatibilities. Please use with care.
* Improve internal metadata validation code for reencryption metadata.
* Add updated documentation for LUKS2 On-Disk Format Specification
version 1.1.0 (with reencryption extension description and updated
metadata description). See docs/on-disk-format-luks2.pdf or online
version in https://gitlab.com/cryptsetup/LUKS2-docs repository.

View File

@@ -1,71 +0,0 @@
SUBDIRS = crypto_backend luks1 loopaes verity tcrypt
moduledir = $(libdir)/cryptsetup
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libcryptsetup.pc
AM_CPPFLAGS = -include config.h \
-I$(top_srcdir) \
-I$(top_srcdir)/lib/crypto_backend \
-I$(top_srcdir)/lib/luks1 \
-I$(top_srcdir)/lib/loopaes \
-I$(top_srcdir)/lib/verity \
-I$(top_srcdir)/lib/tcrypt \
-DDATADIR=\""$(datadir)"\" \
-DLIBDIR=\""$(libdir)"\" \
-DPREFIX=\""$(prefix)"\" \
-DSYSCONFDIR=\""$(sysconfdir)"\" \
-DVERSION=\""$(VERSION)"\"
lib_LTLIBRARIES = libcryptsetup.la
common_ldadd = \
crypto_backend/libcrypto_backend.la \
luks1/libluks1.la \
loopaes/libloopaes.la \
verity/libverity.la \
tcrypt/libtcrypt.la
libcryptsetup_la_DEPENDENCIES = $(common_ldadd) libcryptsetup.sym
libcryptsetup_la_LDFLAGS = $(AM_LDFLAGS) -no-undefined \
-Wl,--version-script=$(top_srcdir)/lib/libcryptsetup.sym \
-version-info @LIBCRYPTSETUP_VERSION_INFO@
libcryptsetup_la_CFLAGS = -Wall $(AM_CFLAGS) @CRYPTO_CFLAGS@
libcryptsetup_la_LIBADD = \
@UUID_LIBS@ \
@DEVMAPPER_LIBS@ \
@CRYPTO_LIBS@ \
@FIPSCHECK_LIBS@ \
$(common_ldadd)
libcryptsetup_la_SOURCES = \
setup.c \
internal.h \
bitops.h \
nls.h \
libcryptsetup.h \
utils.c \
utils_benchmark.c \
utils_crypt.c \
utils_crypt.h \
utils_loop.c \
utils_loop.h \
utils_devpath.c \
utils_wipe.c \
utils_fips.c \
utils_fips.h \
utils_device.c \
libdevmapper.c \
utils_dm.h \
volumekey.c \
random.c \
crypt_plain.c
include_HEADERS = libcryptsetup.h
EXTRA_DIST = libcryptsetup.pc.in libcryptsetup.sym

116
lib/Makemodule.am Normal file
View File

@@ -0,0 +1,116 @@
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = lib/libcryptsetup.pc
lib_LTLIBRARIES = libcryptsetup.la
noinst_LTLIBRARIES += libutils_io.la
include_HEADERS = lib/libcryptsetup.h
EXTRA_DIST += lib/libcryptsetup.pc.in lib/libcryptsetup.sym
libutils_io_la_CFLAGS = $(AM_CFLAGS)
libutils_io_la_SOURCES = \
lib/utils_io.c \
lib/utils_io.h
libcryptsetup_la_CPPFLAGS = $(AM_CPPFLAGS) \
-I $(top_srcdir)/lib/crypto_backend \
-I $(top_srcdir)/lib/luks1 \
-I $(top_srcdir)/lib/luks2 \
-I $(top_srcdir)/lib/loopaes \
-I $(top_srcdir)/lib/verity \
-I $(top_srcdir)/lib/tcrypt \
-I $(top_srcdir)/lib/integrity \
-I $(top_srcdir)/lib/bitlk
libcryptsetup_la_DEPENDENCIES = libutils_io.la libcrypto_backend.la lib/libcryptsetup.sym
libcryptsetup_la_LDFLAGS = $(AM_LDFLAGS) -no-undefined \
-Wl,--version-script=$(top_srcdir)/lib/libcryptsetup.sym \
-version-info @LIBCRYPTSETUP_VERSION_INFO@
libcryptsetup_la_CFLAGS = $(AM_CFLAGS) @CRYPTO_CFLAGS@
libcryptsetup_la_LIBADD = \
@UUID_LIBS@ \
@DEVMAPPER_LIBS@ \
@CRYPTO_LIBS@ \
@LIBARGON2_LIBS@ \
@JSON_C_LIBS@ \
@BLKID_LIBS@ \
$(LTLIBICONV) \
libcrypto_backend.la \
libutils_io.la
libcryptsetup_la_SOURCES = \
lib/setup.c \
lib/internal.h \
lib/bitops.h \
lib/nls.h \
lib/libcryptsetup.h \
lib/utils.c \
lib/utils_benchmark.c \
lib/utils_crypt.c \
lib/utils_crypt.h \
lib/utils_loop.c \
lib/utils_loop.h \
lib/utils_devpath.c \
lib/utils_wipe.c \
lib/utils_fips.c \
lib/utils_fips.h \
lib/utils_device.c \
lib/utils_keyring.c \
lib/utils_keyring.h \
lib/utils_device_locking.c \
lib/utils_device_locking.h \
lib/utils_pbkdf.c \
lib/utils_safe_memory.c \
lib/utils_storage_wrappers.c \
lib/utils_storage_wrappers.h \
lib/libdevmapper.c \
lib/utils_dm.h \
lib/volumekey.c \
lib/random.c \
lib/crypt_plain.c \
lib/base64.h \
lib/base64.c \
lib/integrity/integrity.h \
lib/integrity/integrity.c \
lib/loopaes/loopaes.h \
lib/loopaes/loopaes.c \
lib/tcrypt/tcrypt.h \
lib/tcrypt/tcrypt.c \
lib/luks1/af.h \
lib/luks1/af.c \
lib/luks1/keyencryption.c \
lib/luks1/keymanage.c \
lib/luks1/luks.h \
lib/verity/verity_hash.c \
lib/verity/verity_fec.c \
lib/verity/verity.c \
lib/verity/verity.h \
lib/verity/rs_encode_char.c \
lib/verity/rs_decode_char.c \
lib/verity/rs.h \
lib/luks2/luks2_disk_metadata.c \
lib/luks2/luks2_json_format.c \
lib/luks2/luks2_json_metadata.c \
lib/luks2/luks2_luks1_convert.c \
lib/luks2/luks2_digest.c \
lib/luks2/luks2_digest_pbkdf2.c \
lib/luks2/luks2_keyslot.c \
lib/luks2/luks2_keyslot_luks2.c \
lib/luks2/luks2_keyslot_reenc.c \
lib/luks2/luks2_reencrypt.c \
lib/luks2/luks2_reencrypt_digest.c \
lib/luks2/luks2_segment.c \
lib/luks2/luks2_token_keyring.c \
lib/luks2/luks2_token.c \
lib/luks2/luks2_internal.h \
lib/luks2/luks2.h \
lib/utils_blkid.c \
lib/utils_blkid.h \
lib/bitlk/bitlk.h \
lib/bitlk/bitlk.c

605
lib/base64.c Normal file
View File

@@ -0,0 +1,605 @@
/* base64.c -- Encode binary data using printable characters.
Copyright (C) 1999-2001, 2004-2006, 2009-2019 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <https://www.gnu.org/licenses/>. */
/* Written by Simon Josefsson. Partially adapted from GNU MailUtils
* (mailbox/filter_trans.c, as of 2004-11-28). Improved by review
* from Paul Eggert, Bruno Haible, and Stepan Kasal.
*
* See also RFC 4648 <https://www.ietf.org/rfc/rfc4648.txt>.
*
* Be careful with error checking. Here is how you would typically
* use these functions:
*
* bool ok = base64_decode_alloc (in, inlen, &out, &outlen);
* if (!ok)
* FAIL: input was not valid base64
* if (out == NULL)
* FAIL: memory allocation error
* OK: data in OUT/OUTLEN
*
* size_t outlen = base64_encode_alloc (in, inlen, &out);
* if (out == NULL && outlen == 0 && inlen != 0)
* FAIL: input too long
* if (out == NULL)
* FAIL: memory allocation error
* OK: data in OUT/OUTLEN.
*
*/
#include <config.h>
/* Get prototype. */
#include "base64.h"
/* Get malloc. */
#include <stdlib.h>
/* Get UCHAR_MAX. */
#include <limits.h>
#include <string.h>
/* C89 compliant way to cast 'char' to 'unsigned char'. */
static unsigned char
to_uchar (char ch)
{
return ch;
}
static const char b64c[64] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/* Base64 encode IN array of size INLEN into OUT array. OUT needs
to be of length >= BASE64_LENGTH(INLEN), and INLEN needs to be
a multiple of 3. */
static void
base64_encode_fast (const char *restrict in, size_t inlen, char *restrict out)
{
while (inlen)
{
*out++ = b64c[(to_uchar (in[0]) >> 2) & 0x3f];
*out++ = b64c[((to_uchar (in[0]) << 4) + (to_uchar (in[1]) >> 4)) & 0x3f];
*out++ = b64c[((to_uchar (in[1]) << 2) + (to_uchar (in[2]) >> 6)) & 0x3f];
*out++ = b64c[to_uchar (in[2]) & 0x3f];
inlen -= 3;
in += 3;
}
}
/* Base64 encode IN array of size INLEN into OUT array of size OUTLEN.
If OUTLEN is less than BASE64_LENGTH(INLEN), write as many bytes as
possible. If OUTLEN is larger than BASE64_LENGTH(INLEN), also zero
terminate the output buffer. */
void
base64_encode (const char *restrict in, size_t inlen,
char *restrict out, size_t outlen)
{
/* Note this outlen constraint can be enforced at compile time.
I.E. that the output buffer is exactly large enough to hold
the encoded inlen bytes. The inlen constraints (of corresponding
to outlen, and being a multiple of 3) can change at runtime
at the end of input. However the common case when reading
large inputs is to have both constraints satisfied, so we depend
on both in base_encode_fast(). */
if (outlen % 4 == 0 && inlen == outlen / 4 * 3)
{
base64_encode_fast (in, inlen, out);
return;
}
while (inlen && outlen)
{
*out++ = b64c[(to_uchar (in[0]) >> 2) & 0x3f];
if (!--outlen)
break;
*out++ = b64c[((to_uchar (in[0]) << 4)
+ (--inlen ? to_uchar (in[1]) >> 4 : 0))
& 0x3f];
if (!--outlen)
break;
*out++ =
(inlen
? b64c[((to_uchar (in[1]) << 2)
+ (--inlen ? to_uchar (in[2]) >> 6 : 0))
& 0x3f]
: '=');
if (!--outlen)
break;
*out++ = inlen ? b64c[to_uchar (in[2]) & 0x3f] : '=';
if (!--outlen)
break;
if (inlen)
inlen--;
if (inlen)
in += 3;
}
if (outlen)
*out = '\0';
}
/* Allocate a buffer and store zero terminated base64 encoded data
from array IN of size INLEN, returning BASE64_LENGTH(INLEN), i.e.,
the length of the encoded data, excluding the terminating zero. On
return, the OUT variable will hold a pointer to newly allocated
memory that must be deallocated by the caller. If output string
length would overflow, 0 is returned and OUT is set to NULL. If
memory allocation failed, OUT is set to NULL, and the return value
indicates length of the requested memory block, i.e.,
BASE64_LENGTH(inlen) + 1. */
size_t
base64_encode_alloc (const char *in, size_t inlen, char **out)
{
size_t outlen = 1 + BASE64_LENGTH (inlen);
/* Check for overflow in outlen computation.
*
* If there is no overflow, outlen >= inlen.
*
* If the operation (inlen + 2) overflows then it yields at most +1, so
* outlen is 0.
*
* If the multiplication overflows, we lose at least half of the
* correct value, so the result is < ((inlen + 2) / 3) * 2, which is
* less than (inlen + 2) * 0.66667, which is less than inlen as soon as
* (inlen > 4).
*/
if (inlen > outlen)
{
*out = NULL;
return 0;
}
*out = malloc (outlen);
if (!*out)
return outlen;
base64_encode (in, inlen, *out, outlen);
return outlen - 1;
}
/* With this approach this file works independent of the charset used
(think EBCDIC). However, it does assume that the characters in the
Base64 alphabet (A-Za-z0-9+/) are encoded in 0..255. POSIX
1003.1-2001 require that char and unsigned char are 8-bit
quantities, though, taking care of that problem. But this may be a
potential problem on non-POSIX C99 platforms.
IBM C V6 for AIX mishandles "#define B64(x) ...'x'...", so use "_"
as the formal parameter rather than "x". */
#define B64(_) \
((_) == 'A' ? 0 \
: (_) == 'B' ? 1 \
: (_) == 'C' ? 2 \
: (_) == 'D' ? 3 \
: (_) == 'E' ? 4 \
: (_) == 'F' ? 5 \
: (_) == 'G' ? 6 \
: (_) == 'H' ? 7 \
: (_) == 'I' ? 8 \
: (_) == 'J' ? 9 \
: (_) == 'K' ? 10 \
: (_) == 'L' ? 11 \
: (_) == 'M' ? 12 \
: (_) == 'N' ? 13 \
: (_) == 'O' ? 14 \
: (_) == 'P' ? 15 \
: (_) == 'Q' ? 16 \
: (_) == 'R' ? 17 \
: (_) == 'S' ? 18 \
: (_) == 'T' ? 19 \
: (_) == 'U' ? 20 \
: (_) == 'V' ? 21 \
: (_) == 'W' ? 22 \
: (_) == 'X' ? 23 \
: (_) == 'Y' ? 24 \
: (_) == 'Z' ? 25 \
: (_) == 'a' ? 26 \
: (_) == 'b' ? 27 \
: (_) == 'c' ? 28 \
: (_) == 'd' ? 29 \
: (_) == 'e' ? 30 \
: (_) == 'f' ? 31 \
: (_) == 'g' ? 32 \
: (_) == 'h' ? 33 \
: (_) == 'i' ? 34 \
: (_) == 'j' ? 35 \
: (_) == 'k' ? 36 \
: (_) == 'l' ? 37 \
: (_) == 'm' ? 38 \
: (_) == 'n' ? 39 \
: (_) == 'o' ? 40 \
: (_) == 'p' ? 41 \
: (_) == 'q' ? 42 \
: (_) == 'r' ? 43 \
: (_) == 's' ? 44 \
: (_) == 't' ? 45 \
: (_) == 'u' ? 46 \
: (_) == 'v' ? 47 \
: (_) == 'w' ? 48 \
: (_) == 'x' ? 49 \
: (_) == 'y' ? 50 \
: (_) == 'z' ? 51 \
: (_) == '0' ? 52 \
: (_) == '1' ? 53 \
: (_) == '2' ? 54 \
: (_) == '3' ? 55 \
: (_) == '4' ? 56 \
: (_) == '5' ? 57 \
: (_) == '6' ? 58 \
: (_) == '7' ? 59 \
: (_) == '8' ? 60 \
: (_) == '9' ? 61 \
: (_) == '+' ? 62 \
: (_) == '/' ? 63 \
: -1)
static const signed char b64[0x100] = {
B64 (0), B64 (1), B64 (2), B64 (3),
B64 (4), B64 (5), B64 (6), B64 (7),
B64 (8), B64 (9), B64 (10), B64 (11),
B64 (12), B64 (13), B64 (14), B64 (15),
B64 (16), B64 (17), B64 (18), B64 (19),
B64 (20), B64 (21), B64 (22), B64 (23),
B64 (24), B64 (25), B64 (26), B64 (27),
B64 (28), B64 (29), B64 (30), B64 (31),
B64 (32), B64 (33), B64 (34), B64 (35),
B64 (36), B64 (37), B64 (38), B64 (39),
B64 (40), B64 (41), B64 (42), B64 (43),
B64 (44), B64 (45), B64 (46), B64 (47),
B64 (48), B64 (49), B64 (50), B64 (51),
B64 (52), B64 (53), B64 (54), B64 (55),
B64 (56), B64 (57), B64 (58), B64 (59),
B64 (60), B64 (61), B64 (62), B64 (63),
B64 (64), B64 (65), B64 (66), B64 (67),
B64 (68), B64 (69), B64 (70), B64 (71),
B64 (72), B64 (73), B64 (74), B64 (75),
B64 (76), B64 (77), B64 (78), B64 (79),
B64 (80), B64 (81), B64 (82), B64 (83),
B64 (84), B64 (85), B64 (86), B64 (87),
B64 (88), B64 (89), B64 (90), B64 (91),
B64 (92), B64 (93), B64 (94), B64 (95),
B64 (96), B64 (97), B64 (98), B64 (99),
B64 (100), B64 (101), B64 (102), B64 (103),
B64 (104), B64 (105), B64 (106), B64 (107),
B64 (108), B64 (109), B64 (110), B64 (111),
B64 (112), B64 (113), B64 (114), B64 (115),
B64 (116), B64 (117), B64 (118), B64 (119),
B64 (120), B64 (121), B64 (122), B64 (123),
B64 (124), B64 (125), B64 (126), B64 (127),
B64 (128), B64 (129), B64 (130), B64 (131),
B64 (132), B64 (133), B64 (134), B64 (135),
B64 (136), B64 (137), B64 (138), B64 (139),
B64 (140), B64 (141), B64 (142), B64 (143),
B64 (144), B64 (145), B64 (146), B64 (147),
B64 (148), B64 (149), B64 (150), B64 (151),
B64 (152), B64 (153), B64 (154), B64 (155),
B64 (156), B64 (157), B64 (158), B64 (159),
B64 (160), B64 (161), B64 (162), B64 (163),
B64 (164), B64 (165), B64 (166), B64 (167),
B64 (168), B64 (169), B64 (170), B64 (171),
B64 (172), B64 (173), B64 (174), B64 (175),
B64 (176), B64 (177), B64 (178), B64 (179),
B64 (180), B64 (181), B64 (182), B64 (183),
B64 (184), B64 (185), B64 (186), B64 (187),
B64 (188), B64 (189), B64 (190), B64 (191),
B64 (192), B64 (193), B64 (194), B64 (195),
B64 (196), B64 (197), B64 (198), B64 (199),
B64 (200), B64 (201), B64 (202), B64 (203),
B64 (204), B64 (205), B64 (206), B64 (207),
B64 (208), B64 (209), B64 (210), B64 (211),
B64 (212), B64 (213), B64 (214), B64 (215),
B64 (216), B64 (217), B64 (218), B64 (219),
B64 (220), B64 (221), B64 (222), B64 (223),
B64 (224), B64 (225), B64 (226), B64 (227),
B64 (228), B64 (229), B64 (230), B64 (231),
B64 (232), B64 (233), B64 (234), B64 (235),
B64 (236), B64 (237), B64 (238), B64 (239),
B64 (240), B64 (241), B64 (242), B64 (243),
B64 (244), B64 (245), B64 (246), B64 (247),
B64 (248), B64 (249), B64 (250), B64 (251),
B64 (252), B64 (253), B64 (254), B64 (255)
};
#if UCHAR_MAX == 255
# define uchar_in_range(c) true
#else
# define uchar_in_range(c) ((c) <= 255)
#endif
/* Return true if CH is a character from the Base64 alphabet, and
false otherwise. Note that '=' is padding and not considered to be
part of the alphabet. */
bool
isbase64 (char ch)
{
return uchar_in_range (to_uchar (ch)) && 0 <= b64[to_uchar (ch)];
}
/* Initialize decode-context buffer, CTX. */
void
base64_decode_ctx_init (struct base64_decode_context *ctx)
{
ctx->i = 0;
}
/* If CTX->i is 0 or 4, there are four or more bytes in [*IN..IN_END), and
none of those four is a newline, then return *IN. Otherwise, copy up to
4 - CTX->i non-newline bytes from that range into CTX->buf, starting at
index CTX->i and setting CTX->i to reflect the number of bytes copied,
and return CTX->buf. In either case, advance *IN to point to the byte
after the last one processed, and set *N_NON_NEWLINE to the number of
verified non-newline bytes accessible through the returned pointer. */
static const char *
get_4 (struct base64_decode_context *ctx,
char const *restrict *in, char const *restrict in_end,
size_t *n_non_newline)
{
if (ctx->i == 4)
ctx->i = 0;
if (ctx->i == 0)
{
char const *t = *in;
if (4 <= in_end - *in && memchr (t, '\n', 4) == NULL)
{
/* This is the common case: no newline. */
*in += 4;
*n_non_newline = 4;
return (const char *) t;
}
}
{
/* Copy non-newline bytes into BUF. */
char const *p = *in;
while (p < in_end)
{
char c = *p++;
if (c != '\n')
{
ctx->buf[ctx->i++] = c;
if (ctx->i == 4)
break;
}
}
*in = p;
*n_non_newline = ctx->i;
return ctx->buf;
}
}
#define return_false \
do \
{ \
*outp = out; \
return false; \
} \
while (false)
/* Decode up to four bytes of base64-encoded data, IN, of length INLEN
into the output buffer, *OUT, of size *OUTLEN bytes. Return true if
decoding is successful, false otherwise. If *OUTLEN is too small,
as many bytes as possible are written to *OUT. On return, advance
*OUT to point to the byte after the last one written, and decrement
*OUTLEN to reflect the number of bytes remaining in *OUT. */
static bool
decode_4 (char const *restrict in, size_t inlen,
char *restrict *outp, size_t *outleft)
{
char *out = *outp;
if (inlen < 2)
return false;
if (!isbase64 (in[0]) || !isbase64 (in[1]))
return false;
if (*outleft)
{
*out++ = ((b64[to_uchar (in[0])] << 2)
| (b64[to_uchar (in[1])] >> 4));
--*outleft;
}
if (inlen == 2)
return_false;
if (in[2] == '=')
{
if (inlen != 4)
return_false;
if (in[3] != '=')
return_false;
}
else
{
if (!isbase64 (in[2]))
return_false;
if (*outleft)
{
*out++ = (((b64[to_uchar (in[1])] << 4) & 0xf0)
| (b64[to_uchar (in[2])] >> 2));
--*outleft;
}
if (inlen == 3)
return_false;
if (in[3] == '=')
{
if (inlen != 4)
return_false;
}
else
{
if (!isbase64 (in[3]))
return_false;
if (*outleft)
{
*out++ = (((b64[to_uchar (in[2])] << 6) & 0xc0)
| b64[to_uchar (in[3])]);
--*outleft;
}
}
}
*outp = out;
return true;
}
/* Decode base64-encoded input array IN of length INLEN to output array
OUT that can hold *OUTLEN bytes. The input data may be interspersed
with newlines. Return true if decoding was successful, i.e. if the
input was valid base64 data, false otherwise. If *OUTLEN is too
small, as many bytes as possible will be written to OUT. On return,
*OUTLEN holds the length of decoded bytes in OUT. Note that as soon
as any non-alphabet, non-newline character is encountered, decoding
is stopped and false is returned. If INLEN is zero, then process
only whatever data is stored in CTX.
Initially, CTX must have been initialized via base64_decode_ctx_init.
Subsequent calls to this function must reuse whatever state is recorded
in that buffer. It is necessary for when a quadruple of base64 input
bytes spans two input buffers.
If CTX is NULL then newlines are treated as garbage and the input
buffer is processed as a unit. */
bool
base64_decode_ctx (struct base64_decode_context *ctx,
const char *restrict in, size_t inlen,
char *restrict out, size_t *outlen)
{
size_t outleft = *outlen;
bool ignore_newlines = ctx != NULL;
bool flush_ctx = false;
unsigned int ctx_i = 0;
if (ignore_newlines)
{
ctx_i = ctx->i;
flush_ctx = inlen == 0;
}
while (true)
{
size_t outleft_save = outleft;
if (ctx_i == 0 && !flush_ctx)
{
while (true)
{
/* Save a copy of outleft, in case we need to re-parse this
block of four bytes. */
outleft_save = outleft;
if (!decode_4 (in, inlen, &out, &outleft))
break;
in += 4;
inlen -= 4;
}
}
if (inlen == 0 && !flush_ctx)
break;
/* Handle the common case of 72-byte wrapped lines.
This also handles any other multiple-of-4-byte wrapping. */
if (inlen && *in == '\n' && ignore_newlines)
{
++in;
--inlen;
continue;
}
/* Restore OUT and OUTLEFT. */
out -= outleft_save - outleft;
outleft = outleft_save;
{
char const *in_end = in + inlen;
char const *non_nl;
if (ignore_newlines)
non_nl = get_4 (ctx, &in, in_end, &inlen);
else
non_nl = in; /* Might have nl in this case. */
/* If the input is empty or consists solely of newlines (0 non-newlines),
then we're done. Likewise if there are fewer than 4 bytes when not
flushing context and not treating newlines as garbage. */
if (inlen == 0 || (inlen < 4 && !flush_ctx && ignore_newlines))
{
inlen = 0;
break;
}
if (!decode_4 (non_nl, inlen, &out, &outleft))
break;
inlen = in_end - in;
}
}
*outlen -= outleft;
return inlen == 0;
}
/* Allocate an output buffer in *OUT, and decode the base64 encoded
data stored in IN of size INLEN to the *OUT buffer. On return, the
size of the decoded data is stored in *OUTLEN. OUTLEN may be NULL,
if the caller is not interested in the decoded length. *OUT may be
NULL to indicate an out of memory error, in which case *OUTLEN
contains the size of the memory block needed. The function returns
true on successful decoding and memory allocation errors. (Use the
*OUT and *OUTLEN parameters to differentiate between successful
decoding and memory error.) The function returns false if the
input was invalid, in which case *OUT is NULL and *OUTLEN is
undefined. */
bool
base64_decode_alloc_ctx (struct base64_decode_context *ctx,
const char *in, size_t inlen, char **out,
size_t *outlen)
{
/* This may allocate a few bytes too many, depending on input,
but it's not worth the extra CPU time to compute the exact size.
The exact size is 3 * (inlen + (ctx ? ctx->i : 0)) / 4, minus 1 if the
input ends with "=" and minus another 1 if the input ends with "==".
Dividing before multiplying avoids the possibility of overflow. */
size_t needlen = 3 * (inlen / 4) + 3;
*out = malloc (needlen);
if (!*out)
return true;
if (!base64_decode_ctx (ctx, in, inlen, *out, &needlen))
{
free (*out);
*out = NULL;
return false;
}
if (outlen)
*outlen = needlen;
return true;
}

68
lib/base64.h Normal file
View File

@@ -0,0 +1,68 @@
/* base64.h -- Encode binary data using printable characters.
Copyright (C) 2004-2006, 2009-2019 Free Software Foundation, Inc.
Written by Simon Josefsson.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <https://www.gnu.org/licenses/>. */
#ifndef BASE64_H
# define BASE64_H
/* Get size_t. */
# include <stddef.h>
/* Get bool. */
# include <stdbool.h>
# ifdef __cplusplus
extern "C" {
# endif
/* This uses that the expression (n+(k-1))/k means the smallest
integer >= n/k, i.e., the ceiling of n/k. */
# define BASE64_LENGTH(inlen) ((((inlen) + 2) / 3) * 4)
struct base64_decode_context
{
unsigned int i;
char buf[4];
};
extern bool isbase64 (char ch) __attribute__ ((__const__));
extern void base64_encode (const char *restrict in, size_t inlen,
char *restrict out, size_t outlen);
extern size_t base64_encode_alloc (const char *in, size_t inlen, char **out);
extern void base64_decode_ctx_init (struct base64_decode_context *ctx);
extern bool base64_decode_ctx (struct base64_decode_context *ctx,
const char *restrict in, size_t inlen,
char *restrict out, size_t *outlen);
extern bool base64_decode_alloc_ctx (struct base64_decode_context *ctx,
const char *in, size_t inlen,
char **out, size_t *outlen);
#define base64_decode(in, inlen, out, outlen) \
base64_decode_ctx (NULL, in, inlen, out, outlen)
#define base64_decode_alloc(in, inlen, out, outlen) \
base64_decode_alloc_ctx (NULL, in, inlen, out, outlen)
# ifdef __cplusplus
}
# endif
#endif /* BASE64_H */

1382
lib/bitlk/bitlk.c Normal file

File diff suppressed because it is too large Load Diff

131
lib/bitlk/bitlk.h Normal file
View File

@@ -0,0 +1,131 @@
/*
* BITLK (BitLocker-compatible) header definition
*
* Copyright (C) 2019-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2019-2021 Milan Broz
* Copyright (C) 2019-2021 Vojtech Trefny
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef _CRYPTSETUP_BITLK_H
#define _CRYPTSETUP_BITLK_H
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
struct crypt_device;
struct device;
#define BITLK_NONCE_SIZE 12
#define BITLK_SALT_SIZE 16
#define BITLK_VMK_MAC_TAG_SIZE 16
#define BITLK_STATE_NORMAL 0x0004
typedef enum {
BITLK_ENCRYPTION_TYPE_NORMAL = 0,
BITLK_ENCRYPTION_TYPE_EOW,
BITLK_ENCRYPTION_TYPE_UNKNOWN,
} BITLKEncryptionType;
typedef enum {
BITLK_PROTECTION_CLEAR_KEY = 0,
BITLK_PROTECTION_TPM,
BITLK_PROTECTION_STARTUP_KEY,
BITLK_PROTECTION_TPM_PIN,
BITLK_PROTECTION_RECOVERY_PASSPHRASE,
BITLK_PROTECTION_PASSPHRASE,
BITLK_PROTECTION_SMART_CARD,
BITLK_PROTECTION_UNKNOWN,
} BITLKVMKProtection;
typedef enum {
BITLK_ENTRY_TYPE_PROPERTY = 0x0000,
BITLK_ENTRY_TYPE_VMK = 0x0002,
BITLK_ENTRY_TYPE_FVEK = 0x0003,
BITLK_ENTRY_TYPE_STARTUP_KEY = 0x0006,
BITLK_ENTRY_TYPE_DESCRIPTION = 0x0007,
BITLK_ENTRY_TYPE_VOLUME_HEADER = 0x000f,
} BITLKFVEEntryType;
typedef enum {
BITLK_ENTRY_VALUE_ERASED = 0x0000,
BITLK_ENTRY_VALUE_KEY = 0x0001,
BITLK_ENTRY_VALUE_STRING = 0x0002,
BITLK_ENTRY_VALUE_STRETCH_KEY = 0x0003,
BITLK_ENTRY_VALUE_USE_KEY = 0x0004,
BITLK_ENTRY_VALUE_ENCRYPTED_KEY = 0x0005,
BITLK_ENTRY_VALUE_TPM_KEY = 0x0006,
BITLK_ENTRY_VALUE_VALIDATION = 0x0007,
BITLK_ENTRY_VALUE_VMK = 0x0008,
BITLK_ENTRY_VALUE_EXTERNAL_KEY = 0x0009,
BITLK_ENTRY_VALUE_OFFSET_SIZE = 0x000f,
BITLK_ENTRY_VALUE_RECOVERY_TIME = 0x015,
} BITLKFVEEntryValue;
struct bitlk_vmk {
char *guid;
char *name;
BITLKVMKProtection protection;
uint8_t salt[BITLK_SALT_SIZE];
uint8_t mac_tag[BITLK_VMK_MAC_TAG_SIZE];
uint8_t nonce[BITLK_NONCE_SIZE];
struct volume_key *vk;
struct bitlk_vmk *next;
};
struct bitlk_fvek {
uint8_t mac_tag[BITLK_VMK_MAC_TAG_SIZE];
uint8_t nonce[BITLK_NONCE_SIZE];
struct volume_key *vk;
};
struct bitlk_metadata {
uint16_t sector_size;
bool togo;
bool state;
BITLKEncryptionType type;
const char *cipher;
const char *cipher_mode;
uint16_t key_size;
char *guid;
uint64_t creation_time;
char *description;
uint64_t metadata_offset[3];
uint32_t metadata_version;
uint64_t volume_header_offset;
uint64_t volume_header_size;
struct bitlk_vmk *vmks;
struct bitlk_fvek *fvek;
};
int BITLK_read_sb(struct crypt_device *cd, struct bitlk_metadata *params);
int BITLK_dump(struct crypt_device *cd, struct device *device, struct bitlk_metadata *params);
int BITLK_activate(struct crypt_device *cd,
const char *name,
const char *password,
size_t passwordLen,
const struct bitlk_metadata *params,
uint32_t flags);
void BITLK_bitlk_fvek_free(struct bitlk_fvek *fvek);
void BITLK_bitlk_vmk_free(struct bitlk_vmk *vmk);
void BITLK_bitlk_metadata_free(struct bitlk_metadata *params);
#endif

View File

@@ -1,9 +1,9 @@
/*
* cryptsetup plain device helper functions
*
* Copyright (C) 2004, Jana Saout <jana@saout.de>
* Copyright (C) 2010-2012 Red Hat, Inc. All rights reserved.
* Copyright (C) 2010-2012, Milan Broz
* Copyright (C) 2004 Jana Saout <jana@saout.de>
* Copyright (C) 2010-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2010-2021 Milan Broz
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
@@ -64,7 +64,7 @@ static int hash(const char *hash_name, size_t key_size, char *key,
#define PLAIN_HASH_LEN_MAX 256
int crypt_plain_hash(struct crypt_device *ctx __attribute__((unused)),
int crypt_plain_hash(struct crypt_device *cd,
const char *hash_name,
char *key, size_t key_size,
const char *passphrase, size_t passphrase_size)
@@ -73,7 +73,7 @@ int crypt_plain_hash(struct crypt_device *ctx __attribute__((unused)),
size_t hash_size, pad_size;
int r;
log_dbg("Plain: hashing passphrase using %s.", hash_name);
log_dbg(cd, "Plain: hashing passphrase using %s.", hash_name);
if (strlen(hash_name) >= PLAIN_HASH_LEN_MAX)
return -EINVAL;
@@ -85,11 +85,11 @@ int crypt_plain_hash(struct crypt_device *ctx __attribute__((unused)),
*s = '\0';
s++;
if (!*s || sscanf(s, "%zd", &hash_size) != 1) {
log_dbg("Hash length is not a number");
log_dbg(cd, "Hash length is not a number");
return -EINVAL;
}
if (hash_size > key_size) {
log_dbg("Hash length %zd > key length %zd",
log_dbg(cd, "Hash length %zd > key length %zd",
hash_size, key_size);
return -EINVAL;
}
@@ -102,7 +102,7 @@ int crypt_plain_hash(struct crypt_device *ctx __attribute__((unused)),
/* No hash, copy passphrase directly */
if (!strcmp(hash_name_buf, "plain")) {
if (passphrase_size < hash_size) {
log_dbg("Too short plain passphrase.");
log_dbg(cd, "Too short plain passphrase.");
return -EINVAL;
}
memcpy(key, passphrase, hash_size);

View File

@@ -1,30 +0,0 @@
moduledir = $(libdir)/cryptsetup
noinst_LTLIBRARIES = libcrypto_backend.la
libcrypto_backend_la_CFLAGS = $(AM_CFLAGS) -Wall @CRYPTO_CFLAGS@
libcrypto_backend_la_SOURCES = crypto_backend.h \
crypto_cipher_kernel.c crypto_storage.c pbkdf_check.c crc32.c
if CRYPTO_BACKEND_GCRYPT
libcrypto_backend_la_SOURCES += crypto_gcrypt.c
endif
if CRYPTO_BACKEND_OPENSSL
libcrypto_backend_la_SOURCES += crypto_openssl.c
endif
if CRYPTO_BACKEND_NSS
libcrypto_backend_la_SOURCES += crypto_nss.c
endif
if CRYPTO_BACKEND_KERNEL
libcrypto_backend_la_SOURCES += crypto_kernel.c
endif
if CRYPTO_BACKEND_NETTLE
libcrypto_backend_la_SOURCES += crypto_nettle.c
endif
if CRYPTO_INTERNAL_PBKDF2
libcrypto_backend_la_SOURCES += pbkdf2_generic.c
endif
AM_CPPFLAGS = -include config.h -I$(top_srcdir)/lib

View File

@@ -0,0 +1,39 @@
noinst_LTLIBRARIES += libcrypto_backend.la
libcrypto_backend_la_CFLAGS = $(AM_CFLAGS) @CRYPTO_CFLAGS@
libcrypto_backend_la_SOURCES = \
lib/crypto_backend/crypto_backend.h \
lib/crypto_backend/crypto_backend_internal.h \
lib/crypto_backend/crypto_cipher_kernel.c \
lib/crypto_backend/crypto_storage.c \
lib/crypto_backend/pbkdf_check.c \
lib/crypto_backend/crc32.c \
lib/crypto_backend/argon2_generic.c \
lib/crypto_backend/cipher_generic.c \
lib/crypto_backend/cipher_check.c
if CRYPTO_BACKEND_GCRYPT
libcrypto_backend_la_SOURCES += lib/crypto_backend/crypto_gcrypt.c
endif
if CRYPTO_BACKEND_OPENSSL
libcrypto_backend_la_SOURCES += lib/crypto_backend/crypto_openssl.c
endif
if CRYPTO_BACKEND_NSS
libcrypto_backend_la_SOURCES += lib/crypto_backend/crypto_nss.c
endif
if CRYPTO_BACKEND_KERNEL
libcrypto_backend_la_SOURCES += lib/crypto_backend/crypto_kernel.c
endif
if CRYPTO_BACKEND_NETTLE
libcrypto_backend_la_SOURCES += lib/crypto_backend/crypto_nettle.c
endif
if CRYPTO_INTERNAL_PBKDF2
libcrypto_backend_la_SOURCES += lib/crypto_backend/pbkdf2_generic.c
endif
if CRYPTO_INTERNAL_ARGON2
libcrypto_backend_la_DEPENDENCIES = libargon2.la
libcrypto_backend_la_LIBADD = libargon2.la
endif

View File

@@ -0,0 +1,30 @@
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
moral rights retained by the original author(s) and/or performer(s);
publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
rights protecting the extraction, dissemination, use and reuse of data in a Work;
database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
4. Limitations and Disclaimers.
No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work.

View File

@@ -0,0 +1,30 @@
noinst_LTLIBRARIES += libargon2.la
libargon2_la_CFLAGS = $(AM_CFLAGS) -std=c89 -pthread -O3
libargon2_la_CPPFLAGS = $(AM_CPPFLAGS) \
-I lib/crypto_backend/argon2 \
-I lib/crypto_backend/argon2/blake2
libargon2_la_SOURCES = \
lib/crypto_backend/argon2/blake2/blake2b.c \
lib/crypto_backend/argon2/blake2/blake2.h \
lib/crypto_backend/argon2/blake2/blake2-impl.h \
lib/crypto_backend/argon2/argon2.c \
lib/crypto_backend/argon2/argon2.h \
lib/crypto_backend/argon2/core.c \
lib/crypto_backend/argon2/core.h \
lib/crypto_backend/argon2/encoding.c \
lib/crypto_backend/argon2/encoding.h \
lib/crypto_backend/argon2/thread.c \
lib/crypto_backend/argon2/thread.h
if CRYPTO_INTERNAL_SSE_ARGON2
libargon2_la_SOURCES += lib/crypto_backend/argon2/blake2/blamka-round-opt.h \
lib/crypto_backend/argon2/opt.c
else
libargon2_la_SOURCES += lib/crypto_backend/argon2/blake2/blamka-round-ref.h \
lib/crypto_backend/argon2/ref.c
endif
EXTRA_DIST += lib/crypto_backend/argon2/LICENSE
EXTRA_DIST += lib/crypto_backend/argon2/README

View File

@@ -0,0 +1,5 @@
This is bundled Argon2 algorithm library, copied from
https://github.com/P-H-C/phc-winner-argon2
For more info see Password Hashing Competition site:
https://password-hashing.net/

View File

@@ -0,0 +1,458 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "argon2.h"
#include "encoding.h"
#include "core.h"
/* to silent gcc -Wcast-qual for const cast */
#define CONST_CAST(x) (x)(uintptr_t)
const char *argon2_type2string(argon2_type type, int uppercase) {
switch (type) {
case Argon2_d:
return uppercase ? "Argon2d" : "argon2d";
case Argon2_i:
return uppercase ? "Argon2i" : "argon2i";
case Argon2_id:
return uppercase ? "Argon2id" : "argon2id";
}
return NULL;
}
int argon2_ctx(argon2_context *context, argon2_type type) {
/* 1. Validate all inputs */
int result = validate_inputs(context);
uint32_t memory_blocks, segment_length;
argon2_instance_t instance;
if (ARGON2_OK != result) {
return result;
}
if (Argon2_d != type && Argon2_i != type && Argon2_id != type) {
return ARGON2_INCORRECT_TYPE;
}
/* 2. Align memory size */
/* Minimum memory_blocks = 8L blocks, where L is the number of lanes */
memory_blocks = context->m_cost;
if (memory_blocks < 2 * ARGON2_SYNC_POINTS * context->lanes) {
memory_blocks = 2 * ARGON2_SYNC_POINTS * context->lanes;
}
segment_length = memory_blocks / (context->lanes * ARGON2_SYNC_POINTS);
/* Ensure that all segments have equal length */
memory_blocks = segment_length * (context->lanes * ARGON2_SYNC_POINTS);
instance.version = context->version;
instance.memory = NULL;
instance.passes = context->t_cost;
instance.memory_blocks = memory_blocks;
instance.segment_length = segment_length;
instance.lane_length = segment_length * ARGON2_SYNC_POINTS;
instance.lanes = context->lanes;
instance.threads = context->threads;
instance.type = type;
if (instance.threads > instance.lanes) {
instance.threads = instance.lanes;
}
/* 3. Initialization: Hashing inputs, allocating memory, filling first
* blocks
*/
result = initialize(&instance, context);
if (ARGON2_OK != result) {
return result;
}
/* 4. Filling memory */
result = fill_memory_blocks(&instance);
if (ARGON2_OK != result) {
return result;
}
/* 5. Finalization */
finalize(context, &instance);
return ARGON2_OK;
}
int argon2_hash(const uint32_t t_cost, const uint32_t m_cost,
const uint32_t parallelism, const void *pwd,
const size_t pwdlen, const void *salt, const size_t saltlen,
void *hash, const size_t hashlen, char *encoded,
const size_t encodedlen, argon2_type type,
const uint32_t version){
argon2_context context;
int result;
uint8_t *out;
if (pwdlen > ARGON2_MAX_PWD_LENGTH) {
return ARGON2_PWD_TOO_LONG;
}
if (saltlen > ARGON2_MAX_SALT_LENGTH) {
return ARGON2_SALT_TOO_LONG;
}
if (hashlen > ARGON2_MAX_OUTLEN) {
return ARGON2_OUTPUT_TOO_LONG;
}
if (hashlen < ARGON2_MIN_OUTLEN) {
return ARGON2_OUTPUT_TOO_SHORT;
}
out = malloc(hashlen);
if (!out) {
return ARGON2_MEMORY_ALLOCATION_ERROR;
}
context.out = (uint8_t *)out;
context.outlen = (uint32_t)hashlen;
context.pwd = CONST_CAST(uint8_t *)pwd;
context.pwdlen = (uint32_t)pwdlen;
context.salt = CONST_CAST(uint8_t *)salt;
context.saltlen = (uint32_t)saltlen;
context.secret = NULL;
context.secretlen = 0;
context.ad = NULL;
context.adlen = 0;
context.t_cost = t_cost;
context.m_cost = m_cost;
context.lanes = parallelism;
context.threads = parallelism;
context.allocate_cbk = NULL;
context.free_cbk = NULL;
context.flags = ARGON2_DEFAULT_FLAGS;
context.version = version;
result = argon2_ctx(&context, type);
if (result != ARGON2_OK) {
clear_internal_memory(out, hashlen);
free(out);
return result;
}
/* if raw hash requested, write it */
if (hash) {
memcpy(hash, out, hashlen);
}
/* if encoding requested, write it */
if (encoded && encodedlen) {
if (encode_string(encoded, encodedlen, &context, type) != ARGON2_OK) {
clear_internal_memory(out, hashlen); /* wipe buffers if error */
clear_internal_memory(encoded, encodedlen);
free(out);
return ARGON2_ENCODING_FAIL;
}
}
clear_internal_memory(out, hashlen);
free(out);
return ARGON2_OK;
}
int argon2i_hash_encoded(const uint32_t t_cost, const uint32_t m_cost,
const uint32_t parallelism, const void *pwd,
const size_t pwdlen, const void *salt,
const size_t saltlen, const size_t hashlen,
char *encoded, const size_t encodedlen) {
return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen,
NULL, hashlen, encoded, encodedlen, Argon2_i,
ARGON2_VERSION_NUMBER);
}
int argon2i_hash_raw(const uint32_t t_cost, const uint32_t m_cost,
const uint32_t parallelism, const void *pwd,
const size_t pwdlen, const void *salt,
const size_t saltlen, void *hash, const size_t hashlen) {
return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen,
hash, hashlen, NULL, 0, Argon2_i, ARGON2_VERSION_NUMBER);
}
int argon2d_hash_encoded(const uint32_t t_cost, const uint32_t m_cost,
const uint32_t parallelism, const void *pwd,
const size_t pwdlen, const void *salt,
const size_t saltlen, const size_t hashlen,
char *encoded, const size_t encodedlen) {
return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen,
NULL, hashlen, encoded, encodedlen, Argon2_d,
ARGON2_VERSION_NUMBER);
}
int argon2d_hash_raw(const uint32_t t_cost, const uint32_t m_cost,
const uint32_t parallelism, const void *pwd,
const size_t pwdlen, const void *salt,
const size_t saltlen, void *hash, const size_t hashlen) {
return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen,
hash, hashlen, NULL, 0, Argon2_d, ARGON2_VERSION_NUMBER);
}
int argon2id_hash_encoded(const uint32_t t_cost, const uint32_t m_cost,
const uint32_t parallelism, const void *pwd,
const size_t pwdlen, const void *salt,
const size_t saltlen, const size_t hashlen,
char *encoded, const size_t encodedlen) {
return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen,
NULL, hashlen, encoded, encodedlen, Argon2_id,
ARGON2_VERSION_NUMBER);
}
int argon2id_hash_raw(const uint32_t t_cost, const uint32_t m_cost,
const uint32_t parallelism, const void *pwd,
const size_t pwdlen, const void *salt,
const size_t saltlen, void *hash, const size_t hashlen) {
return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen,
hash, hashlen, NULL, 0, Argon2_id,
ARGON2_VERSION_NUMBER);
}
static int argon2_compare(const uint8_t *b1, const uint8_t *b2, size_t len) {
size_t i;
uint8_t d = 0U;
for (i = 0U; i < len; i++) {
d |= b1[i] ^ b2[i];
}
return (int)((1 & ((d - 1) >> 8)) - 1);
}
int argon2_verify(const char *encoded, const void *pwd, const size_t pwdlen,
argon2_type type) {
argon2_context ctx;
uint8_t *desired_result = NULL;
int ret = ARGON2_OK;
size_t encoded_len;
uint32_t max_field_len;
if (pwdlen > ARGON2_MAX_PWD_LENGTH) {
return ARGON2_PWD_TOO_LONG;
}
if (encoded == NULL) {
return ARGON2_DECODING_FAIL;
}
encoded_len = strlen(encoded);
if (encoded_len > UINT32_MAX) {
return ARGON2_DECODING_FAIL;
}
/* No field can be longer than the encoded length */
/* coverity[strlen_assign] */
max_field_len = (uint32_t)encoded_len;
ctx.saltlen = max_field_len;
ctx.outlen = max_field_len;
ctx.salt = malloc(ctx.saltlen);
ctx.out = malloc(ctx.outlen);
if (!ctx.salt || !ctx.out) {
ret = ARGON2_MEMORY_ALLOCATION_ERROR;
goto fail;
}
ctx.pwd = CONST_CAST(uint8_t *)pwd;
ctx.pwdlen = (uint32_t)pwdlen;
ret = decode_string(&ctx, encoded, type);
if (ret != ARGON2_OK) {
goto fail;
}
/* Set aside the desired result, and get a new buffer. */
desired_result = ctx.out;
ctx.out = malloc(ctx.outlen);
if (!ctx.out) {
ret = ARGON2_MEMORY_ALLOCATION_ERROR;
goto fail;
}
ret = argon2_verify_ctx(&ctx, (char *)desired_result, type);
if (ret != ARGON2_OK) {
goto fail;
}
fail:
free(ctx.salt);
free(ctx.out);
free(desired_result);
return ret;
}
int argon2i_verify(const char *encoded, const void *pwd, const size_t pwdlen) {
return argon2_verify(encoded, pwd, pwdlen, Argon2_i);
}
int argon2d_verify(const char *encoded, const void *pwd, const size_t pwdlen) {
return argon2_verify(encoded, pwd, pwdlen, Argon2_d);
}
int argon2id_verify(const char *encoded, const void *pwd, const size_t pwdlen) {
return argon2_verify(encoded, pwd, pwdlen, Argon2_id);
}
int argon2d_ctx(argon2_context *context) {
return argon2_ctx(context, Argon2_d);
}
int argon2i_ctx(argon2_context *context) {
return argon2_ctx(context, Argon2_i);
}
int argon2id_ctx(argon2_context *context) {
return argon2_ctx(context, Argon2_id);
}
int argon2_verify_ctx(argon2_context *context, const char *hash,
argon2_type type) {
int ret = argon2_ctx(context, type);
if (ret != ARGON2_OK) {
return ret;
}
if (argon2_compare(CONST_CAST(uint8_t *)hash, context->out, context->outlen)) {
return ARGON2_VERIFY_MISMATCH;
}
return ARGON2_OK;
}
int argon2d_verify_ctx(argon2_context *context, const char *hash) {
return argon2_verify_ctx(context, hash, Argon2_d);
}
int argon2i_verify_ctx(argon2_context *context, const char *hash) {
return argon2_verify_ctx(context, hash, Argon2_i);
}
int argon2id_verify_ctx(argon2_context *context, const char *hash) {
return argon2_verify_ctx(context, hash, Argon2_id);
}
const char *argon2_error_message(int error_code) {
switch (error_code) {
case ARGON2_OK:
return "OK";
case ARGON2_OUTPUT_PTR_NULL:
return "Output pointer is NULL";
case ARGON2_OUTPUT_TOO_SHORT:
return "Output is too short";
case ARGON2_OUTPUT_TOO_LONG:
return "Output is too long";
case ARGON2_PWD_TOO_SHORT:
return "Password is too short";
case ARGON2_PWD_TOO_LONG:
return "Password is too long";
case ARGON2_SALT_TOO_SHORT:
return "Salt is too short";
case ARGON2_SALT_TOO_LONG:
return "Salt is too long";
case ARGON2_AD_TOO_SHORT:
return "Associated data is too short";
case ARGON2_AD_TOO_LONG:
return "Associated data is too long";
case ARGON2_SECRET_TOO_SHORT:
return "Secret is too short";
case ARGON2_SECRET_TOO_LONG:
return "Secret is too long";
case ARGON2_TIME_TOO_SMALL:
return "Time cost is too small";
case ARGON2_TIME_TOO_LARGE:
return "Time cost is too large";
case ARGON2_MEMORY_TOO_LITTLE:
return "Memory cost is too small";
case ARGON2_MEMORY_TOO_MUCH:
return "Memory cost is too large";
case ARGON2_LANES_TOO_FEW:
return "Too few lanes";
case ARGON2_LANES_TOO_MANY:
return "Too many lanes";
case ARGON2_PWD_PTR_MISMATCH:
return "Password pointer is NULL, but password length is not 0";
case ARGON2_SALT_PTR_MISMATCH:
return "Salt pointer is NULL, but salt length is not 0";
case ARGON2_SECRET_PTR_MISMATCH:
return "Secret pointer is NULL, but secret length is not 0";
case ARGON2_AD_PTR_MISMATCH:
return "Associated data pointer is NULL, but ad length is not 0";
case ARGON2_MEMORY_ALLOCATION_ERROR:
return "Memory allocation error";
case ARGON2_FREE_MEMORY_CBK_NULL:
return "The free memory callback is NULL";
case ARGON2_ALLOCATE_MEMORY_CBK_NULL:
return "The allocate memory callback is NULL";
case ARGON2_INCORRECT_PARAMETER:
return "Argon2_Context context is NULL";
case ARGON2_INCORRECT_TYPE:
return "There is no such version of Argon2";
case ARGON2_OUT_PTR_MISMATCH:
return "Output pointer mismatch";
case ARGON2_THREADS_TOO_FEW:
return "Not enough threads";
case ARGON2_THREADS_TOO_MANY:
return "Too many threads";
case ARGON2_MISSING_ARGS:
return "Missing arguments";
case ARGON2_ENCODING_FAIL:
return "Encoding failed";
case ARGON2_DECODING_FAIL:
return "Decoding failed";
case ARGON2_THREAD_FAIL:
return "Threading failure";
case ARGON2_DECODING_LENGTH_FAIL:
return "Some of encoded parameters are too long or too short";
case ARGON2_VERIFY_MISMATCH:
return "The password does not match the supplied hash";
default:
return "Unknown error code";
}
}
size_t argon2_encodedlen(uint32_t t_cost, uint32_t m_cost, uint32_t parallelism,
uint32_t saltlen, uint32_t hashlen, argon2_type type) {
if (!argon2_type2string(type, 0))
return 0;
return strlen("$$v=$m=,t=,p=$$") + strlen(argon2_type2string(type, 0)) +
numlen(t_cost) + numlen(m_cost) + numlen(parallelism) +
b64len(saltlen) + b64len(hashlen) + numlen(ARGON2_VERSION_NUMBER) + 1;
}

View File

@@ -0,0 +1,437 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#ifndef ARGON2_H
#define ARGON2_H
#include <stdint.h>
#include <stddef.h>
#include <limits.h>
#if defined(__cplusplus)
extern "C" {
#endif
/* Symbols visibility control */
#ifdef A2_VISCTL
#define ARGON2_PUBLIC __attribute__((visibility("default")))
#define ARGON2_LOCAL __attribute__ ((visibility ("hidden")))
#elif _MSC_VER
#define ARGON2_PUBLIC __declspec(dllexport)
#define ARGON2_LOCAL
#else
#define ARGON2_PUBLIC
#define ARGON2_LOCAL
#endif
/*
* Argon2 input parameter restrictions
*/
/* Minimum and maximum number of lanes (degree of parallelism) */
#define ARGON2_MIN_LANES UINT32_C(1)
#define ARGON2_MAX_LANES UINT32_C(0xFFFFFF)
/* Minimum and maximum number of threads */
#define ARGON2_MIN_THREADS UINT32_C(1)
#define ARGON2_MAX_THREADS UINT32_C(0xFFFFFF)
/* Number of synchronization points between lanes per pass */
#define ARGON2_SYNC_POINTS UINT32_C(4)
/* Minimum and maximum digest size in bytes */
#define ARGON2_MIN_OUTLEN UINT32_C(4)
#define ARGON2_MAX_OUTLEN UINT32_C(0xFFFFFFFF)
/* Minimum and maximum number of memory blocks (each of BLOCK_SIZE bytes) */
#define ARGON2_MIN_MEMORY (2 * ARGON2_SYNC_POINTS) /* 2 blocks per slice */
#define ARGON2_MIN(a, b) ((a) < (b) ? (a) : (b))
/* Max memory size is addressing-space/2, topping at 2^32 blocks (4 TB) */
#define ARGON2_MAX_MEMORY_BITS \
ARGON2_MIN(UINT32_C(32), (sizeof(void *) * CHAR_BIT - 10 - 1))
#define ARGON2_MAX_MEMORY \
ARGON2_MIN(UINT32_C(0xFFFFFFFF), UINT64_C(1) << ARGON2_MAX_MEMORY_BITS)
/* Minimum and maximum number of passes */
#define ARGON2_MIN_TIME UINT32_C(1)
#define ARGON2_MAX_TIME UINT32_C(0xFFFFFFFF)
/* Minimum and maximum password length in bytes */
#define ARGON2_MIN_PWD_LENGTH UINT32_C(0)
#define ARGON2_MAX_PWD_LENGTH UINT32_C(0xFFFFFFFF)
/* Minimum and maximum associated data length in bytes */
#define ARGON2_MIN_AD_LENGTH UINT32_C(0)
#define ARGON2_MAX_AD_LENGTH UINT32_C(0xFFFFFFFF)
/* Minimum and maximum salt length in bytes */
#define ARGON2_MIN_SALT_LENGTH UINT32_C(8)
#define ARGON2_MAX_SALT_LENGTH UINT32_C(0xFFFFFFFF)
/* Minimum and maximum key length in bytes */
#define ARGON2_MIN_SECRET UINT32_C(0)
#define ARGON2_MAX_SECRET UINT32_C(0xFFFFFFFF)
/* Flags to determine which fields are securely wiped (default = no wipe). */
#define ARGON2_DEFAULT_FLAGS UINT32_C(0)
#define ARGON2_FLAG_CLEAR_PASSWORD (UINT32_C(1) << 0)
#define ARGON2_FLAG_CLEAR_SECRET (UINT32_C(1) << 1)
/* Global flag to determine if we are wiping internal memory buffers. This flag
* is defined in core.c and defaults to 1 (wipe internal memory). */
extern int FLAG_clear_internal_memory;
/* Error codes */
typedef enum Argon2_ErrorCodes {
ARGON2_OK = 0,
ARGON2_OUTPUT_PTR_NULL = -1,
ARGON2_OUTPUT_TOO_SHORT = -2,
ARGON2_OUTPUT_TOO_LONG = -3,
ARGON2_PWD_TOO_SHORT = -4,
ARGON2_PWD_TOO_LONG = -5,
ARGON2_SALT_TOO_SHORT = -6,
ARGON2_SALT_TOO_LONG = -7,
ARGON2_AD_TOO_SHORT = -8,
ARGON2_AD_TOO_LONG = -9,
ARGON2_SECRET_TOO_SHORT = -10,
ARGON2_SECRET_TOO_LONG = -11,
ARGON2_TIME_TOO_SMALL = -12,
ARGON2_TIME_TOO_LARGE = -13,
ARGON2_MEMORY_TOO_LITTLE = -14,
ARGON2_MEMORY_TOO_MUCH = -15,
ARGON2_LANES_TOO_FEW = -16,
ARGON2_LANES_TOO_MANY = -17,
ARGON2_PWD_PTR_MISMATCH = -18, /* NULL ptr with non-zero length */
ARGON2_SALT_PTR_MISMATCH = -19, /* NULL ptr with non-zero length */
ARGON2_SECRET_PTR_MISMATCH = -20, /* NULL ptr with non-zero length */
ARGON2_AD_PTR_MISMATCH = -21, /* NULL ptr with non-zero length */
ARGON2_MEMORY_ALLOCATION_ERROR = -22,
ARGON2_FREE_MEMORY_CBK_NULL = -23,
ARGON2_ALLOCATE_MEMORY_CBK_NULL = -24,
ARGON2_INCORRECT_PARAMETER = -25,
ARGON2_INCORRECT_TYPE = -26,
ARGON2_OUT_PTR_MISMATCH = -27,
ARGON2_THREADS_TOO_FEW = -28,
ARGON2_THREADS_TOO_MANY = -29,
ARGON2_MISSING_ARGS = -30,
ARGON2_ENCODING_FAIL = -31,
ARGON2_DECODING_FAIL = -32,
ARGON2_THREAD_FAIL = -33,
ARGON2_DECODING_LENGTH_FAIL = -34,
ARGON2_VERIFY_MISMATCH = -35
} argon2_error_codes;
/* Memory allocator types --- for external allocation */
typedef int (*allocate_fptr)(uint8_t **memory, size_t bytes_to_allocate);
typedef void (*deallocate_fptr)(uint8_t *memory, size_t bytes_to_allocate);
/* Argon2 external data structures */
/*
*****
* Context: structure to hold Argon2 inputs:
* output array and its length,
* password and its length,
* salt and its length,
* secret and its length,
* associated data and its length,
* number of passes, amount of used memory (in KBytes, can be rounded up a bit)
* number of parallel threads that will be run.
* All the parameters above affect the output hash value.
* Additionally, two function pointers can be provided to allocate and
* deallocate the memory (if NULL, memory will be allocated internally).
* Also, three flags indicate whether to erase password, secret as soon as they
* are pre-hashed (and thus not needed anymore), and the entire memory
*****
* Simplest situation: you have output array out[8], password is stored in
* pwd[32], salt is stored in salt[16], you do not have keys nor associated
* data. You need to spend 1 GB of RAM and you run 5 passes of Argon2d with
* 4 parallel lanes.
* You want to erase the password, but you're OK with last pass not being
* erased. You want to use the default memory allocator.
* Then you initialize:
Argon2_Context(out,8,pwd,32,salt,16,NULL,0,NULL,0,5,1<<20,4,4,NULL,NULL,true,false,false,false)
*/
typedef struct Argon2_Context {
uint8_t *out; /* output array */
uint32_t outlen; /* digest length */
uint8_t *pwd; /* password array */
uint32_t pwdlen; /* password length */
uint8_t *salt; /* salt array */
uint32_t saltlen; /* salt length */
uint8_t *secret; /* key array */
uint32_t secretlen; /* key length */
uint8_t *ad; /* associated data array */
uint32_t adlen; /* associated data length */
uint32_t t_cost; /* number of passes */
uint32_t m_cost; /* amount of memory requested (KB) */
uint32_t lanes; /* number of lanes */
uint32_t threads; /* maximum number of threads */
uint32_t version; /* version number */
allocate_fptr allocate_cbk; /* pointer to memory allocator */
deallocate_fptr free_cbk; /* pointer to memory deallocator */
uint32_t flags; /* array of bool options */
} argon2_context;
/* Argon2 primitive type */
typedef enum Argon2_type {
Argon2_d = 0,
Argon2_i = 1,
Argon2_id = 2
} argon2_type;
/* Version of the algorithm */
typedef enum Argon2_version {
ARGON2_VERSION_10 = 0x10,
ARGON2_VERSION_13 = 0x13,
ARGON2_VERSION_NUMBER = ARGON2_VERSION_13
} argon2_version;
/*
* Function that gives the string representation of an argon2_type.
* @param type The argon2_type that we want the string for
* @param uppercase Whether the string should have the first letter uppercase
* @return NULL if invalid type, otherwise the string representation.
*/
ARGON2_PUBLIC const char *argon2_type2string(argon2_type type, int uppercase);
/*
* Function that performs memory-hard hashing with certain degree of parallelism
* @param context Pointer to the Argon2 internal structure
* @return Error code if smth is wrong, ARGON2_OK otherwise
*/
ARGON2_PUBLIC int argon2_ctx(argon2_context *context, argon2_type type);
/**
* Hashes a password with Argon2i, producing an encoded hash
* @param t_cost Number of iterations
* @param m_cost Sets memory usage to m_cost kibibytes
* @param parallelism Number of threads and compute lanes
* @param pwd Pointer to password
* @param pwdlen Password size in bytes
* @param salt Pointer to salt
* @param saltlen Salt size in bytes
* @param hashlen Desired length of the hash in bytes
* @param encoded Buffer where to write the encoded hash
* @param encodedlen Size of the buffer (thus max size of the encoded hash)
* @pre Different parallelism levels will give different results
* @pre Returns ARGON2_OK if successful
*/
ARGON2_PUBLIC int argon2i_hash_encoded(const uint32_t t_cost,
const uint32_t m_cost,
const uint32_t parallelism,
const void *pwd, const size_t pwdlen,
const void *salt, const size_t saltlen,
const size_t hashlen, char *encoded,
const size_t encodedlen);
/**
* Hashes a password with Argon2i, producing a raw hash at @hash
* @param t_cost Number of iterations
* @param m_cost Sets memory usage to m_cost kibibytes
* @param parallelism Number of threads and compute lanes
* @param pwd Pointer to password
* @param pwdlen Password size in bytes
* @param salt Pointer to salt
* @param saltlen Salt size in bytes
* @param hash Buffer where to write the raw hash - updated by the function
* @param hashlen Desired length of the hash in bytes
* @pre Different parallelism levels will give different results
* @pre Returns ARGON2_OK if successful
*/
ARGON2_PUBLIC int argon2i_hash_raw(const uint32_t t_cost, const uint32_t m_cost,
const uint32_t parallelism, const void *pwd,
const size_t pwdlen, const void *salt,
const size_t saltlen, void *hash,
const size_t hashlen);
ARGON2_PUBLIC int argon2d_hash_encoded(const uint32_t t_cost,
const uint32_t m_cost,
const uint32_t parallelism,
const void *pwd, const size_t pwdlen,
const void *salt, const size_t saltlen,
const size_t hashlen, char *encoded,
const size_t encodedlen);
ARGON2_PUBLIC int argon2d_hash_raw(const uint32_t t_cost, const uint32_t m_cost,
const uint32_t parallelism, const void *pwd,
const size_t pwdlen, const void *salt,
const size_t saltlen, void *hash,
const size_t hashlen);
ARGON2_PUBLIC int argon2id_hash_encoded(const uint32_t t_cost,
const uint32_t m_cost,
const uint32_t parallelism,
const void *pwd, const size_t pwdlen,
const void *salt, const size_t saltlen,
const size_t hashlen, char *encoded,
const size_t encodedlen);
ARGON2_PUBLIC int argon2id_hash_raw(const uint32_t t_cost,
const uint32_t m_cost,
const uint32_t parallelism, const void *pwd,
const size_t pwdlen, const void *salt,
const size_t saltlen, void *hash,
const size_t hashlen);
/* generic function underlying the above ones */
ARGON2_PUBLIC int argon2_hash(const uint32_t t_cost, const uint32_t m_cost,
const uint32_t parallelism, const void *pwd,
const size_t pwdlen, const void *salt,
const size_t saltlen, void *hash,
const size_t hashlen, char *encoded,
const size_t encodedlen, argon2_type type,
const uint32_t version);
/**
* Verifies a password against an encoded string
* Encoded string is restricted as in validate_inputs()
* @param encoded String encoding parameters, salt, hash
* @param pwd Pointer to password
* @pre Returns ARGON2_OK if successful
*/
ARGON2_PUBLIC int argon2i_verify(const char *encoded, const void *pwd,
const size_t pwdlen);
ARGON2_PUBLIC int argon2d_verify(const char *encoded, const void *pwd,
const size_t pwdlen);
ARGON2_PUBLIC int argon2id_verify(const char *encoded, const void *pwd,
const size_t pwdlen);
/* generic function underlying the above ones */
ARGON2_PUBLIC int argon2_verify(const char *encoded, const void *pwd,
const size_t pwdlen, argon2_type type);
/**
* Argon2d: Version of Argon2 that picks memory blocks depending
* on the password and salt. Only for side-channel-free
* environment!!
*****
* @param context Pointer to current Argon2 context
* @return Zero if successful, a non zero error code otherwise
*/
ARGON2_PUBLIC int argon2d_ctx(argon2_context *context);
/**
* Argon2i: Version of Argon2 that picks memory blocks
* independent on the password and salt. Good for side-channels,
* but worse w.r.t. tradeoff attacks if only one pass is used.
*****
* @param context Pointer to current Argon2 context
* @return Zero if successful, a non zero error code otherwise
*/
ARGON2_PUBLIC int argon2i_ctx(argon2_context *context);
/**
* Argon2id: Version of Argon2 where the first half-pass over memory is
* password-independent, the rest are password-dependent (on the password and
* salt). OK against side channels (they reduce to 1/2-pass Argon2i), and
* better with w.r.t. tradeoff attacks (similar to Argon2d).
*****
* @param context Pointer to current Argon2 context
* @return Zero if successful, a non zero error code otherwise
*/
ARGON2_PUBLIC int argon2id_ctx(argon2_context *context);
/**
* Verify if a given password is correct for Argon2d hashing
* @param context Pointer to current Argon2 context
* @param hash The password hash to verify. The length of the hash is
* specified by the context outlen member
* @return Zero if successful, a non zero error code otherwise
*/
ARGON2_PUBLIC int argon2d_verify_ctx(argon2_context *context, const char *hash);
/**
* Verify if a given password is correct for Argon2i hashing
* @param context Pointer to current Argon2 context
* @param hash The password hash to verify. The length of the hash is
* specified by the context outlen member
* @return Zero if successful, a non zero error code otherwise
*/
ARGON2_PUBLIC int argon2i_verify_ctx(argon2_context *context, const char *hash);
/**
* Verify if a given password is correct for Argon2id hashing
* @param context Pointer to current Argon2 context
* @param hash The password hash to verify. The length of the hash is
* specified by the context outlen member
* @return Zero if successful, a non zero error code otherwise
*/
ARGON2_PUBLIC int argon2id_verify_ctx(argon2_context *context,
const char *hash);
/* generic function underlying the above ones */
ARGON2_PUBLIC int argon2_verify_ctx(argon2_context *context, const char *hash,
argon2_type type);
/**
* Get the associated error message for given error code
* @return The error message associated with the given error code
*/
ARGON2_PUBLIC const char *argon2_error_message(int error_code);
/**
* Returns the encoded hash length for the given input parameters
* @param t_cost Number of iterations
* @param m_cost Memory usage in kibibytes
* @param parallelism Number of threads; used to compute lanes
* @param saltlen Salt size in bytes
* @param hashlen Hash size in bytes
* @param type The argon2_type that we want the encoded length for
* @return The encoded hash length in bytes
*/
ARGON2_PUBLIC size_t argon2_encodedlen(uint32_t t_cost, uint32_t m_cost,
uint32_t parallelism, uint32_t saltlen,
uint32_t hashlen, argon2_type type);
#if defined(__cplusplus)
}
#endif
#endif

View File

@@ -0,0 +1,154 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#ifndef PORTABLE_BLAKE2_IMPL_H
#define PORTABLE_BLAKE2_IMPL_H
#include <stdint.h>
#include <string.h>
#if defined(_MSC_VER)
#define BLAKE2_INLINE __inline
#elif defined(__GNUC__) || defined(__clang__)
#define BLAKE2_INLINE __inline__
#else
#define BLAKE2_INLINE
#endif
/* Argon2 Team - Begin Code */
/*
Not an exhaustive list, but should cover the majority of modern platforms
Additionally, the code will always be correct---this is only a performance
tweak.
*/
#if (defined(__BYTE_ORDER__) && \
(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || \
defined(__LITTLE_ENDIAN__) || defined(__ARMEL__) || defined(__MIPSEL__) || \
defined(__AARCH64EL__) || defined(__amd64__) || defined(__i386__) || \
defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64) || \
defined(_M_ARM)
#define NATIVE_LITTLE_ENDIAN
#endif
/* Argon2 Team - End Code */
static BLAKE2_INLINE uint32_t load32(const void *src) {
#if defined(NATIVE_LITTLE_ENDIAN)
uint32_t w;
memcpy(&w, src, sizeof w);
return w;
#else
const uint8_t *p = (const uint8_t *)src;
uint32_t w = *p++;
w |= (uint32_t)(*p++) << 8;
w |= (uint32_t)(*p++) << 16;
w |= (uint32_t)(*p++) << 24;
return w;
#endif
}
static BLAKE2_INLINE uint64_t load64(const void *src) {
#if defined(NATIVE_LITTLE_ENDIAN)
uint64_t w;
memcpy(&w, src, sizeof w);
return w;
#else
const uint8_t *p = (const uint8_t *)src;
uint64_t w = *p++;
w |= (uint64_t)(*p++) << 8;
w |= (uint64_t)(*p++) << 16;
w |= (uint64_t)(*p++) << 24;
w |= (uint64_t)(*p++) << 32;
w |= (uint64_t)(*p++) << 40;
w |= (uint64_t)(*p++) << 48;
w |= (uint64_t)(*p++) << 56;
return w;
#endif
}
static BLAKE2_INLINE void store32(void *dst, uint32_t w) {
#if defined(NATIVE_LITTLE_ENDIAN)
memcpy(dst, &w, sizeof w);
#else
uint8_t *p = (uint8_t *)dst;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
#endif
}
static BLAKE2_INLINE void store64(void *dst, uint64_t w) {
#if defined(NATIVE_LITTLE_ENDIAN)
memcpy(dst, &w, sizeof w);
#else
uint8_t *p = (uint8_t *)dst;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
#endif
}
static BLAKE2_INLINE uint64_t load48(const void *src) {
const uint8_t *p = (const uint8_t *)src;
uint64_t w = *p++;
w |= (uint64_t)(*p++) << 8;
w |= (uint64_t)(*p++) << 16;
w |= (uint64_t)(*p++) << 24;
w |= (uint64_t)(*p++) << 32;
w |= (uint64_t)(*p++) << 40;
return w;
}
static BLAKE2_INLINE void store48(void *dst, uint64_t w) {
uint8_t *p = (uint8_t *)dst;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
w >>= 8;
*p++ = (uint8_t)w;
}
static BLAKE2_INLINE uint32_t rotr32(const uint32_t w, const unsigned c) {
return (w >> c) | (w << (32 - c));
}
static BLAKE2_INLINE uint64_t rotr64(const uint64_t w, const unsigned c) {
return (w >> c) | (w << (64 - c));
}
#endif

View File

@@ -0,0 +1,89 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#ifndef PORTABLE_BLAKE2_H
#define PORTABLE_BLAKE2_H
#include "../argon2.h"
#if defined(__cplusplus)
extern "C" {
#endif
enum blake2b_constant {
BLAKE2B_BLOCKBYTES = 128,
BLAKE2B_OUTBYTES = 64,
BLAKE2B_KEYBYTES = 64,
BLAKE2B_SALTBYTES = 16,
BLAKE2B_PERSONALBYTES = 16
};
#pragma pack(push, 1)
typedef struct __blake2b_param {
uint8_t digest_length; /* 1 */
uint8_t key_length; /* 2 */
uint8_t fanout; /* 3 */
uint8_t depth; /* 4 */
uint32_t leaf_length; /* 8 */
uint64_t node_offset; /* 16 */
uint8_t node_depth; /* 17 */
uint8_t inner_length; /* 18 */
uint8_t reserved[14]; /* 32 */
uint8_t salt[BLAKE2B_SALTBYTES]; /* 48 */
uint8_t personal[BLAKE2B_PERSONALBYTES]; /* 64 */
} blake2b_param;
#pragma pack(pop)
typedef struct __blake2b_state {
uint64_t h[8];
uint64_t t[2];
uint64_t f[2];
uint8_t buf[BLAKE2B_BLOCKBYTES];
unsigned buflen;
unsigned outlen;
uint8_t last_node;
} blake2b_state;
/* Ensure param structs have not been wrongly padded */
/* Poor man's static_assert */
enum {
blake2_size_check_0 = 1 / !!(CHAR_BIT == 8),
blake2_size_check_2 =
1 / !!(sizeof(blake2b_param) == sizeof(uint64_t) * CHAR_BIT)
};
/* Streaming API */
ARGON2_LOCAL int blake2b_init(blake2b_state *S, size_t outlen);
ARGON2_LOCAL int blake2b_init_key(blake2b_state *S, size_t outlen, const void *key,
size_t keylen);
ARGON2_LOCAL int blake2b_init_param(blake2b_state *S, const blake2b_param *P);
ARGON2_LOCAL int blake2b_update(blake2b_state *S, const void *in, size_t inlen);
ARGON2_LOCAL int blake2b_final(blake2b_state *S, void *out, size_t outlen);
/* Simple API */
ARGON2_LOCAL int blake2b(void *out, size_t outlen, const void *in, size_t inlen,
const void *key, size_t keylen);
/* Argon2 Team - Begin Code */
ARGON2_LOCAL int blake2b_long(void *out, size_t outlen, const void *in, size_t inlen);
/* Argon2 Team - End Code */
#if defined(__cplusplus)
}
#endif
#endif

View File

@@ -0,0 +1,392 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include "blake2.h"
#include "blake2-impl.h"
void clear_internal_memory(void *v, size_t n);
static const uint64_t blake2b_IV[8] = {
UINT64_C(0x6a09e667f3bcc908), UINT64_C(0xbb67ae8584caa73b),
UINT64_C(0x3c6ef372fe94f82b), UINT64_C(0xa54ff53a5f1d36f1),
UINT64_C(0x510e527fade682d1), UINT64_C(0x9b05688c2b3e6c1f),
UINT64_C(0x1f83d9abfb41bd6b), UINT64_C(0x5be0cd19137e2179)};
static const unsigned int blake2b_sigma[12][16] = {
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
{14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3},
{11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4},
{7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8},
{9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13},
{2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9},
{12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11},
{13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10},
{6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5},
{10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
{14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3},
};
static BLAKE2_INLINE void blake2b_set_lastnode(blake2b_state *S) {
S->f[1] = (uint64_t)-1;
}
static BLAKE2_INLINE void blake2b_set_lastblock(blake2b_state *S) {
if (S->last_node) {
blake2b_set_lastnode(S);
}
S->f[0] = (uint64_t)-1;
}
static BLAKE2_INLINE void blake2b_increment_counter(blake2b_state *S,
uint64_t inc) {
S->t[0] += inc;
S->t[1] += (S->t[0] < inc);
}
static BLAKE2_INLINE void blake2b_invalidate_state(blake2b_state *S) {
clear_internal_memory(S, sizeof(*S)); /* wipe */
blake2b_set_lastblock(S); /* invalidate for further use */
}
static BLAKE2_INLINE void blake2b_init0(blake2b_state *S) {
memset(S, 0, sizeof(*S));
memcpy(S->h, blake2b_IV, sizeof(S->h));
}
int blake2b_init_param(blake2b_state *S, const blake2b_param *P) {
const unsigned char *p = (const unsigned char *)P;
unsigned int i;
if (NULL == P || NULL == S) {
return -1;
}
blake2b_init0(S);
/* IV XOR Parameter Block */
for (i = 0; i < 8; ++i) {
S->h[i] ^= load64(&p[i * sizeof(S->h[i])]);
}
S->outlen = P->digest_length;
return 0;
}
/* Sequential blake2b initialization */
int blake2b_init(blake2b_state *S, size_t outlen) {
blake2b_param P;
if (S == NULL) {
return -1;
}
if ((outlen == 0) || (outlen > BLAKE2B_OUTBYTES)) {
blake2b_invalidate_state(S);
return -1;
}
/* Setup Parameter Block for unkeyed BLAKE2 */
P.digest_length = (uint8_t)outlen;
P.key_length = 0;
P.fanout = 1;
P.depth = 1;
P.leaf_length = 0;
P.node_offset = 0;
P.node_depth = 0;
P.inner_length = 0;
memset(P.reserved, 0, sizeof(P.reserved));
memset(P.salt, 0, sizeof(P.salt));
memset(P.personal, 0, sizeof(P.personal));
return blake2b_init_param(S, &P);
}
int blake2b_init_key(blake2b_state *S, size_t outlen, const void *key,
size_t keylen) {
blake2b_param P;
if (S == NULL) {
return -1;
}
if ((outlen == 0) || (outlen > BLAKE2B_OUTBYTES)) {
blake2b_invalidate_state(S);
return -1;
}
if ((key == 0) || (keylen == 0) || (keylen > BLAKE2B_KEYBYTES)) {
blake2b_invalidate_state(S);
return -1;
}
/* Setup Parameter Block for keyed BLAKE2 */
P.digest_length = (uint8_t)outlen;
P.key_length = (uint8_t)keylen;
P.fanout = 1;
P.depth = 1;
P.leaf_length = 0;
P.node_offset = 0;
P.node_depth = 0;
P.inner_length = 0;
memset(P.reserved, 0, sizeof(P.reserved));
memset(P.salt, 0, sizeof(P.salt));
memset(P.personal, 0, sizeof(P.personal));
if (blake2b_init_param(S, &P) < 0) {
blake2b_invalidate_state(S);
return -1;
}
{
uint8_t block[BLAKE2B_BLOCKBYTES];
memset(block, 0, BLAKE2B_BLOCKBYTES);
memcpy(block, key, keylen);
blake2b_update(S, block, BLAKE2B_BLOCKBYTES);
/* Burn the key from stack */
clear_internal_memory(block, BLAKE2B_BLOCKBYTES);
}
return 0;
}
static void blake2b_compress(blake2b_state *S, const uint8_t *block) {
uint64_t m[16];
uint64_t v[16];
unsigned int i, r;
for (i = 0; i < 16; ++i) {
m[i] = load64(block + i * sizeof(m[i]));
}
for (i = 0; i < 8; ++i) {
v[i] = S->h[i];
}
v[8] = blake2b_IV[0];
v[9] = blake2b_IV[1];
v[10] = blake2b_IV[2];
v[11] = blake2b_IV[3];
v[12] = blake2b_IV[4] ^ S->t[0];
v[13] = blake2b_IV[5] ^ S->t[1];
v[14] = blake2b_IV[6] ^ S->f[0];
v[15] = blake2b_IV[7] ^ S->f[1];
#define G(r, i, a, b, c, d) \
do { \
a = a + b + m[blake2b_sigma[r][2 * i + 0]]; \
d = rotr64(d ^ a, 32); \
c = c + d; \
b = rotr64(b ^ c, 24); \
a = a + b + m[blake2b_sigma[r][2 * i + 1]]; \
d = rotr64(d ^ a, 16); \
c = c + d; \
b = rotr64(b ^ c, 63); \
} while ((void)0, 0)
#define ROUND(r) \
do { \
G(r, 0, v[0], v[4], v[8], v[12]); \
G(r, 1, v[1], v[5], v[9], v[13]); \
G(r, 2, v[2], v[6], v[10], v[14]); \
G(r, 3, v[3], v[7], v[11], v[15]); \
G(r, 4, v[0], v[5], v[10], v[15]); \
G(r, 5, v[1], v[6], v[11], v[12]); \
G(r, 6, v[2], v[7], v[8], v[13]); \
G(r, 7, v[3], v[4], v[9], v[14]); \
} while ((void)0, 0)
for (r = 0; r < 12; ++r) {
ROUND(r);
}
for (i = 0; i < 8; ++i) {
S->h[i] = S->h[i] ^ v[i] ^ v[i + 8];
}
#undef G
#undef ROUND
}
int blake2b_update(blake2b_state *S, const void *in, size_t inlen) {
const uint8_t *pin = (const uint8_t *)in;
if (inlen == 0) {
return 0;
}
/* Sanity check */
if (S == NULL || in == NULL) {
return -1;
}
/* Is this a reused state? */
if (S->f[0] != 0) {
return -1;
}
if (S->buflen + inlen > BLAKE2B_BLOCKBYTES) {
/* Complete current block */
size_t left = S->buflen;
size_t fill = BLAKE2B_BLOCKBYTES - left;
memcpy(&S->buf[left], pin, fill);
blake2b_increment_counter(S, BLAKE2B_BLOCKBYTES);
blake2b_compress(S, S->buf);
S->buflen = 0;
inlen -= fill;
pin += fill;
/* Avoid buffer copies when possible */
while (inlen > BLAKE2B_BLOCKBYTES) {
blake2b_increment_counter(S, BLAKE2B_BLOCKBYTES);
blake2b_compress(S, pin);
inlen -= BLAKE2B_BLOCKBYTES;
pin += BLAKE2B_BLOCKBYTES;
}
}
memcpy(&S->buf[S->buflen], pin, inlen);
S->buflen += (unsigned int)inlen;
return 0;
}
int blake2b_final(blake2b_state *S, void *out, size_t outlen) {
uint8_t buffer[BLAKE2B_OUTBYTES] = {0};
unsigned int i;
/* Sanity checks */
if (S == NULL || out == NULL || outlen < S->outlen) {
return -1;
}
/* Is this a reused state? */
if (S->f[0] != 0) {
return -1;
}
blake2b_increment_counter(S, S->buflen);
blake2b_set_lastblock(S);
memset(&S->buf[S->buflen], 0, BLAKE2B_BLOCKBYTES - S->buflen); /* Padding */
blake2b_compress(S, S->buf);
for (i = 0; i < 8; ++i) { /* Output full hash to temp buffer */
store64(buffer + sizeof(S->h[i]) * i, S->h[i]);
}
memcpy(out, buffer, S->outlen);
clear_internal_memory(buffer, sizeof(buffer));
clear_internal_memory(S->buf, sizeof(S->buf));
clear_internal_memory(S->h, sizeof(S->h));
return 0;
}
int blake2b(void *out, size_t outlen, const void *in, size_t inlen,
const void *key, size_t keylen) {
blake2b_state S;
int ret = -1;
/* Verify parameters */
if (NULL == in && inlen > 0) {
goto fail;
}
if (NULL == out || outlen == 0 || outlen > BLAKE2B_OUTBYTES) {
goto fail;
}
if ((NULL == key && keylen > 0) || keylen > BLAKE2B_KEYBYTES) {
goto fail;
}
if (keylen > 0) {
if (blake2b_init_key(&S, outlen, key, keylen) < 0) {
goto fail;
}
} else {
if (blake2b_init(&S, outlen) < 0) {
goto fail;
}
}
if (blake2b_update(&S, in, inlen) < 0) {
goto fail;
}
ret = blake2b_final(&S, out, outlen);
fail:
clear_internal_memory(&S, sizeof(S));
return ret;
}
/* Argon2 Team - Begin Code */
int blake2b_long(void *pout, size_t outlen, const void *in, size_t inlen) {
uint8_t *out = (uint8_t *)pout;
blake2b_state blake_state;
uint8_t outlen_bytes[sizeof(uint32_t)] = {0};
int ret = -1;
if (outlen > UINT32_MAX) {
goto fail;
}
/* Ensure little-endian byte order! */
store32(outlen_bytes, (uint32_t)outlen);
#define TRY(statement) \
do { \
ret = statement; \
if (ret < 0) { \
goto fail; \
} \
} while ((void)0, 0)
if (outlen <= BLAKE2B_OUTBYTES) {
TRY(blake2b_init(&blake_state, outlen));
TRY(blake2b_update(&blake_state, outlen_bytes, sizeof(outlen_bytes)));
TRY(blake2b_update(&blake_state, in, inlen));
TRY(blake2b_final(&blake_state, out, outlen));
} else {
uint32_t toproduce;
uint8_t out_buffer[BLAKE2B_OUTBYTES];
uint8_t in_buffer[BLAKE2B_OUTBYTES];
TRY(blake2b_init(&blake_state, BLAKE2B_OUTBYTES));
TRY(blake2b_update(&blake_state, outlen_bytes, sizeof(outlen_bytes)));
TRY(blake2b_update(&blake_state, in, inlen));
TRY(blake2b_final(&blake_state, out_buffer, BLAKE2B_OUTBYTES));
memcpy(out, out_buffer, BLAKE2B_OUTBYTES / 2);
out += BLAKE2B_OUTBYTES / 2;
toproduce = (uint32_t)outlen - BLAKE2B_OUTBYTES / 2;
while (toproduce > BLAKE2B_OUTBYTES) {
memcpy(in_buffer, out_buffer, BLAKE2B_OUTBYTES);
TRY(blake2b(out_buffer, BLAKE2B_OUTBYTES, in_buffer,
BLAKE2B_OUTBYTES, NULL, 0));
memcpy(out, out_buffer, BLAKE2B_OUTBYTES / 2);
out += BLAKE2B_OUTBYTES / 2;
toproduce -= BLAKE2B_OUTBYTES / 2;
}
memcpy(in_buffer, out_buffer, BLAKE2B_OUTBYTES);
TRY(blake2b(out_buffer, toproduce, in_buffer, BLAKE2B_OUTBYTES, NULL,
0));
memcpy(out, out_buffer, toproduce);
}
fail:
clear_internal_memory(&blake_state, sizeof(blake_state));
return ret;
#undef TRY
}
/* Argon2 Team - End Code */

View File

@@ -0,0 +1,471 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#ifndef BLAKE_ROUND_MKA_OPT_H
#define BLAKE_ROUND_MKA_OPT_H
#include "blake2-impl.h"
#include <emmintrin.h>
#if defined(__SSSE3__)
#include <tmmintrin.h> /* for _mm_shuffle_epi8 and _mm_alignr_epi8 */
#endif
#if defined(__XOP__) && (defined(__GNUC__) || defined(__clang__))
#include <x86intrin.h>
#endif
#if !defined(__AVX512F__)
#if !defined(__AVX2__)
#if !defined(__XOP__)
#if defined(__SSSE3__)
#define r16 \
(_mm_setr_epi8(2, 3, 4, 5, 6, 7, 0, 1, 10, 11, 12, 13, 14, 15, 8, 9))
#define r24 \
(_mm_setr_epi8(3, 4, 5, 6, 7, 0, 1, 2, 11, 12, 13, 14, 15, 8, 9, 10))
#define _mm_roti_epi64(x, c) \
(-(c) == 32) \
? _mm_shuffle_epi32((x), _MM_SHUFFLE(2, 3, 0, 1)) \
: (-(c) == 24) \
? _mm_shuffle_epi8((x), r24) \
: (-(c) == 16) \
? _mm_shuffle_epi8((x), r16) \
: (-(c) == 63) \
? _mm_xor_si128(_mm_srli_epi64((x), -(c)), \
_mm_add_epi64((x), (x))) \
: _mm_xor_si128(_mm_srli_epi64((x), -(c)), \
_mm_slli_epi64((x), 64 - (-(c))))
#else /* defined(__SSE2__) */
#define _mm_roti_epi64(r, c) \
_mm_xor_si128(_mm_srli_epi64((r), -(c)), _mm_slli_epi64((r), 64 - (-(c))))
#endif
#else
#endif
static BLAKE2_INLINE __m128i fBlaMka(__m128i x, __m128i y) {
const __m128i z = _mm_mul_epu32(x, y);
return _mm_add_epi64(_mm_add_epi64(x, y), _mm_add_epi64(z, z));
}
#define G1(A0, B0, C0, D0, A1, B1, C1, D1) \
do { \
A0 = fBlaMka(A0, B0); \
A1 = fBlaMka(A1, B1); \
\
D0 = _mm_xor_si128(D0, A0); \
D1 = _mm_xor_si128(D1, A1); \
\
D0 = _mm_roti_epi64(D0, -32); \
D1 = _mm_roti_epi64(D1, -32); \
\
C0 = fBlaMka(C0, D0); \
C1 = fBlaMka(C1, D1); \
\
B0 = _mm_xor_si128(B0, C0); \
B1 = _mm_xor_si128(B1, C1); \
\
B0 = _mm_roti_epi64(B0, -24); \
B1 = _mm_roti_epi64(B1, -24); \
} while ((void)0, 0)
#define G2(A0, B0, C0, D0, A1, B1, C1, D1) \
do { \
A0 = fBlaMka(A0, B0); \
A1 = fBlaMka(A1, B1); \
\
D0 = _mm_xor_si128(D0, A0); \
D1 = _mm_xor_si128(D1, A1); \
\
D0 = _mm_roti_epi64(D0, -16); \
D1 = _mm_roti_epi64(D1, -16); \
\
C0 = fBlaMka(C0, D0); \
C1 = fBlaMka(C1, D1); \
\
B0 = _mm_xor_si128(B0, C0); \
B1 = _mm_xor_si128(B1, C1); \
\
B0 = _mm_roti_epi64(B0, -63); \
B1 = _mm_roti_epi64(B1, -63); \
} while ((void)0, 0)
#if defined(__SSSE3__)
#define DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \
do { \
__m128i t0 = _mm_alignr_epi8(B1, B0, 8); \
__m128i t1 = _mm_alignr_epi8(B0, B1, 8); \
B0 = t0; \
B1 = t1; \
\
t0 = C0; \
C0 = C1; \
C1 = t0; \
\
t0 = _mm_alignr_epi8(D1, D0, 8); \
t1 = _mm_alignr_epi8(D0, D1, 8); \
D0 = t1; \
D1 = t0; \
} while ((void)0, 0)
#define UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \
do { \
__m128i t0 = _mm_alignr_epi8(B0, B1, 8); \
__m128i t1 = _mm_alignr_epi8(B1, B0, 8); \
B0 = t0; \
B1 = t1; \
\
t0 = C0; \
C0 = C1; \
C1 = t0; \
\
t0 = _mm_alignr_epi8(D0, D1, 8); \
t1 = _mm_alignr_epi8(D1, D0, 8); \
D0 = t1; \
D1 = t0; \
} while ((void)0, 0)
#else /* SSE2 */
#define DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \
do { \
__m128i t0 = D0; \
__m128i t1 = B0; \
D0 = C0; \
C0 = C1; \
C1 = D0; \
D0 = _mm_unpackhi_epi64(D1, _mm_unpacklo_epi64(t0, t0)); \
D1 = _mm_unpackhi_epi64(t0, _mm_unpacklo_epi64(D1, D1)); \
B0 = _mm_unpackhi_epi64(B0, _mm_unpacklo_epi64(B1, B1)); \
B1 = _mm_unpackhi_epi64(B1, _mm_unpacklo_epi64(t1, t1)); \
} while ((void)0, 0)
#define UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \
do { \
__m128i t0, t1; \
t0 = C0; \
C0 = C1; \
C1 = t0; \
t0 = B0; \
t1 = D0; \
B0 = _mm_unpackhi_epi64(B1, _mm_unpacklo_epi64(B0, B0)); \
B1 = _mm_unpackhi_epi64(t0, _mm_unpacklo_epi64(B1, B1)); \
D0 = _mm_unpackhi_epi64(D0, _mm_unpacklo_epi64(D1, D1)); \
D1 = _mm_unpackhi_epi64(D1, _mm_unpacklo_epi64(t1, t1)); \
} while ((void)0, 0)
#endif
#define BLAKE2_ROUND(A0, A1, B0, B1, C0, C1, D0, D1) \
do { \
G1(A0, B0, C0, D0, A1, B1, C1, D1); \
G2(A0, B0, C0, D0, A1, B1, C1, D1); \
\
DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1); \
\
G1(A0, B0, C0, D0, A1, B1, C1, D1); \
G2(A0, B0, C0, D0, A1, B1, C1, D1); \
\
UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1); \
} while ((void)0, 0)
#else /* __AVX2__ */
#include <immintrin.h>
#define rotr32(x) _mm256_shuffle_epi32(x, _MM_SHUFFLE(2, 3, 0, 1))
#define rotr24(x) _mm256_shuffle_epi8(x, _mm256_setr_epi8(3, 4, 5, 6, 7, 0, 1, 2, 11, 12, 13, 14, 15, 8, 9, 10, 3, 4, 5, 6, 7, 0, 1, 2, 11, 12, 13, 14, 15, 8, 9, 10))
#define rotr16(x) _mm256_shuffle_epi8(x, _mm256_setr_epi8(2, 3, 4, 5, 6, 7, 0, 1, 10, 11, 12, 13, 14, 15, 8, 9, 2, 3, 4, 5, 6, 7, 0, 1, 10, 11, 12, 13, 14, 15, 8, 9))
#define rotr63(x) _mm256_xor_si256(_mm256_srli_epi64((x), 63), _mm256_add_epi64((x), (x)))
#define G1_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \
do { \
__m256i ml = _mm256_mul_epu32(A0, B0); \
ml = _mm256_add_epi64(ml, ml); \
A0 = _mm256_add_epi64(A0, _mm256_add_epi64(B0, ml)); \
D0 = _mm256_xor_si256(D0, A0); \
D0 = rotr32(D0); \
\
ml = _mm256_mul_epu32(C0, D0); \
ml = _mm256_add_epi64(ml, ml); \
C0 = _mm256_add_epi64(C0, _mm256_add_epi64(D0, ml)); \
\
B0 = _mm256_xor_si256(B0, C0); \
B0 = rotr24(B0); \
\
ml = _mm256_mul_epu32(A1, B1); \
ml = _mm256_add_epi64(ml, ml); \
A1 = _mm256_add_epi64(A1, _mm256_add_epi64(B1, ml)); \
D1 = _mm256_xor_si256(D1, A1); \
D1 = rotr32(D1); \
\
ml = _mm256_mul_epu32(C1, D1); \
ml = _mm256_add_epi64(ml, ml); \
C1 = _mm256_add_epi64(C1, _mm256_add_epi64(D1, ml)); \
\
B1 = _mm256_xor_si256(B1, C1); \
B1 = rotr24(B1); \
} while((void)0, 0);
#define G2_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \
do { \
__m256i ml = _mm256_mul_epu32(A0, B0); \
ml = _mm256_add_epi64(ml, ml); \
A0 = _mm256_add_epi64(A0, _mm256_add_epi64(B0, ml)); \
D0 = _mm256_xor_si256(D0, A0); \
D0 = rotr16(D0); \
\
ml = _mm256_mul_epu32(C0, D0); \
ml = _mm256_add_epi64(ml, ml); \
C0 = _mm256_add_epi64(C0, _mm256_add_epi64(D0, ml)); \
B0 = _mm256_xor_si256(B0, C0); \
B0 = rotr63(B0); \
\
ml = _mm256_mul_epu32(A1, B1); \
ml = _mm256_add_epi64(ml, ml); \
A1 = _mm256_add_epi64(A1, _mm256_add_epi64(B1, ml)); \
D1 = _mm256_xor_si256(D1, A1); \
D1 = rotr16(D1); \
\
ml = _mm256_mul_epu32(C1, D1); \
ml = _mm256_add_epi64(ml, ml); \
C1 = _mm256_add_epi64(C1, _mm256_add_epi64(D1, ml)); \
B1 = _mm256_xor_si256(B1, C1); \
B1 = rotr63(B1); \
} while((void)0, 0);
#define DIAGONALIZE_1(A0, B0, C0, D0, A1, B1, C1, D1) \
do { \
B0 = _mm256_permute4x64_epi64(B0, _MM_SHUFFLE(0, 3, 2, 1)); \
C0 = _mm256_permute4x64_epi64(C0, _MM_SHUFFLE(1, 0, 3, 2)); \
D0 = _mm256_permute4x64_epi64(D0, _MM_SHUFFLE(2, 1, 0, 3)); \
\
B1 = _mm256_permute4x64_epi64(B1, _MM_SHUFFLE(0, 3, 2, 1)); \
C1 = _mm256_permute4x64_epi64(C1, _MM_SHUFFLE(1, 0, 3, 2)); \
D1 = _mm256_permute4x64_epi64(D1, _MM_SHUFFLE(2, 1, 0, 3)); \
} while((void)0, 0);
#define DIAGONALIZE_2(A0, A1, B0, B1, C0, C1, D0, D1) \
do { \
__m256i tmp1 = _mm256_blend_epi32(B0, B1, 0xCC); \
__m256i tmp2 = _mm256_blend_epi32(B0, B1, 0x33); \
B1 = _mm256_permute4x64_epi64(tmp1, _MM_SHUFFLE(2,3,0,1)); \
B0 = _mm256_permute4x64_epi64(tmp2, _MM_SHUFFLE(2,3,0,1)); \
\
tmp1 = C0; \
C0 = C1; \
C1 = tmp1; \
\
tmp1 = _mm256_blend_epi32(D0, D1, 0xCC); \
tmp2 = _mm256_blend_epi32(D0, D1, 0x33); \
D0 = _mm256_permute4x64_epi64(tmp1, _MM_SHUFFLE(2,3,0,1)); \
D1 = _mm256_permute4x64_epi64(tmp2, _MM_SHUFFLE(2,3,0,1)); \
} while(0);
#define UNDIAGONALIZE_1(A0, B0, C0, D0, A1, B1, C1, D1) \
do { \
B0 = _mm256_permute4x64_epi64(B0, _MM_SHUFFLE(2, 1, 0, 3)); \
C0 = _mm256_permute4x64_epi64(C0, _MM_SHUFFLE(1, 0, 3, 2)); \
D0 = _mm256_permute4x64_epi64(D0, _MM_SHUFFLE(0, 3, 2, 1)); \
\
B1 = _mm256_permute4x64_epi64(B1, _MM_SHUFFLE(2, 1, 0, 3)); \
C1 = _mm256_permute4x64_epi64(C1, _MM_SHUFFLE(1, 0, 3, 2)); \
D1 = _mm256_permute4x64_epi64(D1, _MM_SHUFFLE(0, 3, 2, 1)); \
} while((void)0, 0);
#define UNDIAGONALIZE_2(A0, A1, B0, B1, C0, C1, D0, D1) \
do { \
__m256i tmp1 = _mm256_blend_epi32(B0, B1, 0xCC); \
__m256i tmp2 = _mm256_blend_epi32(B0, B1, 0x33); \
B0 = _mm256_permute4x64_epi64(tmp1, _MM_SHUFFLE(2,3,0,1)); \
B1 = _mm256_permute4x64_epi64(tmp2, _MM_SHUFFLE(2,3,0,1)); \
\
tmp1 = C0; \
C0 = C1; \
C1 = tmp1; \
\
tmp1 = _mm256_blend_epi32(D0, D1, 0x33); \
tmp2 = _mm256_blend_epi32(D0, D1, 0xCC); \
D0 = _mm256_permute4x64_epi64(tmp1, _MM_SHUFFLE(2,3,0,1)); \
D1 = _mm256_permute4x64_epi64(tmp2, _MM_SHUFFLE(2,3,0,1)); \
} while((void)0, 0);
#define BLAKE2_ROUND_1(A0, A1, B0, B1, C0, C1, D0, D1) \
do{ \
G1_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \
G2_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \
\
DIAGONALIZE_1(A0, B0, C0, D0, A1, B1, C1, D1) \
\
G1_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \
G2_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \
\
UNDIAGONALIZE_1(A0, B0, C0, D0, A1, B1, C1, D1) \
} while((void)0, 0);
#define BLAKE2_ROUND_2(A0, A1, B0, B1, C0, C1, D0, D1) \
do{ \
G1_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \
G2_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \
\
DIAGONALIZE_2(A0, A1, B0, B1, C0, C1, D0, D1) \
\
G1_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \
G2_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \
\
UNDIAGONALIZE_2(A0, A1, B0, B1, C0, C1, D0, D1) \
} while((void)0, 0);
#endif /* __AVX2__ */
#else /* __AVX512F__ */
#include <immintrin.h>
#define ror64(x, n) _mm512_ror_epi64((x), (n))
static __m512i muladd(__m512i x, __m512i y)
{
__m512i z = _mm512_mul_epu32(x, y);
return _mm512_add_epi64(_mm512_add_epi64(x, y), _mm512_add_epi64(z, z));
}
#define G1(A0, B0, C0, D0, A1, B1, C1, D1) \
do { \
A0 = muladd(A0, B0); \
A1 = muladd(A1, B1); \
\
D0 = _mm512_xor_si512(D0, A0); \
D1 = _mm512_xor_si512(D1, A1); \
\
D0 = ror64(D0, 32); \
D1 = ror64(D1, 32); \
\
C0 = muladd(C0, D0); \
C1 = muladd(C1, D1); \
\
B0 = _mm512_xor_si512(B0, C0); \
B1 = _mm512_xor_si512(B1, C1); \
\
B0 = ror64(B0, 24); \
B1 = ror64(B1, 24); \
} while ((void)0, 0)
#define G2(A0, B0, C0, D0, A1, B1, C1, D1) \
do { \
A0 = muladd(A0, B0); \
A1 = muladd(A1, B1); \
\
D0 = _mm512_xor_si512(D0, A0); \
D1 = _mm512_xor_si512(D1, A1); \
\
D0 = ror64(D0, 16); \
D1 = ror64(D1, 16); \
\
C0 = muladd(C0, D0); \
C1 = muladd(C1, D1); \
\
B0 = _mm512_xor_si512(B0, C0); \
B1 = _mm512_xor_si512(B1, C1); \
\
B0 = ror64(B0, 63); \
B1 = ror64(B1, 63); \
} while ((void)0, 0)
#define DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \
do { \
B0 = _mm512_permutex_epi64(B0, _MM_SHUFFLE(0, 3, 2, 1)); \
B1 = _mm512_permutex_epi64(B1, _MM_SHUFFLE(0, 3, 2, 1)); \
\
C0 = _mm512_permutex_epi64(C0, _MM_SHUFFLE(1, 0, 3, 2)); \
C1 = _mm512_permutex_epi64(C1, _MM_SHUFFLE(1, 0, 3, 2)); \
\
D0 = _mm512_permutex_epi64(D0, _MM_SHUFFLE(2, 1, 0, 3)); \
D1 = _mm512_permutex_epi64(D1, _MM_SHUFFLE(2, 1, 0, 3)); \
} while ((void)0, 0)
#define UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \
do { \
B0 = _mm512_permutex_epi64(B0, _MM_SHUFFLE(2, 1, 0, 3)); \
B1 = _mm512_permutex_epi64(B1, _MM_SHUFFLE(2, 1, 0, 3)); \
\
C0 = _mm512_permutex_epi64(C0, _MM_SHUFFLE(1, 0, 3, 2)); \
C1 = _mm512_permutex_epi64(C1, _MM_SHUFFLE(1, 0, 3, 2)); \
\
D0 = _mm512_permutex_epi64(D0, _MM_SHUFFLE(0, 3, 2, 1)); \
D1 = _mm512_permutex_epi64(D1, _MM_SHUFFLE(0, 3, 2, 1)); \
} while ((void)0, 0)
#define BLAKE2_ROUND(A0, B0, C0, D0, A1, B1, C1, D1) \
do { \
G1(A0, B0, C0, D0, A1, B1, C1, D1); \
G2(A0, B0, C0, D0, A1, B1, C1, D1); \
\
DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1); \
\
G1(A0, B0, C0, D0, A1, B1, C1, D1); \
G2(A0, B0, C0, D0, A1, B1, C1, D1); \
\
UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1); \
} while ((void)0, 0)
#define SWAP_HALVES(A0, A1) \
do { \
__m512i t0, t1; \
t0 = _mm512_shuffle_i64x2(A0, A1, _MM_SHUFFLE(1, 0, 1, 0)); \
t1 = _mm512_shuffle_i64x2(A0, A1, _MM_SHUFFLE(3, 2, 3, 2)); \
A0 = t0; \
A1 = t1; \
} while((void)0, 0)
#define SWAP_QUARTERS(A0, A1) \
do { \
SWAP_HALVES(A0, A1); \
A0 = _mm512_permutexvar_epi64(_mm512_setr_epi64(0, 1, 4, 5, 2, 3, 6, 7), A0); \
A1 = _mm512_permutexvar_epi64(_mm512_setr_epi64(0, 1, 4, 5, 2, 3, 6, 7), A1); \
} while((void)0, 0)
#define UNSWAP_QUARTERS(A0, A1) \
do { \
A0 = _mm512_permutexvar_epi64(_mm512_setr_epi64(0, 1, 4, 5, 2, 3, 6, 7), A0); \
A1 = _mm512_permutexvar_epi64(_mm512_setr_epi64(0, 1, 4, 5, 2, 3, 6, 7), A1); \
SWAP_HALVES(A0, A1); \
} while((void)0, 0)
#define BLAKE2_ROUND_1(A0, C0, B0, D0, A1, C1, B1, D1) \
do { \
SWAP_HALVES(A0, B0); \
SWAP_HALVES(C0, D0); \
SWAP_HALVES(A1, B1); \
SWAP_HALVES(C1, D1); \
BLAKE2_ROUND(A0, B0, C0, D0, A1, B1, C1, D1); \
SWAP_HALVES(A0, B0); \
SWAP_HALVES(C0, D0); \
SWAP_HALVES(A1, B1); \
SWAP_HALVES(C1, D1); \
} while ((void)0, 0)
#define BLAKE2_ROUND_2(A0, A1, B0, B1, C0, C1, D0, D1) \
do { \
SWAP_QUARTERS(A0, A1); \
SWAP_QUARTERS(B0, B1); \
SWAP_QUARTERS(C0, C1); \
SWAP_QUARTERS(D0, D1); \
BLAKE2_ROUND(A0, B0, C0, D0, A1, B1, C1, D1); \
UNSWAP_QUARTERS(A0, A1); \
UNSWAP_QUARTERS(B0, B1); \
UNSWAP_QUARTERS(C0, C1); \
UNSWAP_QUARTERS(D0, D1); \
} while ((void)0, 0)
#endif /* __AVX512F__ */
#endif /* BLAKE_ROUND_MKA_OPT_H */

View File

@@ -0,0 +1,56 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#ifndef BLAKE_ROUND_MKA_H
#define BLAKE_ROUND_MKA_H
#include "blake2.h"
#include "blake2-impl.h"
/* designed by the Lyra PHC team */
static BLAKE2_INLINE uint64_t fBlaMka(uint64_t x, uint64_t y) {
const uint64_t m = UINT64_C(0xFFFFFFFF);
const uint64_t xy = (x & m) * (y & m);
return x + y + 2 * xy;
}
#define G(a, b, c, d) \
do { \
a = fBlaMka(a, b); \
d = rotr64(d ^ a, 32); \
c = fBlaMka(c, d); \
b = rotr64(b ^ c, 24); \
a = fBlaMka(a, b); \
d = rotr64(d ^ a, 16); \
c = fBlaMka(c, d); \
b = rotr64(b ^ c, 63); \
} while ((void)0, 0)
#define BLAKE2_ROUND_NOMSG(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, \
v12, v13, v14, v15) \
do { \
G(v0, v4, v8, v12); \
G(v1, v5, v9, v13); \
G(v2, v6, v10, v14); \
G(v3, v7, v11, v15); \
G(v0, v5, v10, v15); \
G(v1, v6, v11, v12); \
G(v2, v7, v8, v13); \
G(v3, v4, v9, v14); \
} while ((void)0, 0)
#endif

View File

@@ -0,0 +1,641 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
/*For memory wiping*/
#ifdef _MSC_VER
#include <windows.h>
#include <winbase.h> /* For SecureZeroMemory */
#endif
#if defined __STDC_LIB_EXT1__
#define __STDC_WANT_LIB_EXT1__ 1
#endif
#define VC_GE_2005(version) (version >= 1400)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "core.h"
#include "thread.h"
#include "blake2/blake2.h"
#include "blake2/blake2-impl.h"
#ifdef GENKAT
#include "genkat.h"
#endif
#if defined(__clang__)
#if __has_attribute(optnone)
#define NOT_OPTIMIZED __attribute__((optnone))
#endif
#elif defined(__GNUC__)
#define GCC_VERSION \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if GCC_VERSION >= 40400
#define NOT_OPTIMIZED __attribute__((optimize("O0")))
#endif
#endif
#ifndef NOT_OPTIMIZED
#define NOT_OPTIMIZED
#endif
/***************Instance and Position constructors**********/
void init_block_value(block *b, uint8_t in) { memset(b->v, in, sizeof(b->v)); }
void copy_block(block *dst, const block *src) {
memcpy(dst->v, src->v, sizeof(uint64_t) * ARGON2_QWORDS_IN_BLOCK);
}
void xor_block(block *dst, const block *src) {
int i;
for (i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) {
dst->v[i] ^= src->v[i];
}
}
static void load_block(block *dst, const void *input) {
unsigned i;
for (i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) {
dst->v[i] = load64((const uint8_t *)input + i * sizeof(dst->v[i]));
}
}
static void store_block(void *output, const block *src) {
unsigned i;
for (i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) {
store64((uint8_t *)output + i * sizeof(src->v[i]), src->v[i]);
}
}
/***************Memory functions*****************/
int allocate_memory(const argon2_context *context, uint8_t **memory,
size_t num, size_t size) {
size_t memory_size = num*size;
if (memory == NULL) {
return ARGON2_MEMORY_ALLOCATION_ERROR;
}
/* 1. Check for multiplication overflow */
if (size != 0 && memory_size / size != num) {
return ARGON2_MEMORY_ALLOCATION_ERROR;
}
/* 2. Try to allocate with appropriate allocator */
if (context->allocate_cbk) {
(context->allocate_cbk)(memory, memory_size);
} else {
*memory = malloc(memory_size);
}
if (*memory == NULL) {
return ARGON2_MEMORY_ALLOCATION_ERROR;
}
return ARGON2_OK;
}
void free_memory(const argon2_context *context, uint8_t *memory,
size_t num, size_t size) {
size_t memory_size = num*size;
clear_internal_memory(memory, memory_size);
if (context->free_cbk) {
(context->free_cbk)(memory, memory_size);
} else {
free(memory);
}
}
void NOT_OPTIMIZED secure_wipe_memory(void *v, size_t n) {
#if defined(_MSC_VER) && VC_GE_2005(_MSC_VER)
SecureZeroMemory(v, n);
#elif defined memset_s
memset_s(v, n, 0, n);
#elif defined(HAVE_EXPLICIT_BZERO)
explicit_bzero(v, n);
#else
static void *(*const volatile memset_sec)(void *, int, size_t) = &memset;
memset_sec(v, 0, n);
#endif
}
/* Memory clear flag defaults to true. */
int FLAG_clear_internal_memory = 1;
void clear_internal_memory(void *v, size_t n) {
if (FLAG_clear_internal_memory && v) {
secure_wipe_memory(v, n);
}
}
void finalize(const argon2_context *context, argon2_instance_t *instance) {
if (context != NULL && instance != NULL) {
block blockhash;
uint32_t l;
copy_block(&blockhash, instance->memory + instance->lane_length - 1);
/* XOR the last blocks */
for (l = 1; l < instance->lanes; ++l) {
uint32_t last_block_in_lane =
l * instance->lane_length + (instance->lane_length - 1);
xor_block(&blockhash, instance->memory + last_block_in_lane);
}
/* Hash the result */
{
uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE];
store_block(blockhash_bytes, &blockhash);
blake2b_long(context->out, context->outlen, blockhash_bytes,
ARGON2_BLOCK_SIZE);
/* clear blockhash and blockhash_bytes */
clear_internal_memory(blockhash.v, ARGON2_BLOCK_SIZE);
clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE);
}
#ifdef GENKAT
print_tag(context->out, context->outlen);
#endif
free_memory(context, (uint8_t *)instance->memory,
instance->memory_blocks, sizeof(block));
}
}
uint32_t index_alpha(const argon2_instance_t *instance,
const argon2_position_t *position, uint32_t pseudo_rand,
int same_lane) {
/*
* Pass 0:
* This lane : all already finished segments plus already constructed
* blocks in this segment
* Other lanes : all already finished segments
* Pass 1+:
* This lane : (SYNC_POINTS - 1) last segments plus already constructed
* blocks in this segment
* Other lanes : (SYNC_POINTS - 1) last segments
*/
uint32_t reference_area_size;
uint64_t relative_position;
uint32_t start_position, absolute_position;
if (0 == position->pass) {
/* First pass */
if (0 == position->slice) {
/* First slice */
reference_area_size =
position->index - 1; /* all but the previous */
} else {
if (same_lane) {
/* The same lane => add current segment */
reference_area_size =
position->slice * instance->segment_length +
position->index - 1;
} else {
reference_area_size =
position->slice * instance->segment_length +
((position->index == 0) ? (-1) : 0);
}
}
} else {
/* Second pass */
if (same_lane) {
reference_area_size = instance->lane_length -
instance->segment_length + position->index -
1;
} else {
reference_area_size = instance->lane_length -
instance->segment_length +
((position->index == 0) ? (-1) : 0);
}
}
/* 1.2.4. Mapping pseudo_rand to 0..<reference_area_size-1> and produce
* relative position */
relative_position = pseudo_rand;
relative_position = relative_position * relative_position >> 32;
relative_position = reference_area_size - 1 -
(reference_area_size * relative_position >> 32);
/* 1.2.5 Computing starting position */
start_position = 0;
if (0 != position->pass) {
start_position = (position->slice == ARGON2_SYNC_POINTS - 1)
? 0
: (position->slice + 1) * instance->segment_length;
}
/* 1.2.6. Computing absolute position */
absolute_position = (start_position + relative_position) %
instance->lane_length; /* absolute position */
return absolute_position;
}
/* Single-threaded version for p=1 case */
static int fill_memory_blocks_st(argon2_instance_t *instance) {
uint32_t r, s, l;
for (r = 0; r < instance->passes; ++r) {
for (s = 0; s < ARGON2_SYNC_POINTS; ++s) {
for (l = 0; l < instance->lanes; ++l) {
argon2_position_t position = {r, l, (uint8_t)s, 0};
fill_segment(instance, position);
}
}
#ifdef GENKAT
internal_kat(instance, r); /* Print all memory blocks */
#endif
}
return ARGON2_OK;
}
#if !defined(ARGON2_NO_THREADS)
#ifdef _WIN32
static unsigned __stdcall fill_segment_thr(void *thread_data)
#else
static void *fill_segment_thr(void *thread_data)
#endif
{
argon2_thread_data *my_data = thread_data;
fill_segment(my_data->instance_ptr, my_data->pos);
argon2_thread_exit();
return 0;
}
/* Multi-threaded version for p > 1 case */
static int fill_memory_blocks_mt(argon2_instance_t *instance) {
uint32_t r, s;
argon2_thread_handle_t *thread = NULL;
argon2_thread_data *thr_data = NULL;
int rc = ARGON2_OK;
/* 1. Allocating space for threads */
thread = calloc(instance->lanes, sizeof(argon2_thread_handle_t));
if (thread == NULL) {
rc = ARGON2_MEMORY_ALLOCATION_ERROR;
goto fail;
}
thr_data = calloc(instance->lanes, sizeof(argon2_thread_data));
if (thr_data == NULL) {
rc = ARGON2_MEMORY_ALLOCATION_ERROR;
goto fail;
}
for (r = 0; r < instance->passes; ++r) {
for (s = 0; s < ARGON2_SYNC_POINTS; ++s) {
uint32_t l, ll;
/* 2. Calling threads */
for (l = 0; l < instance->lanes; ++l) {
argon2_position_t position;
/* 2.1 Join a thread if limit is exceeded */
if (l >= instance->threads) {
if (argon2_thread_join(thread[l - instance->threads])) {
rc = ARGON2_THREAD_FAIL;
goto fail;
}
}
/* 2.2 Create thread */
position.pass = r;
position.lane = l;
position.slice = (uint8_t)s;
position.index = 0;
thr_data[l].instance_ptr =
instance; /* preparing the thread input */
memcpy(&(thr_data[l].pos), &position,
sizeof(argon2_position_t));
if (argon2_thread_create(&thread[l], &fill_segment_thr,
(void *)&thr_data[l])) {
/* Wait for already running threads */
for (ll = 0; ll < l; ++ll)
argon2_thread_join(thread[ll]);
rc = ARGON2_THREAD_FAIL;
goto fail;
}
/* fill_segment(instance, position); */
/*Non-thread equivalent of the lines above */
}
/* 3. Joining remaining threads */
for (l = instance->lanes - instance->threads; l < instance->lanes;
++l) {
if (argon2_thread_join(thread[l])) {
rc = ARGON2_THREAD_FAIL;
goto fail;
}
}
}
#ifdef GENKAT
internal_kat(instance, r); /* Print all memory blocks */
#endif
}
fail:
if (thread != NULL) {
free(thread);
}
if (thr_data != NULL) {
free(thr_data);
}
return rc;
}
#endif /* ARGON2_NO_THREADS */
int fill_memory_blocks(argon2_instance_t *instance) {
if (instance == NULL || instance->lanes == 0) {
return ARGON2_INCORRECT_PARAMETER;
}
#if defined(ARGON2_NO_THREADS)
return fill_memory_blocks_st(instance);
#else
return instance->threads == 1 ?
fill_memory_blocks_st(instance) : fill_memory_blocks_mt(instance);
#endif
}
int validate_inputs(const argon2_context *context) {
if (NULL == context) {
return ARGON2_INCORRECT_PARAMETER;
}
if (NULL == context->out) {
return ARGON2_OUTPUT_PTR_NULL;
}
/* Validate output length */
if (ARGON2_MIN_OUTLEN > context->outlen) {
return ARGON2_OUTPUT_TOO_SHORT;
}
if (ARGON2_MAX_OUTLEN < context->outlen) {
return ARGON2_OUTPUT_TOO_LONG;
}
/* Validate password (required param) */
if (NULL == context->pwd) {
if (0 != context->pwdlen) {
return ARGON2_PWD_PTR_MISMATCH;
}
}
#if ARGON2_MIN_PWD_LENGTH > 0 /* cryptsetup: fix gcc warning */
if (ARGON2_MIN_PWD_LENGTH > context->pwdlen) {
return ARGON2_PWD_TOO_SHORT;
}
#endif
if (ARGON2_MAX_PWD_LENGTH < context->pwdlen) {
return ARGON2_PWD_TOO_LONG;
}
/* Validate salt (required param) */
if (NULL == context->salt) {
if (0 != context->saltlen) {
return ARGON2_SALT_PTR_MISMATCH;
}
}
if (ARGON2_MIN_SALT_LENGTH > context->saltlen) {
return ARGON2_SALT_TOO_SHORT;
}
if (ARGON2_MAX_SALT_LENGTH < context->saltlen) {
return ARGON2_SALT_TOO_LONG;
}
/* Validate secret (optional param) */
if (NULL == context->secret) {
if (0 != context->secretlen) {
return ARGON2_SECRET_PTR_MISMATCH;
}
} else {
#if ARGON2_MIN_SECRET > 0 /* cryptsetup: fix gcc warning */
if (ARGON2_MIN_SECRET > context->secretlen) {
return ARGON2_SECRET_TOO_SHORT;
}
#endif
if (ARGON2_MAX_SECRET < context->secretlen) {
return ARGON2_SECRET_TOO_LONG;
}
}
/* Validate associated data (optional param) */
if (NULL == context->ad) {
if (0 != context->adlen) {
return ARGON2_AD_PTR_MISMATCH;
}
} else {
#if ARGON2_MIN_AD_LENGTH > 0 /* cryptsetup: fix gcc warning */
if (ARGON2_MIN_AD_LENGTH > context->adlen) {
return ARGON2_AD_TOO_SHORT;
}
#endif
if (ARGON2_MAX_AD_LENGTH < context->adlen) {
return ARGON2_AD_TOO_LONG;
}
}
/* Validate memory cost */
if (ARGON2_MIN_MEMORY > context->m_cost) {
return ARGON2_MEMORY_TOO_LITTLE;
}
#if 0 /* UINT32_MAX, cryptsetup: fix gcc warning */
if (ARGON2_MAX_MEMORY < context->m_cost) {
return ARGON2_MEMORY_TOO_MUCH;
}
#endif
if (context->m_cost < 8 * context->lanes) {
return ARGON2_MEMORY_TOO_LITTLE;
}
/* Validate time cost */
if (ARGON2_MIN_TIME > context->t_cost) {
return ARGON2_TIME_TOO_SMALL;
}
if (ARGON2_MAX_TIME < context->t_cost) {
return ARGON2_TIME_TOO_LARGE;
}
/* Validate lanes */
if (ARGON2_MIN_LANES > context->lanes) {
return ARGON2_LANES_TOO_FEW;
}
if (ARGON2_MAX_LANES < context->lanes) {
return ARGON2_LANES_TOO_MANY;
}
/* Validate threads */
if (ARGON2_MIN_THREADS > context->threads) {
return ARGON2_THREADS_TOO_FEW;
}
if (ARGON2_MAX_THREADS < context->threads) {
return ARGON2_THREADS_TOO_MANY;
}
if (NULL != context->allocate_cbk && NULL == context->free_cbk) {
return ARGON2_FREE_MEMORY_CBK_NULL;
}
if (NULL == context->allocate_cbk && NULL != context->free_cbk) {
return ARGON2_ALLOCATE_MEMORY_CBK_NULL;
}
return ARGON2_OK;
}
void fill_first_blocks(uint8_t *blockhash, const argon2_instance_t *instance) {
uint32_t l;
/* Make the first and second block in each lane as G(H0||0||i) or
G(H0||1||i) */
uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE];
for (l = 0; l < instance->lanes; ++l) {
store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, 0);
store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH + 4, l);
blake2b_long(blockhash_bytes, ARGON2_BLOCK_SIZE, blockhash,
ARGON2_PREHASH_SEED_LENGTH);
load_block(&instance->memory[l * instance->lane_length + 0],
blockhash_bytes);
store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, 1);
blake2b_long(blockhash_bytes, ARGON2_BLOCK_SIZE, blockhash,
ARGON2_PREHASH_SEED_LENGTH);
load_block(&instance->memory[l * instance->lane_length + 1],
blockhash_bytes);
}
clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE);
}
void initial_hash(uint8_t *blockhash, argon2_context *context,
argon2_type type) {
blake2b_state BlakeHash;
uint8_t value[sizeof(uint32_t)];
if (NULL == context || NULL == blockhash) {
return;
}
blake2b_init(&BlakeHash, ARGON2_PREHASH_DIGEST_LENGTH);
store32(&value, context->lanes);
blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
store32(&value, context->outlen);
blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
store32(&value, context->m_cost);
blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
store32(&value, context->t_cost);
blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
store32(&value, context->version);
blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
store32(&value, (uint32_t)type);
blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
store32(&value, context->pwdlen);
blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
if (context->pwd != NULL) {
blake2b_update(&BlakeHash, (const uint8_t *)context->pwd,
context->pwdlen);
if (context->flags & ARGON2_FLAG_CLEAR_PASSWORD) {
secure_wipe_memory(context->pwd, context->pwdlen);
context->pwdlen = 0;
}
}
store32(&value, context->saltlen);
blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
if (context->salt != NULL) {
blake2b_update(&BlakeHash, (const uint8_t *)context->salt,
context->saltlen);
}
store32(&value, context->secretlen);
blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
if (context->secret != NULL) {
blake2b_update(&BlakeHash, (const uint8_t *)context->secret,
context->secretlen);
if (context->flags & ARGON2_FLAG_CLEAR_SECRET) {
secure_wipe_memory(context->secret, context->secretlen);
context->secretlen = 0;
}
}
store32(&value, context->adlen);
blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
if (context->ad != NULL) {
blake2b_update(&BlakeHash, (const uint8_t *)context->ad,
context->adlen);
}
blake2b_final(&BlakeHash, blockhash, ARGON2_PREHASH_DIGEST_LENGTH);
}
int initialize(argon2_instance_t *instance, argon2_context *context) {
uint8_t blockhash[ARGON2_PREHASH_SEED_LENGTH];
int result = ARGON2_OK;
if (instance == NULL || context == NULL)
return ARGON2_INCORRECT_PARAMETER;
instance->context_ptr = context;
/* 1. Memory allocation */
result = allocate_memory(context, (uint8_t **)&(instance->memory),
instance->memory_blocks, sizeof(block));
if (result != ARGON2_OK) {
return result;
}
/* 2. Initial hashing */
/* H_0 + 8 extra bytes to produce the first blocks */
/* uint8_t blockhash[ARGON2_PREHASH_SEED_LENGTH]; */
/* Hashing all inputs */
initial_hash(blockhash, context, instance->type);
/* Zeroing 8 extra bytes */
clear_internal_memory(blockhash + ARGON2_PREHASH_DIGEST_LENGTH,
ARGON2_PREHASH_SEED_LENGTH -
ARGON2_PREHASH_DIGEST_LENGTH);
#ifdef GENKAT
initial_kat(blockhash, context, instance->type);
#endif
/* 3. Creating first blocks, we always have at least two blocks in a slice
*/
fill_first_blocks(blockhash, instance);
/* Clearing the hash */
clear_internal_memory(blockhash, ARGON2_PREHASH_SEED_LENGTH);
return ARGON2_OK;
}

View File

@@ -0,0 +1,228 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#ifndef ARGON2_CORE_H
#define ARGON2_CORE_H
#include "argon2.h"
#define CONST_CAST(x) (x)(uintptr_t)
/**********************Argon2 internal constants*******************************/
enum argon2_core_constants {
/* Memory block size in bytes */
ARGON2_BLOCK_SIZE = 1024,
ARGON2_QWORDS_IN_BLOCK = ARGON2_BLOCK_SIZE / 8,
ARGON2_OWORDS_IN_BLOCK = ARGON2_BLOCK_SIZE / 16,
ARGON2_HWORDS_IN_BLOCK = ARGON2_BLOCK_SIZE / 32,
ARGON2_512BIT_WORDS_IN_BLOCK = ARGON2_BLOCK_SIZE / 64,
/* Number of pseudo-random values generated by one call to Blake in Argon2i
to
generate reference block positions */
ARGON2_ADDRESSES_IN_BLOCK = 128,
/* Pre-hashing digest length and its extension*/
ARGON2_PREHASH_DIGEST_LENGTH = 64,
ARGON2_PREHASH_SEED_LENGTH = 72
};
/*************************Argon2 internal data types***********************/
/*
* Structure for the (1KB) memory block implemented as 128 64-bit words.
* Memory blocks can be copied, XORed. Internal words can be accessed by [] (no
* bounds checking).
*/
typedef struct block_ { uint64_t v[ARGON2_QWORDS_IN_BLOCK]; } block;
/*****************Functions that work with the block******************/
/* Initialize each byte of the block with @in */
void init_block_value(block *b, uint8_t in);
/* Copy block @src to block @dst */
void copy_block(block *dst, const block *src);
/* XOR @src onto @dst bytewise */
void xor_block(block *dst, const block *src);
/*
* Argon2 instance: memory pointer, number of passes, amount of memory, type,
* and derived values.
* Used to evaluate the number and location of blocks to construct in each
* thread
*/
typedef struct Argon2_instance_t {
block *memory; /* Memory pointer */
uint32_t version;
uint32_t passes; /* Number of passes */
uint32_t memory_blocks; /* Number of blocks in memory */
uint32_t segment_length;
uint32_t lane_length;
uint32_t lanes;
uint32_t threads;
argon2_type type;
int print_internals; /* whether to print the memory blocks */
argon2_context *context_ptr; /* points back to original context */
} argon2_instance_t;
/*
* Argon2 position: where we construct the block right now. Used to distribute
* work between threads.
*/
typedef struct Argon2_position_t {
uint32_t pass;
uint32_t lane;
uint8_t slice;
uint32_t index;
} argon2_position_t;
/*Struct that holds the inputs for thread handling FillSegment*/
typedef struct Argon2_thread_data {
argon2_instance_t *instance_ptr;
argon2_position_t pos;
} argon2_thread_data;
/*************************Argon2 core functions********************************/
/* Allocates memory to the given pointer, uses the appropriate allocator as
* specified in the context. Total allocated memory is num*size.
* @param context argon2_context which specifies the allocator
* @param memory pointer to the pointer to the memory
* @param size the size in bytes for each element to be allocated
* @param num the number of elements to be allocated
* @return ARGON2_OK if @memory is a valid pointer and memory is allocated
*/
int allocate_memory(const argon2_context *context, uint8_t **memory,
size_t num, size_t size);
/*
* Frees memory at the given pointer, uses the appropriate deallocator as
* specified in the context. Also cleans the memory using clear_internal_memory.
* @param context argon2_context which specifies the deallocator
* @param memory pointer to buffer to be freed
* @param size the size in bytes for each element to be deallocated
* @param num the number of elements to be deallocated
*/
void free_memory(const argon2_context *context, uint8_t *memory,
size_t num, size_t size);
/* Function that securely cleans the memory. This ignores any flags set
* regarding clearing memory. Usually one just calls clear_internal_memory.
* @param mem Pointer to the memory
* @param s Memory size in bytes
*/
void secure_wipe_memory(void *v, size_t n);
/* Function that securely clears the memory if FLAG_clear_internal_memory is
* set. If the flag isn't set, this function does nothing.
* @param mem Pointer to the memory
* @param s Memory size in bytes
*/
void clear_internal_memory(void *v, size_t n);
/*
* Computes absolute position of reference block in the lane following a skewed
* distribution and using a pseudo-random value as input
* @param instance Pointer to the current instance
* @param position Pointer to the current position
* @param pseudo_rand 32-bit pseudo-random value used to determine the position
* @param same_lane Indicates if the block will be taken from the current lane.
* If so we can reference the current segment
* @pre All pointers must be valid
*/
uint32_t index_alpha(const argon2_instance_t *instance,
const argon2_position_t *position, uint32_t pseudo_rand,
int same_lane);
/*
* Function that validates all inputs against predefined restrictions and return
* an error code
* @param context Pointer to current Argon2 context
* @return ARGON2_OK if everything is all right, otherwise one of error codes
* (all defined in <argon2.h>
*/
int validate_inputs(const argon2_context *context);
/*
* Hashes all the inputs into @a blockhash[PREHASH_DIGEST_LENGTH], clears
* password and secret if needed
* @param context Pointer to the Argon2 internal structure containing memory
* pointer, and parameters for time and space requirements.
* @param blockhash Buffer for pre-hashing digest
* @param type Argon2 type
* @pre @a blockhash must have at least @a PREHASH_DIGEST_LENGTH bytes
* allocated
*/
void initial_hash(uint8_t *blockhash, argon2_context *context,
argon2_type type);
/*
* Function creates first 2 blocks per lane
* @param instance Pointer to the current instance
* @param blockhash Pointer to the pre-hashing digest
* @pre blockhash must point to @a PREHASH_SEED_LENGTH allocated values
*/
void fill_first_blocks(uint8_t *blockhash, const argon2_instance_t *instance);
/*
* Function allocates memory, hashes the inputs with Blake, and creates first
* two blocks. Returns the pointer to the main memory with 2 blocks per lane
* initialized
* @param context Pointer to the Argon2 internal structure containing memory
* pointer, and parameters for time and space requirements.
* @param instance Current Argon2 instance
* @return Zero if successful, -1 if memory failed to allocate. @context->state
* will be modified if successful.
*/
int initialize(argon2_instance_t *instance, argon2_context *context);
/*
* XORing the last block of each lane, hashing it, making the tag. Deallocates
* the memory.
* @param context Pointer to current Argon2 context (use only the out parameters
* from it)
* @param instance Pointer to current instance of Argon2
* @pre instance->state must point to necessary amount of memory
* @pre context->out must point to outlen bytes of memory
* @pre if context->free_cbk is not NULL, it should point to a function that
* deallocates memory
*/
void finalize(const argon2_context *context, argon2_instance_t *instance);
/*
* Function that fills the segment using previous segments also from other
* threads
* @param context current context
* @param instance Pointer to the current instance
* @param position Current position
* @pre all block pointers must be valid
*/
void fill_segment(const argon2_instance_t *instance,
argon2_position_t position);
/*
* Function that fills the entire memory t_cost times based on the first two
* blocks in each lane
* @param instance Pointer to the current instance
* @return ARGON2_OK if successful, @context->state
*/
int fill_memory_blocks(argon2_instance_t *instance);
#endif

View File

@@ -0,0 +1,462 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include "encoding.h"
#include "core.h"
/*
* Example code for a decoder and encoder of "hash strings", with Argon2
* parameters.
*
* This code comprises three sections:
*
* -- The first section contains generic Base64 encoding and decoding
* functions. It is conceptually applicable to any hash function
* implementation that uses Base64 to encode and decode parameters,
* salts and outputs. It could be made into a library, provided that
* the relevant functions are made public (non-static) and be given
* reasonable names to avoid collisions with other functions.
*
* -- The second section is specific to Argon2. It encodes and decodes
* the parameters, salts and outputs. It does not compute the hash
* itself.
*
* The code was originally written by Thomas Pornin <pornin@bolet.org>,
* to whom comments and remarks may be sent. It is released under what
* should amount to Public Domain or its closest equivalent; the
* following mantra is supposed to incarnate that fact with all the
* proper legal rituals:
*
* ---------------------------------------------------------------------
* This file is provided under the terms of Creative Commons CC0 1.0
* Public Domain Dedication. To the extent possible under law, the
* author (Thomas Pornin) has waived all copyright and related or
* neighboring rights to this file. This work is published from: Canada.
* ---------------------------------------------------------------------
*
* Copyright (c) 2015 Thomas Pornin
*/
/* ==================================================================== */
/*
* Common code; could be shared between different hash functions.
*
* Note: the Base64 functions below assume that uppercase letters (resp.
* lowercase letters) have consecutive numerical codes, that fit on 8
* bits. All modern systems use ASCII-compatible charsets, where these
* properties are true. If you are stuck with a dinosaur of a system
* that still defaults to EBCDIC then you already have much bigger
* interoperability issues to deal with.
*/
/*
* Some macros for constant-time comparisons. These work over values in
* the 0..255 range. Returned value is 0x00 on "false", 0xFF on "true".
*/
#define EQ(x, y) ((((0U - ((unsigned)(x) ^ (unsigned)(y))) >> 8) & 0xFF) ^ 0xFF)
#define GT(x, y) ((((unsigned)(y) - (unsigned)(x)) >> 8) & 0xFF)
#define GE(x, y) (GT(y, x) ^ 0xFF)
#define LT(x, y) GT(y, x)
#define LE(x, y) GE(y, x)
/*
* Convert value x (0..63) to corresponding Base64 character.
*/
static int b64_byte_to_char(unsigned x) {
return (LT(x, 26) & (x + 'A')) |
(GE(x, 26) & LT(x, 52) & (x + ('a' - 26))) |
(GE(x, 52) & LT(x, 62) & (x + ('0' - 52))) | (EQ(x, 62) & '+') |
(EQ(x, 63) & '/');
}
/*
* Convert character c to the corresponding 6-bit value. If character c
* is not a Base64 character, then 0xFF (255) is returned.
*/
static unsigned b64_char_to_byte(int c) {
unsigned x;
x = (GE(c, 'A') & LE(c, 'Z') & (c - 'A')) |
(GE(c, 'a') & LE(c, 'z') & (c - ('a' - 26))) |
(GE(c, '0') & LE(c, '9') & (c - ('0' - 52))) | (EQ(c, '+') & 62) |
(EQ(c, '/') & 63);
return x | (EQ(x, 0) & (EQ(c, 'A') ^ 0xFF));
}
/*
* Convert some bytes to Base64. 'dst_len' is the length (in characters)
* of the output buffer 'dst'; if that buffer is not large enough to
* receive the result (including the terminating 0), then (size_t)-1
* is returned. Otherwise, the zero-terminated Base64 string is written
* in the buffer, and the output length (counted WITHOUT the terminating
* zero) is returned.
*/
static size_t to_base64(char *dst, size_t dst_len, const void *src,
size_t src_len) {
size_t olen;
const unsigned char *buf;
unsigned acc, acc_len;
olen = (src_len / 3) << 2;
switch (src_len % 3) {
case 2:
olen++;
/* fall through */
case 1:
olen += 2;
break;
}
if (dst_len <= olen) {
return (size_t)-1;
}
acc = 0;
acc_len = 0;
buf = (const unsigned char *)src;
while (src_len-- > 0) {
acc = (acc << 8) + (*buf++);
acc_len += 8;
while (acc_len >= 6) {
acc_len -= 6;
*dst++ = (char)b64_byte_to_char((acc >> acc_len) & 0x3F);
}
}
if (acc_len > 0) {
*dst++ = (char)b64_byte_to_char((acc << (6 - acc_len)) & 0x3F);
}
*dst++ = 0;
return olen;
}
/*
* Decode Base64 chars into bytes. The '*dst_len' value must initially
* contain the length of the output buffer '*dst'; when the decoding
* ends, the actual number of decoded bytes is written back in
* '*dst_len'.
*
* Decoding stops when a non-Base64 character is encountered, or when
* the output buffer capacity is exceeded. If an error occurred (output
* buffer is too small, invalid last characters leading to unprocessed
* buffered bits), then NULL is returned; otherwise, the returned value
* points to the first non-Base64 character in the source stream, which
* may be the terminating zero.
*/
static const char *from_base64(void *dst, size_t *dst_len, const char *src) {
size_t len;
unsigned char *buf;
unsigned acc, acc_len;
buf = (unsigned char *)dst;
len = 0;
acc = 0;
acc_len = 0;
for (;;) {
unsigned d;
d = b64_char_to_byte(*src);
if (d == 0xFF) {
break;
}
src++;
acc = (acc << 6) + d;
acc_len += 6;
if (acc_len >= 8) {
acc_len -= 8;
if ((len++) >= *dst_len) {
return NULL;
}
*buf++ = (acc >> acc_len) & 0xFF;
}
}
/*
* If the input length is equal to 1 modulo 4 (which is
* invalid), then there will remain 6 unprocessed bits;
* otherwise, only 0, 2 or 4 bits are buffered. The buffered
* bits must also all be zero.
*/
if (acc_len > 4 || (acc & (((unsigned)1 << acc_len) - 1)) != 0) {
return NULL;
}
*dst_len = len;
return src;
}
/*
* Decode decimal integer from 'str'; the value is written in '*v'.
* Returned value is a pointer to the next non-decimal character in the
* string. If there is no digit at all, or the value encoding is not
* minimal (extra leading zeros), or the value does not fit in an
* 'unsigned long', then NULL is returned.
*/
static const char *decode_decimal(const char *str, unsigned long *v) {
const char *orig;
unsigned long acc;
acc = 0;
for (orig = str;; str++) {
int c;
c = *str;
if (c < '0' || c > '9') {
break;
}
c -= '0';
if (acc > (ULONG_MAX / 10)) {
return NULL;
}
acc *= 10;
if ((unsigned long)c > (ULONG_MAX - acc)) {
return NULL;
}
acc += (unsigned long)c;
}
if (str == orig || (*orig == '0' && str != (orig + 1))) {
return NULL;
}
*v = acc;
return str;
}
/* ==================================================================== */
/*
* Code specific to Argon2.
*
* The code below applies the following format:
*
* $argon2<T>[$v=<num>]$m=<num>,t=<num>,p=<num>$<bin>$<bin>
*
* where <T> is either 'd', 'id', or 'i', <num> is a decimal integer (positive,
* fits in an 'unsigned long'), and <bin> is Base64-encoded data (no '=' padding
* characters, no newline or whitespace).
*
* The last two binary chunks (encoded in Base64) are, in that order,
* the salt and the output. Both are required. The binary salt length and the
* output length must be in the allowed ranges defined in argon2.h.
*
* The ctx struct must contain buffers large enough to hold the salt and pwd
* when it is fed into decode_string.
*/
int decode_string(argon2_context *ctx, const char *str, argon2_type type) {
/* check for prefix */
#define CC(prefix) \
do { \
size_t cc_len = strlen(prefix); \
if (strncmp(str, prefix, cc_len) != 0) { \
return ARGON2_DECODING_FAIL; \
} \
str += cc_len; \
} while ((void)0, 0)
/* optional prefix checking with supplied code */
#define CC_opt(prefix, code) \
do { \
size_t cc_len = strlen(prefix); \
if (strncmp(str, prefix, cc_len) == 0) { \
str += cc_len; \
{ code; } \
} \
} while ((void)0, 0)
/* Decoding prefix into decimal */
#define DECIMAL(x) \
do { \
unsigned long dec_x; \
str = decode_decimal(str, &dec_x); \
if (str == NULL) { \
return ARGON2_DECODING_FAIL; \
} \
(x) = dec_x; \
} while ((void)0, 0)
/* Decoding prefix into uint32_t decimal */
#define DECIMAL_U32(x) \
do { \
unsigned long dec_x; \
str = decode_decimal(str, &dec_x); \
if (str == NULL || dec_x > UINT32_MAX) { \
return ARGON2_DECODING_FAIL; \
} \
(x) = (uint32_t)dec_x; \
} while ((void)0, 0)
/* Decoding base64 into a binary buffer */
#define BIN(buf, max_len, len) \
do { \
size_t bin_len = (max_len); \
str = from_base64(buf, &bin_len, str); \
if (str == NULL || bin_len > UINT32_MAX) { \
return ARGON2_DECODING_FAIL; \
} \
(len) = (uint32_t)bin_len; \
} while ((void)0, 0)
size_t maxsaltlen = ctx->saltlen;
size_t maxoutlen = ctx->outlen;
int validation_result;
const char* type_string;
/* We should start with the argon2_type we are using */
type_string = argon2_type2string(type, 0);
if (!type_string) {
return ARGON2_INCORRECT_TYPE;
}
CC("$");
CC(type_string);
/* Reading the version number if the default is suppressed */
ctx->version = ARGON2_VERSION_10;
CC_opt("$v=", DECIMAL_U32(ctx->version));
CC("$m=");
DECIMAL_U32(ctx->m_cost);
CC(",t=");
DECIMAL_U32(ctx->t_cost);
CC(",p=");
DECIMAL_U32(ctx->lanes);
ctx->threads = ctx->lanes;
CC("$");
BIN(ctx->salt, maxsaltlen, ctx->saltlen);
CC("$");
BIN(ctx->out, maxoutlen, ctx->outlen);
/* The rest of the fields get the default values */
ctx->secret = NULL;
ctx->secretlen = 0;
ctx->ad = NULL;
ctx->adlen = 0;
ctx->allocate_cbk = NULL;
ctx->free_cbk = NULL;
ctx->flags = ARGON2_DEFAULT_FLAGS;
/* On return, must have valid context */
validation_result = validate_inputs(ctx);
if (validation_result != ARGON2_OK) {
return validation_result;
}
/* Can't have any additional characters */
if (*str == 0) {
return ARGON2_OK;
} else {
return ARGON2_DECODING_FAIL;
}
#undef CC
#undef CC_opt
#undef DECIMAL
#undef BIN
}
int encode_string(char *dst, size_t dst_len, argon2_context *ctx,
argon2_type type) {
#define SS(str) \
do { \
size_t pp_len = strlen(str); \
if (pp_len >= dst_len) { \
return ARGON2_ENCODING_FAIL; \
} \
memcpy(dst, str, pp_len + 1); \
dst += pp_len; \
dst_len -= pp_len; \
} while ((void)0, 0)
#define SX(x) \
do { \
char tmp[30]; \
sprintf(tmp, "%lu", (unsigned long)(x)); \
SS(tmp); \
} while ((void)0, 0)
#define SB(buf, len) \
do { \
size_t sb_len = to_base64(dst, dst_len, buf, len); \
if (sb_len == (size_t)-1) { \
return ARGON2_ENCODING_FAIL; \
} \
dst += sb_len; \
dst_len -= sb_len; \
} while ((void)0, 0)
const char* type_string = argon2_type2string(type, 0);
int validation_result = validate_inputs(ctx);
if (!type_string) {
return ARGON2_ENCODING_FAIL;
}
if (validation_result != ARGON2_OK) {
return validation_result;
}
SS("$");
SS(type_string);
SS("$v=");
SX(ctx->version);
SS("$m=");
SX(ctx->m_cost);
SS(",t=");
SX(ctx->t_cost);
SS(",p=");
SX(ctx->lanes);
SS("$");
SB(ctx->salt, ctx->saltlen);
SS("$");
SB(ctx->out, ctx->outlen);
return ARGON2_OK;
#undef SS
#undef SX
#undef SB
}
size_t b64len(uint32_t len) {
size_t olen = ((size_t)len / 3) << 2;
switch (len % 3) {
case 2:
olen++;
/* fall through */
case 1:
olen += 2;
break;
}
return olen;
}
size_t numlen(uint32_t num) {
size_t len = 1;
while (num >= 10) {
++len;
num = num / 10;
}
return len;
}

View File

@@ -0,0 +1,57 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#ifndef ENCODING_H
#define ENCODING_H
#include "argon2.h"
#define ARGON2_MAX_DECODED_LANES UINT32_C(255)
#define ARGON2_MIN_DECODED_SALT_LEN UINT32_C(8)
#define ARGON2_MIN_DECODED_OUT_LEN UINT32_C(12)
/*
* encode an Argon2 hash string into the provided buffer. 'dst_len'
* contains the size, in characters, of the 'dst' buffer; if 'dst_len'
* is less than the number of required characters (including the
* terminating 0), then this function returns ARGON2_ENCODING_ERROR.
*
* on success, ARGON2_OK is returned.
*/
int encode_string(char *dst, size_t dst_len, argon2_context *ctx,
argon2_type type);
/*
* Decodes an Argon2 hash string into the provided structure 'ctx'.
* The only fields that must be set prior to this call are ctx.saltlen and
* ctx.outlen (which must be the maximal salt and out length values that are
* allowed), ctx.salt and ctx.out (which must be buffers of the specified
* length), and ctx.pwd and ctx.pwdlen which must hold a valid password.
*
* Invalid input string causes an error. On success, the ctx is valid and all
* fields have been initialized.
*
* Returned value is ARGON2_OK on success, other ARGON2_ codes on error.
*/
int decode_string(argon2_context *ctx, const char *str, argon2_type type);
/* Returns the length of the encoded byte stream with length len */
size_t b64len(uint32_t len);
/* Returns the length of the encoded number num */
size_t numlen(uint32_t num);
#endif

View File

@@ -0,0 +1,283 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "argon2.h"
#include "core.h"
#include "blake2/blake2.h"
#include "blake2/blamka-round-opt.h"
/*
* Function fills a new memory block and optionally XORs the old block over the new one.
* Memory must be initialized.
* @param state Pointer to the just produced block. Content will be updated(!)
* @param ref_block Pointer to the reference block
* @param next_block Pointer to the block to be XORed over. May coincide with @ref_block
* @param with_xor Whether to XOR into the new block (1) or just overwrite (0)
* @pre all block pointers must be valid
*/
#if defined(__AVX512F__)
static void fill_block(__m512i *state, const block *ref_block,
block *next_block, int with_xor) {
__m512i block_XY[ARGON2_512BIT_WORDS_IN_BLOCK];
unsigned int i;
if (with_xor) {
for (i = 0; i < ARGON2_512BIT_WORDS_IN_BLOCK; i++) {
state[i] = _mm512_xor_si512(
state[i], _mm512_loadu_si512((const __m512i *)ref_block->v + i));
block_XY[i] = _mm512_xor_si512(
state[i], _mm512_loadu_si512((const __m512i *)next_block->v + i));
}
} else {
for (i = 0; i < ARGON2_512BIT_WORDS_IN_BLOCK; i++) {
block_XY[i] = state[i] = _mm512_xor_si512(
state[i], _mm512_loadu_si512((const __m512i *)ref_block->v + i));
}
}
for (i = 0; i < 2; ++i) {
BLAKE2_ROUND_1(
state[8 * i + 0], state[8 * i + 1], state[8 * i + 2], state[8 * i + 3],
state[8 * i + 4], state[8 * i + 5], state[8 * i + 6], state[8 * i + 7]);
}
for (i = 0; i < 2; ++i) {
BLAKE2_ROUND_2(
state[2 * 0 + i], state[2 * 1 + i], state[2 * 2 + i], state[2 * 3 + i],
state[2 * 4 + i], state[2 * 5 + i], state[2 * 6 + i], state[2 * 7 + i]);
}
for (i = 0; i < ARGON2_512BIT_WORDS_IN_BLOCK; i++) {
state[i] = _mm512_xor_si512(state[i], block_XY[i]);
_mm512_storeu_si512((__m512i *)next_block->v + i, state[i]);
}
}
#elif defined(__AVX2__)
static void fill_block(__m256i *state, const block *ref_block,
block *next_block, int with_xor) {
__m256i block_XY[ARGON2_HWORDS_IN_BLOCK];
unsigned int i;
if (with_xor) {
for (i = 0; i < ARGON2_HWORDS_IN_BLOCK; i++) {
state[i] = _mm256_xor_si256(
state[i], _mm256_loadu_si256((const __m256i *)ref_block->v + i));
block_XY[i] = _mm256_xor_si256(
state[i], _mm256_loadu_si256((const __m256i *)next_block->v + i));
}
} else {
for (i = 0; i < ARGON2_HWORDS_IN_BLOCK; i++) {
block_XY[i] = state[i] = _mm256_xor_si256(
state[i], _mm256_loadu_si256((const __m256i *)ref_block->v + i));
}
}
for (i = 0; i < 4; ++i) {
BLAKE2_ROUND_1(state[8 * i + 0], state[8 * i + 4], state[8 * i + 1], state[8 * i + 5],
state[8 * i + 2], state[8 * i + 6], state[8 * i + 3], state[8 * i + 7]);
}
for (i = 0; i < 4; ++i) {
BLAKE2_ROUND_2(state[ 0 + i], state[ 4 + i], state[ 8 + i], state[12 + i],
state[16 + i], state[20 + i], state[24 + i], state[28 + i]);
}
for (i = 0; i < ARGON2_HWORDS_IN_BLOCK; i++) {
state[i] = _mm256_xor_si256(state[i], block_XY[i]);
_mm256_storeu_si256((__m256i *)next_block->v + i, state[i]);
}
}
#else
static void fill_block(__m128i *state, const block *ref_block,
block *next_block, int with_xor) {
__m128i block_XY[ARGON2_OWORDS_IN_BLOCK];
unsigned int i;
if (with_xor) {
for (i = 0; i < ARGON2_OWORDS_IN_BLOCK; i++) {
state[i] = _mm_xor_si128(
state[i], _mm_loadu_si128((const __m128i *)ref_block->v + i));
block_XY[i] = _mm_xor_si128(
state[i], _mm_loadu_si128((const __m128i *)next_block->v + i));
}
} else {
for (i = 0; i < ARGON2_OWORDS_IN_BLOCK; i++) {
block_XY[i] = state[i] = _mm_xor_si128(
state[i], _mm_loadu_si128((const __m128i *)ref_block->v + i));
}
}
for (i = 0; i < 8; ++i) {
BLAKE2_ROUND(state[8 * i + 0], state[8 * i + 1], state[8 * i + 2],
state[8 * i + 3], state[8 * i + 4], state[8 * i + 5],
state[8 * i + 6], state[8 * i + 7]);
}
for (i = 0; i < 8; ++i) {
BLAKE2_ROUND(state[8 * 0 + i], state[8 * 1 + i], state[8 * 2 + i],
state[8 * 3 + i], state[8 * 4 + i], state[8 * 5 + i],
state[8 * 6 + i], state[8 * 7 + i]);
}
for (i = 0; i < ARGON2_OWORDS_IN_BLOCK; i++) {
state[i] = _mm_xor_si128(state[i], block_XY[i]);
_mm_storeu_si128((__m128i *)next_block->v + i, state[i]);
}
}
#endif
static void next_addresses(block *address_block, block *input_block) {
/*Temporary zero-initialized blocks*/
#if defined(__AVX512F__)
__m512i zero_block[ARGON2_512BIT_WORDS_IN_BLOCK];
__m512i zero2_block[ARGON2_512BIT_WORDS_IN_BLOCK];
#elif defined(__AVX2__)
__m256i zero_block[ARGON2_HWORDS_IN_BLOCK];
__m256i zero2_block[ARGON2_HWORDS_IN_BLOCK];
#else
__m128i zero_block[ARGON2_OWORDS_IN_BLOCK];
__m128i zero2_block[ARGON2_OWORDS_IN_BLOCK];
#endif
memset(zero_block, 0, sizeof(zero_block));
memset(zero2_block, 0, sizeof(zero2_block));
/*Increasing index counter*/
input_block->v[6]++;
/*First iteration of G*/
fill_block(zero_block, input_block, address_block, 0);
/*Second iteration of G*/
fill_block(zero2_block, address_block, address_block, 0);
}
void fill_segment(const argon2_instance_t *instance,
argon2_position_t position) {
block *ref_block = NULL, *curr_block = NULL;
block address_block, input_block;
uint64_t pseudo_rand, ref_index, ref_lane;
uint32_t prev_offset, curr_offset;
uint32_t starting_index, i;
#if defined(__AVX512F__)
__m512i state[ARGON2_512BIT_WORDS_IN_BLOCK];
#elif defined(__AVX2__)
__m256i state[ARGON2_HWORDS_IN_BLOCK];
#else
__m128i state[ARGON2_OWORDS_IN_BLOCK];
#endif
int data_independent_addressing;
if (instance == NULL) {
return;
}
data_independent_addressing =
(instance->type == Argon2_i) ||
(instance->type == Argon2_id && (position.pass == 0) &&
(position.slice < ARGON2_SYNC_POINTS / 2));
if (data_independent_addressing) {
init_block_value(&input_block, 0);
input_block.v[0] = position.pass;
input_block.v[1] = position.lane;
input_block.v[2] = position.slice;
input_block.v[3] = instance->memory_blocks;
input_block.v[4] = instance->passes;
input_block.v[5] = instance->type;
}
starting_index = 0;
if ((0 == position.pass) && (0 == position.slice)) {
starting_index = 2; /* we have already generated the first two blocks */
/* Don't forget to generate the first block of addresses: */
if (data_independent_addressing) {
next_addresses(&address_block, &input_block);
}
}
/* Offset of the current block */
curr_offset = position.lane * instance->lane_length +
position.slice * instance->segment_length + starting_index;
if (0 == curr_offset % instance->lane_length) {
/* Last block in this lane */
prev_offset = curr_offset + instance->lane_length - 1;
} else {
/* Previous block */
prev_offset = curr_offset - 1;
}
memcpy(state, ((instance->memory + prev_offset)->v), ARGON2_BLOCK_SIZE);
for (i = starting_index; i < instance->segment_length;
++i, ++curr_offset, ++prev_offset) {
/*1.1 Rotating prev_offset if needed */
if (curr_offset % instance->lane_length == 1) {
prev_offset = curr_offset - 1;
}
/* 1.2 Computing the index of the reference block */
/* 1.2.1 Taking pseudo-random value from the previous block */
if (data_independent_addressing) {
if (i % ARGON2_ADDRESSES_IN_BLOCK == 0) {
next_addresses(&address_block, &input_block);
}
pseudo_rand = address_block.v[i % ARGON2_ADDRESSES_IN_BLOCK];
} else {
pseudo_rand = instance->memory[prev_offset].v[0];
}
/* 1.2.2 Computing the lane of the reference block */
ref_lane = ((pseudo_rand >> 32)) % instance->lanes;
if ((position.pass == 0) && (position.slice == 0)) {
/* Can not reference other lanes yet */
ref_lane = position.lane;
}
/* 1.2.3 Computing the number of possible reference block within the
* lane.
*/
position.index = i;
ref_index = index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF,
ref_lane == position.lane);
/* 2 Creating a new block */
ref_block =
instance->memory + instance->lane_length * ref_lane + ref_index;
curr_block = instance->memory + curr_offset;
if (ARGON2_VERSION_10 == instance->version) {
/* version 1.2.1 and earlier: overwrite, not XOR */
fill_block(state, ref_block, curr_block, 0);
} else {
if(0 == position.pass) {
fill_block(state, ref_block, curr_block, 0);
} else {
fill_block(state, ref_block, curr_block, 1);
}
}
}
}

View File

@@ -0,0 +1,194 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "argon2.h"
#include "core.h"
#include "blake2/blamka-round-ref.h"
#include "blake2/blake2-impl.h"
#include "blake2/blake2.h"
/*
* Function fills a new memory block and optionally XORs the old block over the new one.
* @next_block must be initialized.
* @param prev_block Pointer to the previous block
* @param ref_block Pointer to the reference block
* @param next_block Pointer to the block to be constructed
* @param with_xor Whether to XOR into the new block (1) or just overwrite (0)
* @pre all block pointers must be valid
*/
static void fill_block(const block *prev_block, const block *ref_block,
block *next_block, int with_xor) {
block blockR, block_tmp;
unsigned i;
copy_block(&blockR, ref_block);
xor_block(&blockR, prev_block);
copy_block(&block_tmp, &blockR);
/* Now blockR = ref_block + prev_block and block_tmp = ref_block + prev_block */
if (with_xor) {
/* Saving the next block contents for XOR over: */
xor_block(&block_tmp, next_block);
/* Now blockR = ref_block + prev_block and
block_tmp = ref_block + prev_block + next_block */
}
/* Apply Blake2 on columns of 64-bit words: (0,1,...,15) , then
(16,17,..31)... finally (112,113,...127) */
for (i = 0; i < 8; ++i) {
BLAKE2_ROUND_NOMSG(
blockR.v[16 * i], blockR.v[16 * i + 1], blockR.v[16 * i + 2],
blockR.v[16 * i + 3], blockR.v[16 * i + 4], blockR.v[16 * i + 5],
blockR.v[16 * i + 6], blockR.v[16 * i + 7], blockR.v[16 * i + 8],
blockR.v[16 * i + 9], blockR.v[16 * i + 10], blockR.v[16 * i + 11],
blockR.v[16 * i + 12], blockR.v[16 * i + 13], blockR.v[16 * i + 14],
blockR.v[16 * i + 15]);
}
/* Apply Blake2 on rows of 64-bit words: (0,1,16,17,...112,113), then
(2,3,18,19,...,114,115).. finally (14,15,30,31,...,126,127) */
for (i = 0; i < 8; i++) {
BLAKE2_ROUND_NOMSG(
blockR.v[2 * i], blockR.v[2 * i + 1], blockR.v[2 * i + 16],
blockR.v[2 * i + 17], blockR.v[2 * i + 32], blockR.v[2 * i + 33],
blockR.v[2 * i + 48], blockR.v[2 * i + 49], blockR.v[2 * i + 64],
blockR.v[2 * i + 65], blockR.v[2 * i + 80], blockR.v[2 * i + 81],
blockR.v[2 * i + 96], blockR.v[2 * i + 97], blockR.v[2 * i + 112],
blockR.v[2 * i + 113]);
}
copy_block(next_block, &block_tmp);
xor_block(next_block, &blockR);
}
static void next_addresses(block *address_block, block *input_block,
const block *zero_block) {
input_block->v[6]++;
fill_block(zero_block, input_block, address_block, 0);
fill_block(zero_block, address_block, address_block, 0);
}
void fill_segment(const argon2_instance_t *instance,
argon2_position_t position) {
block *ref_block = NULL, *curr_block = NULL;
block address_block, input_block, zero_block;
uint64_t pseudo_rand, ref_index, ref_lane;
uint32_t prev_offset, curr_offset;
uint32_t starting_index;
uint32_t i;
int data_independent_addressing;
if (instance == NULL) {
return;
}
data_independent_addressing =
(instance->type == Argon2_i) ||
(instance->type == Argon2_id && (position.pass == 0) &&
(position.slice < ARGON2_SYNC_POINTS / 2));
if (data_independent_addressing) {
init_block_value(&zero_block, 0);
init_block_value(&input_block, 0);
input_block.v[0] = position.pass;
input_block.v[1] = position.lane;
input_block.v[2] = position.slice;
input_block.v[3] = instance->memory_blocks;
input_block.v[4] = instance->passes;
input_block.v[5] = instance->type;
}
starting_index = 0;
if ((0 == position.pass) && (0 == position.slice)) {
starting_index = 2; /* we have already generated the first two blocks */
/* Don't forget to generate the first block of addresses: */
if (data_independent_addressing) {
next_addresses(&address_block, &input_block, &zero_block);
}
}
/* Offset of the current block */
curr_offset = position.lane * instance->lane_length +
position.slice * instance->segment_length + starting_index;
if (0 == curr_offset % instance->lane_length) {
/* Last block in this lane */
prev_offset = curr_offset + instance->lane_length - 1;
} else {
/* Previous block */
prev_offset = curr_offset - 1;
}
for (i = starting_index; i < instance->segment_length;
++i, ++curr_offset, ++prev_offset) {
/*1.1 Rotating prev_offset if needed */
if (curr_offset % instance->lane_length == 1) {
prev_offset = curr_offset - 1;
}
/* 1.2 Computing the index of the reference block */
/* 1.2.1 Taking pseudo-random value from the previous block */
if (data_independent_addressing) {
if (i % ARGON2_ADDRESSES_IN_BLOCK == 0) {
next_addresses(&address_block, &input_block, &zero_block);
}
pseudo_rand = address_block.v[i % ARGON2_ADDRESSES_IN_BLOCK];
} else {
pseudo_rand = instance->memory[prev_offset].v[0];
}
/* 1.2.2 Computing the lane of the reference block */
ref_lane = ((pseudo_rand >> 32)) % instance->lanes;
if ((position.pass == 0) && (position.slice == 0)) {
/* Can not reference other lanes yet */
ref_lane = position.lane;
}
/* 1.2.3 Computing the number of possible reference block within the
* lane.
*/
position.index = i;
ref_index = index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF,
ref_lane == position.lane);
/* 2 Creating a new block */
ref_block =
instance->memory + instance->lane_length * ref_lane + ref_index;
curr_block = instance->memory + curr_offset;
if (ARGON2_VERSION_10 == instance->version) {
/* version 1.2.1 and earlier: overwrite, not XOR */
fill_block(instance->memory + prev_offset, ref_block, curr_block, 0);
} else {
if(0 == position.pass) {
fill_block(instance->memory + prev_offset, ref_block,
curr_block, 0);
} else {
fill_block(instance->memory + prev_offset, ref_block,
curr_block, 1);
}
}
}
}

View File

@@ -0,0 +1,57 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#if !defined(ARGON2_NO_THREADS)
#include "thread.h"
#if defined(_WIN32)
#include <windows.h>
#endif
int argon2_thread_create(argon2_thread_handle_t *handle,
argon2_thread_func_t func, void *args) {
if (NULL == handle || func == NULL) {
return -1;
}
#if defined(_WIN32)
*handle = _beginthreadex(NULL, 0, func, args, 0, NULL);
return *handle != 0 ? 0 : -1;
#else
return pthread_create(handle, NULL, func, args);
#endif
}
int argon2_thread_join(argon2_thread_handle_t handle) {
#if defined(_WIN32)
if (WaitForSingleObject((HANDLE)handle, INFINITE) == WAIT_OBJECT_0) {
return CloseHandle((HANDLE)handle) != 0 ? 0 : -1;
}
return -1;
#else
return pthread_join(handle, NULL);
#endif
}
void argon2_thread_exit(void) {
#if defined(_WIN32)
_endthreadex(0);
#else
pthread_exit(NULL);
#endif
}
#endif /* ARGON2_NO_THREADS */

View File

@@ -0,0 +1,67 @@
/*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#ifndef ARGON2_THREAD_H
#define ARGON2_THREAD_H
#if !defined(ARGON2_NO_THREADS)
/*
Here we implement an abstraction layer for the simpĺe requirements
of the Argon2 code. We only require 3 primitives---thread creation,
joining, and termination---so full emulation of the pthreads API
is unwarranted. Currently we wrap pthreads and Win32 threads.
The API defines 2 types: the function pointer type,
argon2_thread_func_t,
and the type of the thread handle---argon2_thread_handle_t.
*/
#if defined(_WIN32)
#include <process.h>
typedef unsigned(__stdcall *argon2_thread_func_t)(void *);
typedef uintptr_t argon2_thread_handle_t;
#else
#include <pthread.h>
typedef void *(*argon2_thread_func_t)(void *);
typedef pthread_t argon2_thread_handle_t;
#endif
/* Creates a thread
* @param handle pointer to a thread handle, which is the output of this
* function. Must not be NULL.
* @param func A function pointer for the thread's entry point. Must not be
* NULL.
* @param args Pointer that is passed as an argument to @func. May be NULL.
* @return 0 if @handle and @func are valid pointers and a thread is successfully
* created.
*/
int argon2_thread_create(argon2_thread_handle_t *handle,
argon2_thread_func_t func, void *args);
/* Waits for a thread to terminate
* @param handle Handle to a thread created with argon2_thread_create.
* @return 0 if @handle is a valid handle, and joining completed successfully.
*/
int argon2_thread_join(argon2_thread_handle_t handle);
/* Terminate the current thread. Must be run inside a thread created by
* argon2_thread_create.
*/
void argon2_thread_exit(void);
#endif /* ARGON2_NO_THREADS */
#endif

View File

@@ -0,0 +1,79 @@
/*
* Argon2 PBKDF2 library wrapper
*
* Copyright (C) 2016-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2016-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <errno.h>
#include "crypto_backend_internal.h"
#if HAVE_ARGON2_H
#include <argon2.h>
#else
#include "argon2/argon2.h"
#endif
#define CONST_CAST(x) (x)(uintptr_t)
int argon2(const char *type, const char *password, size_t password_length,
const char *salt, size_t salt_length,
char *key, size_t key_length,
uint32_t iterations, uint32_t memory, uint32_t parallel)
{
#if !USE_INTERNAL_ARGON2 && !HAVE_ARGON2_H
return -EINVAL;
#else
argon2_type atype;
argon2_context context = {
.flags = ARGON2_DEFAULT_FLAGS,
.version = ARGON2_VERSION_NUMBER,
.t_cost = (uint32_t)iterations,
.m_cost = (uint32_t)memory,
.lanes = (uint32_t)parallel,
.threads = (uint32_t)parallel,
.out = (uint8_t *)key,
.outlen = (uint32_t)key_length,
.pwd = CONST_CAST(uint8_t *)password,
.pwdlen = (uint32_t)password_length,
.salt = CONST_CAST(uint8_t *)salt,
.saltlen = (uint32_t)salt_length,
};
int r;
if (!strcmp(type, "argon2i"))
atype = Argon2_i;
else if(!strcmp(type, "argon2id"))
atype = Argon2_id;
else
return -EINVAL;
switch (argon2_ctx(&context, atype)) {
case ARGON2_OK:
r = 0;
break;
case ARGON2_MEMORY_ALLOCATION_ERROR:
case ARGON2_FREE_MEMORY_CBK_NULL:
case ARGON2_ALLOCATE_MEMORY_CBK_NULL:
r = -ENOMEM;
break;
default:
r = -EINVAL;
}
return r;
#endif
}

View File

@@ -0,0 +1,161 @@
/*
* Cipher performance check
*
* Copyright (C) 2018-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2018-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <errno.h>
#include <time.h>
#include "crypto_backend_internal.h"
#ifndef CLOCK_MONOTONIC_RAW
#define CLOCK_MONOTONIC_RAW CLOCK_MONOTONIC
#endif
/*
* This is not simulating storage, so using disk block causes extreme overhead.
* Let's use some fixed block size where results are more reliable...
*/
#define CIPHER_BLOCK_BYTES 65536
/*
* If the measured value is lower, encrypted buffer is probably too small
* and calculated values are not reliable.
*/
#define CIPHER_TIME_MIN_MS 0.001
/*
* The whole test depends on Linux kernel usermode crypto API for now.
* (The same implementations are used in dm-crypt though.)
*/
static int time_ms(struct timespec *start, struct timespec *end, double *ms)
{
double start_ms, end_ms;
start_ms = start->tv_sec * 1000.0 + start->tv_nsec / (1000.0 * 1000);
end_ms = end->tv_sec * 1000.0 + end->tv_nsec / (1000.0 * 1000);
*ms = end_ms - start_ms;
return 0;
}
static int cipher_perf_one(const char *name, const char *mode, char *buffer, size_t buffer_size,
const char *key, size_t key_size, const char *iv, size_t iv_size, int enc)
{
struct crypt_cipher_kernel cipher;
size_t done = 0, block = CIPHER_BLOCK_BYTES;
int r;
if (buffer_size < block)
block = buffer_size;
r = crypt_cipher_init_kernel(&cipher, name, mode, key, key_size);
if (r < 0)
return r;
while (done < buffer_size) {
if ((done + block) > buffer_size)
block = buffer_size - done;
if (enc)
r = crypt_cipher_encrypt_kernel(&cipher, &buffer[done], &buffer[done],
block, iv, iv_size);
else
r = crypt_cipher_decrypt_kernel(&cipher, &buffer[done], &buffer[done],
block, iv, iv_size);
if (r < 0)
break;
done += block;
}
crypt_cipher_destroy_kernel(&cipher);
return r;
}
static int cipher_measure(const char *name, const char *mode, char *buffer, size_t buffer_size,
const char *key, size_t key_size, const char *iv, size_t iv_size,
int encrypt, double *ms)
{
struct timespec start, end;
int r;
/*
* Using getrusage would be better here but the precision
* is not adequate, so better stick with CLOCK_MONOTONIC
*/
if (clock_gettime(CLOCK_MONOTONIC_RAW, &start) < 0)
return -EINVAL;
r = cipher_perf_one(name, mode, buffer, buffer_size, key, key_size, iv, iv_size, encrypt);
if (r < 0)
return r;
if (clock_gettime(CLOCK_MONOTONIC_RAW, &end) < 0)
return -EINVAL;
r = time_ms(&start, &end, ms);
if (r < 0)
return r;
if (*ms < CIPHER_TIME_MIN_MS)
return -ERANGE;
return 0;
}
static double speed_mbs(unsigned long bytes, double ms)
{
double speed = bytes, s = ms / 1000.;
return speed / (1024 * 1024) / s;
}
int crypt_cipher_perf_kernel(const char *name, const char *mode, char *buffer, size_t buffer_size,
const char *key, size_t key_size, const char *iv, size_t iv_size,
double *encryption_mbs, double *decryption_mbs)
{
double ms_enc, ms_dec, ms;
int r, repeat_enc, repeat_dec;
ms_enc = 0.0;
repeat_enc = 1;
while (ms_enc < 1000.0) {
r = cipher_measure(name, mode, buffer, buffer_size, key, key_size, iv, iv_size, 1, &ms);
if (r < 0)
return r;
ms_enc += ms;
repeat_enc++;
}
ms_dec = 0.0;
repeat_dec = 1;
while (ms_dec < 1000.0) {
r = cipher_measure(name, mode, buffer, buffer_size, key, key_size, iv, iv_size, 0, &ms);
if (r < 0)
return r;
ms_dec += ms;
repeat_dec++;
}
*encryption_mbs = speed_mbs(buffer_size * repeat_enc, ms_enc);
*decryption_mbs = speed_mbs(buffer_size * repeat_dec, ms_dec);
return 0;
}

View File

@@ -0,0 +1,90 @@
/*
* Linux kernel cipher generic utilities
*
* Copyright (C) 2018-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2018-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string.h>
#include <stdbool.h>
#include <errno.h>
#include "crypto_backend.h"
struct cipher_alg {
const char *name;
const char *mode;
int blocksize;
bool wrapped_key;
};
/* FIXME: Getting block size should be dynamic from cipher backend. */
static const struct cipher_alg cipher_algs[] = {
{ "cipher_null", NULL, 16, false },
{ "aes", NULL, 16, false },
{ "serpent", NULL, 16, false },
{ "twofish", NULL, 16, false },
{ "anubis", NULL, 16, false },
{ "blowfish", NULL, 8, false },
{ "camellia", NULL, 16, false },
{ "cast5", NULL, 8, false },
{ "cast6", NULL, 16, false },
{ "des", NULL, 8, false },
{ "des3_ede", NULL, 8, false },
{ "khazad", NULL, 8, false },
{ "seed", NULL, 16, false },
{ "tea", NULL, 8, false },
{ "xtea", NULL, 8, false },
{ "paes", NULL, 16, true }, /* protected AES, s390 wrapped key scheme */
{ "xchacha12,aes", "adiantum", 32, false },
{ "xchacha20,aes", "adiantum", 32, false },
{ "sm4", NULL, 16, false },
{ NULL, NULL, 0, false }
};
static const struct cipher_alg *_get_alg(const char *name, const char *mode)
{
int i = 0;
while (name && cipher_algs[i].name) {
if (!strcasecmp(name, cipher_algs[i].name))
if (!mode || !cipher_algs[i].mode ||
!strncasecmp(mode, cipher_algs[i].mode, strlen(cipher_algs[i].mode)))
return &cipher_algs[i];
i++;
}
return NULL;
}
int crypt_cipher_ivsize(const char *name, const char *mode)
{
const struct cipher_alg *ca = _get_alg(name, mode);
if (!ca)
return -EINVAL;
if (mode && !strcasecmp(mode, "ecb"))
return 0;
return ca->blocksize;
}
int crypt_cipher_wrapped_key(const char *name, const char *mode)
{
const struct cipher_alg *ca = _get_alg(name, mode);
return ca ? (int)ca->wrapped_key : 0;
}

View File

@@ -19,7 +19,7 @@
* order from highest-order term to lowest-order term. UARTs transmit
* characters in order from LSB to MSB. By storing the CRC this way,
* we hand it to the UART in the order low-byte to high-byte; the UART
* sends each low-bit to hight-bit; and the result is transmission bit
* sends each low-bit to high-bit; and the result is transmission bit
* by bit from highest- to lowest-order term without requiring any bit
* shuffling on our part. Reception works similarly.
*
@@ -42,7 +42,6 @@
#include "crypto_backend.h"
static const uint32_t crc32_tab[] = {
0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
@@ -113,4 +112,3 @@ uint32_t crypt_crc32(uint32_t seed, const unsigned char *buf, size_t len)
return crc;
}

View File

@@ -1,8 +1,8 @@
/*
* crypto backend implementation
*
* Copyright (C) 2010-2012, Red Hat, Inc. All rights reserved.
* Copyright (C) 2010-2014, Milan Broz
* Copyright (C) 2010-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2010-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -22,15 +22,17 @@
#define _CRYPTO_BACKEND_H
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
struct crypt_device;
struct crypt_hash;
struct crypt_hmac;
struct crypt_cipher;
struct crypt_storage;
int crypt_backend_init(struct crypt_device *ctx);
int crypt_backend_init(void);
void crypt_backend_destroy(void);
#define CRYPT_BACKEND_KERNEL (1 << 0) /* Crypto uses kernel part, for benchmark */
@@ -42,64 +44,95 @@ int crypt_hash_size(const char *name);
int crypt_hash_init(struct crypt_hash **ctx, const char *name);
int crypt_hash_write(struct crypt_hash *ctx, const char *buffer, size_t length);
int crypt_hash_final(struct crypt_hash *ctx, char *buffer, size_t length);
int crypt_hash_destroy(struct crypt_hash *ctx);
void crypt_hash_destroy(struct crypt_hash *ctx);
/* HMAC */
int crypt_hmac_size(const char *name);
int crypt_hmac_init(struct crypt_hmac **ctx, const char *name,
const void *buffer, size_t length);
const void *key, size_t key_length);
int crypt_hmac_write(struct crypt_hmac *ctx, const char *buffer, size_t length);
int crypt_hmac_final(struct crypt_hmac *ctx, char *buffer, size_t length);
int crypt_hmac_destroy(struct crypt_hmac *ctx);
void crypt_hmac_destroy(struct crypt_hmac *ctx);
/* RNG (if fips paramater set, must provide FIPS compliance) */
/* RNG (if fips parameter set, must provide FIPS compliance) */
enum { CRYPT_RND_NORMAL = 0, CRYPT_RND_KEY = 1, CRYPT_RND_SALT = 2 };
int crypt_backend_rng(char *buffer, size_t length, int quality, int fips);
/* PBKDF*/
int crypt_pbkdf_check(const char *kdf, const char *hash,
const char *password, size_t password_size,
const char *salt, size_t salt_size,
uint64_t *iter_secs);
struct crypt_pbkdf_limits {
uint32_t min_iterations, max_iterations;
uint32_t min_memory, max_memory;
uint32_t min_parallel, max_parallel;
};
int crypt_pbkdf_get_limits(const char *kdf, struct crypt_pbkdf_limits *l);
int crypt_pbkdf(const char *kdf, const char *hash,
const char *password, size_t password_length,
const char *salt, size_t salt_length,
char *key, size_t key_length,
unsigned int iterations);
#if USE_INTERNAL_PBKDF2
/* internal PBKDF2 implementation */
int pkcs5_pbkdf2(const char *hash,
const char *P, size_t Plen,
const char *S, size_t Slen,
unsigned int c,
unsigned int dkLen, char *DK,
unsigned int hash_block_size);
#endif
uint32_t iterations, uint32_t memory, uint32_t parallel);
int crypt_pbkdf_perf(const char *kdf, const char *hash,
const char *password, size_t password_size,
const char *salt, size_t salt_size,
size_t volume_key_size, uint32_t time_ms,
uint32_t max_memory_kb, uint32_t parallel_threads,
uint32_t *iterations_out, uint32_t *memory_out,
int (*progress)(uint32_t time_ms, void *usrptr), void *usrptr);
/* CRC32 */
uint32_t crypt_crc32(uint32_t seed, const unsigned char *buf, size_t len);
/* ciphers */
int crypt_cipher_blocksize(const char *name);
/* Block ciphers */
int crypt_cipher_ivsize(const char *name, const char *mode);
int crypt_cipher_wrapped_key(const char *name, const char *mode);
int crypt_cipher_init(struct crypt_cipher **ctx, const char *name,
const char *mode, const void *buffer, size_t length);
int crypt_cipher_destroy(struct crypt_cipher *ctx);
const char *mode, const void *key, size_t key_length);
void crypt_cipher_destroy(struct crypt_cipher *ctx);
int crypt_cipher_encrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length);
int crypt_cipher_decrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length);
bool crypt_cipher_kernel_only(struct crypt_cipher *ctx);
/* storage encryption wrappers */
int crypt_storage_init(struct crypt_storage **ctx, uint64_t sector_start,
/* Benchmark of kernel cipher performance */
int crypt_cipher_perf_kernel(const char *name, const char *mode, char *buffer, size_t buffer_size,
const char *key, size_t key_size, const char *iv, size_t iv_size,
double *encryption_mbs, double *decryption_mbs);
/* Check availability of a cipher (in kernel only) */
int crypt_cipher_check_kernel(const char *name, const char *mode,
const char *integrity, size_t key_length);
/* Storage encryption wrappers */
int crypt_storage_init(struct crypt_storage **ctx, size_t sector_size,
const char *cipher, const char *cipher_mode,
char *key, size_t key_length);
int crypt_storage_destroy(struct crypt_storage *ctx);
int crypt_storage_decrypt(struct crypt_storage *ctx, uint64_t sector,
size_t count, char *buffer);
int crypt_storage_encrypt(struct crypt_storage *ctx, uint64_t sector,
size_t count, char *buffer);
const void *key, size_t key_length, bool large_iv);
void crypt_storage_destroy(struct crypt_storage *ctx);
int crypt_storage_decrypt(struct crypt_storage *ctx, uint64_t iv_offset,
uint64_t length, char *buffer);
int crypt_storage_encrypt(struct crypt_storage *ctx, uint64_t iv_offset,
uint64_t length, char *buffer);
bool crypt_storage_kernel_only(struct crypt_storage *ctx);
/* Temporary Bitlk helper */
int crypt_bitlk_decrypt_key(const void *key, size_t key_length,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length,
const char *tag, size_t tag_length);
/* Memzero helper (memset on stack can be optimized out) */
static inline void crypt_backend_memzero(void *s, size_t n)
{
#ifdef HAVE_EXPLICIT_BZERO
explicit_bzero(s, n);
#else
volatile uint8_t *p = (volatile uint8_t *)s;
while(n--) *p++ = 0;
#endif
}
#endif /* _CRYPTO_BACKEND_H */

View File

@@ -0,0 +1,63 @@
/*
* crypto backend implementation
*
* Copyright (C) 2010-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2010-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef _CRYPTO_BACKEND_INTERNAL_H
#define _CRYPTO_BACKEND_INTERNAL_H
#include "crypto_backend.h"
#if USE_INTERNAL_PBKDF2
/* internal PBKDF2 implementation */
int pkcs5_pbkdf2(const char *hash,
const char *P, size_t Plen,
const char *S, size_t Slen,
unsigned int c,
unsigned int dkLen, char *DK,
unsigned int hash_block_size);
#endif
/* Argon2 implementation wrapper */
int argon2(const char *type, const char *password, size_t password_length,
const char *salt, size_t salt_length,
char *key, size_t key_length,
uint32_t iterations, uint32_t memory, uint32_t parallel);
/* Block ciphers: fallback to kernel crypto API */
struct crypt_cipher_kernel {
int tfmfd;
int opfd;
};
int crypt_cipher_init_kernel(struct crypt_cipher_kernel *ctx, const char *name,
const char *mode, const void *key, size_t key_length);
int crypt_cipher_encrypt_kernel(struct crypt_cipher_kernel *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length);
int crypt_cipher_decrypt_kernel(struct crypt_cipher_kernel *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length);
void crypt_cipher_destroy_kernel(struct crypt_cipher_kernel *ctx);
int crypt_bitlk_decrypt_key_kernel(const void *key, size_t key_length,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length,
const char *tag, size_t tag_length);
#endif /* _CRYPTO_BACKEND_INTERNAL_H */

View File

@@ -1,8 +1,8 @@
/*
* Linux kernel userspace API crypto backend implementation (skcipher)
*
* Copyright (C) 2012, Red Hat, Inc. All rights reserved.
* Copyright (C) 2012-2014, Milan Broz
* Copyright (C) 2012-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2012-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -22,11 +22,12 @@
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include "crypto_backend.h"
#include "crypto_backend_internal.h"
#ifdef ENABLE_AF_ALG
@@ -39,125 +40,80 @@
#define SOL_ALG 279
#endif
struct crypt_cipher {
int tfmfd;
int opfd;
};
#ifndef ALG_SET_AEAD_AUTHSIZE
#define ALG_SET_AEAD_AUTHSIZE 5
#endif
struct cipher_alg {
const char *name;
int blocksize;
};
/* FIXME: Getting block size should be dynamic from cipher backend. */
static struct cipher_alg cipher_algs[] = {
{ "cipher_null", 16 },
{ "aes", 16 },
{ "serpent", 16 },
{ "twofish", 16 },
{ "anubis", 16 },
{ "blowfish", 8 },
{ "camellia", 16 },
{ "cast5", 8 },
{ "cast6", 16 },
{ "des", 8 },
{ "des3_ede", 8 },
{ "khazad", 8 },
{ "seed", 16 },
{ "tea", 8 },
{ "xtea", 8 },
{ NULL, 0 }
};
static struct cipher_alg *_get_alg(const char *name)
/*
* ciphers
*
* ENOENT - algorithm not available
* ENOTSUP - AF_ALG family not available
* (but cannot check specifically for skcipher API)
*/
static int _crypt_cipher_init(struct crypt_cipher_kernel *ctx,
const void *key, size_t key_length,
size_t tag_length, struct sockaddr_alg *sa)
{
int i = 0;
if (!ctx)
return -EINVAL;
while (name && cipher_algs[i].name) {
if (!strcasecmp(name, cipher_algs[i].name))
return &cipher_algs[i];
i++;
}
return NULL;
}
int crypt_cipher_blocksize(const char *name)
{
struct cipher_alg *ca = _get_alg(name);
return ca ? ca->blocksize : -EINVAL;
}
/* Shared with hash kernel backend */
int crypt_kernel_socket_init(struct sockaddr_alg *sa, int *tfmfd, int *opfd);
int crypt_kernel_socket_init(struct sockaddr_alg *sa, int *tfmfd, int *opfd)
{
*tfmfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
if (*tfmfd == -1)
ctx->opfd = -1;
ctx->tfmfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
if (ctx->tfmfd < 0) {
crypt_cipher_destroy_kernel(ctx);
return -ENOTSUP;
}
if (bind(*tfmfd, (struct sockaddr *)sa, sizeof(*sa)) == -1) {
close(*tfmfd);
*tfmfd = -1;
if (bind(ctx->tfmfd, (struct sockaddr *)sa, sizeof(*sa)) < 0) {
crypt_cipher_destroy_kernel(ctx);
return -ENOENT;
}
*opfd = accept(*tfmfd, NULL, 0);
if (*opfd == -1) {
close(*tfmfd);
*tfmfd = -1;
if (setsockopt(ctx->tfmfd, SOL_ALG, ALG_SET_KEY, key, key_length) < 0) {
crypt_cipher_destroy_kernel(ctx);
return -EINVAL;
}
if (tag_length && setsockopt(ctx->tfmfd, SOL_ALG, ALG_SET_AEAD_AUTHSIZE, NULL, tag_length) < 0) {
crypt_cipher_destroy_kernel(ctx);
return -EINVAL;
}
ctx->opfd = accept(ctx->tfmfd, NULL, 0);
if (ctx->opfd < 0) {
crypt_cipher_destroy_kernel(ctx);
return -EINVAL;
}
return 0;
}
/*
*ciphers
*
* ENOENT - algorithm not available
* ENOTSUP - AF_ALG family not available
* (but cannot check specificaly for skcipher API)
*/
int crypt_cipher_init(struct crypt_cipher **ctx, const char *name,
const char *mode, const void *buffer, size_t length)
int crypt_cipher_init_kernel(struct crypt_cipher_kernel *ctx, const char *name,
const char *mode, const void *key, size_t key_length)
{
struct crypt_cipher *h;
struct sockaddr_alg sa = {
.salg_family = AF_ALG,
.salg_type = "skcipher",
};
int r;
h = malloc(sizeof(*h));
if (!h)
return -ENOMEM;
if (!strcmp(name, "cipher_null"))
key_length = 0;
snprintf((char *)sa.salg_name, sizeof(sa.salg_name),
"%s(%s)", mode, name);
r = crypt_kernel_socket_init(&sa, &h->tfmfd, &h->opfd);
if (r < 0) {
free(h);
return r;
}
if (length && strcmp(name, "cipher_null") &&
setsockopt(h->tfmfd, SOL_ALG, ALG_SET_KEY, buffer, length) == -1) {
crypt_cipher_destroy(h);
r = snprintf((char *)sa.salg_name, sizeof(sa.salg_name), "%s(%s)", mode, name);
if (r < 0 || (size_t)r >= sizeof(sa.salg_name))
return -EINVAL;
}
*ctx = h;
return 0;
return _crypt_cipher_init(ctx, key, key_length, 0, &sa);
}
/* The in/out should be aligned to page boundary */
static int crypt_cipher_crypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length,
uint32_t direction)
static int _crypt_cipher_crypt(struct crypt_cipher_kernel *ctx,
const char *in, size_t in_length,
char *out, size_t out_length,
const char *iv, size_t iv_length,
uint32_t direction)
{
int r = 0;
ssize_t len;
@@ -166,7 +122,7 @@ static int crypt_cipher_crypt(struct crypt_cipher *ctx,
uint32_t *type;
struct iovec iov = {
.iov_base = (void*)(uintptr_t)in,
.iov_len = length,
.iov_len = in_length,
};
int iv_msg_size = iv ? CMSG_SPACE(sizeof(*alg_iv) + iv_length) : 0;
char buffer[CMSG_SPACE(sizeof(*type)) + iv_msg_size];
@@ -177,7 +133,7 @@ static int crypt_cipher_crypt(struct crypt_cipher *ctx,
.msg_iovlen = 1,
};
if (!in || !out || !length)
if (!in || !out || !in_length)
return -EINVAL;
if ((!iv && iv_length) || (iv && !iv_length))
@@ -199,6 +155,9 @@ static int crypt_cipher_crypt(struct crypt_cipher *ctx,
/* Set IV */
if (iv) {
header = CMSG_NXTHDR(&msg, header);
if (!header)
return -EINVAL;
header->cmsg_level = SOL_ALG;
header->cmsg_type = ALG_SET_IV;
header->cmsg_len = iv_msg_size;
@@ -208,74 +167,186 @@ static int crypt_cipher_crypt(struct crypt_cipher *ctx,
}
len = sendmsg(ctx->opfd, &msg, 0);
if (len != (ssize_t)length) {
if (len != (ssize_t)(in_length)) {
r = -EIO;
goto bad;
}
len = read(ctx->opfd, out, length);
if (len != (ssize_t)length)
len = read(ctx->opfd, out, out_length);
if (len != (ssize_t)out_length)
r = -EIO;
bad:
memset(buffer, 0, sizeof(buffer));
crypt_backend_memzero(buffer, sizeof(buffer));
return r;
}
int crypt_cipher_encrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
int crypt_cipher_encrypt_kernel(struct crypt_cipher_kernel *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
{
return crypt_cipher_crypt(ctx, in, out, length,
iv, iv_length, ALG_OP_ENCRYPT);
return _crypt_cipher_crypt(ctx, in, length, out, length,
iv, iv_length, ALG_OP_ENCRYPT);
}
int crypt_cipher_decrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
int crypt_cipher_decrypt_kernel(struct crypt_cipher_kernel *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
{
return crypt_cipher_crypt(ctx, in, out, length,
iv, iv_length, ALG_OP_DECRYPT);
return _crypt_cipher_crypt(ctx, in, length, out, length,
iv, iv_length, ALG_OP_DECRYPT);
}
int crypt_cipher_destroy(struct crypt_cipher *ctx)
void crypt_cipher_destroy_kernel(struct crypt_cipher_kernel *ctx)
{
if (ctx->tfmfd != -1)
if (ctx->tfmfd >= 0)
close(ctx->tfmfd);
if (ctx->opfd != -1)
if (ctx->opfd >= 0)
close(ctx->opfd);
memset(ctx, 0, sizeof(*ctx));
free(ctx);
return 0;
ctx->tfmfd = -1;
ctx->opfd = -1;
}
int crypt_cipher_check_kernel(const char *name, const char *mode,
const char *integrity, size_t key_length)
{
struct crypt_cipher_kernel c;
char mode_name[64], tmp_salg_name[180], *real_mode = NULL, *cipher_iv = NULL, *key;
const char *salg_type;
bool aead;
int r;
struct sockaddr_alg sa = {
.salg_family = AF_ALG,
};
aead = integrity && strcmp(integrity, "none");
/* Remove IV if present */
if (mode) {
strncpy(mode_name, mode, sizeof(mode_name));
mode_name[sizeof(mode_name) - 1] = 0;
cipher_iv = strchr(mode_name, '-');
if (cipher_iv) {
*cipher_iv = '\0';
real_mode = mode_name;
}
}
salg_type = aead ? "aead" : "skcipher";
r = snprintf((char *)sa.salg_type, sizeof(sa.salg_type), "%s", salg_type);
if (r < 0 || (size_t)r >= sizeof(sa.salg_name))
return -EINVAL;
memset(tmp_salg_name, 0, sizeof(tmp_salg_name));
/* FIXME: this is duplicating a part of devmapper backend */
if (aead && !strcmp(integrity, "poly1305"))
r = snprintf(tmp_salg_name, sizeof(tmp_salg_name), "rfc7539(%s,%s)", name, integrity);
else if (!real_mode)
r = snprintf(tmp_salg_name, sizeof(tmp_salg_name), "%s", name);
else if (aead && !strcmp(real_mode, "ccm"))
r = snprintf(tmp_salg_name, sizeof(tmp_salg_name), "rfc4309(%s(%s))", real_mode, name);
else
r = snprintf(tmp_salg_name, sizeof(tmp_salg_name), "%s(%s)", real_mode, name);
if (r < 0 || (size_t)r >= sizeof(tmp_salg_name))
return -EINVAL;
memcpy(sa.salg_name, tmp_salg_name, sizeof(sa.salg_name));
key = malloc(key_length);
if (!key)
return -ENOMEM;
/* We cannot use RNG yet, any key works here, tweak the first part if it is split key (XTS). */
memset(key, 0xab, key_length);
*key = 0xef;
r = _crypt_cipher_init(&c, key, key_length, 0, &sa);
crypt_cipher_destroy_kernel(&c);
free(key);
return r;
}
int crypt_bitlk_decrypt_key_kernel(const void *key, size_t key_length,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length,
const char *tag, size_t tag_length)
{
struct crypt_cipher_kernel c;
struct sockaddr_alg sa = {
.salg_family = AF_ALG,
.salg_type = "aead",
.salg_name = "ccm(aes)",
};
int r;
char buffer[128], ccm_iv[16];
if (length + tag_length > sizeof(buffer))
return -EINVAL;
if (iv_length > sizeof(ccm_iv) - 2)
return -EINVAL;
r = _crypt_cipher_init(&c, key, key_length, tag_length, &sa);
if (r < 0)
return r;
memcpy(buffer, in, length);
memcpy(buffer + length, tag, tag_length);
/* CCM IV - RFC3610 */
memset(ccm_iv, 0, sizeof(ccm_iv));
ccm_iv[0] = 15 - iv_length - 1;
memcpy(ccm_iv + 1, iv, iv_length);
memset(ccm_iv + 1 + iv_length, 0, ccm_iv[0] + 1);
iv_length = sizeof(ccm_iv);
r = _crypt_cipher_crypt(&c, buffer, length + tag_length, out, length,
ccm_iv, iv_length, ALG_OP_DECRYPT);
crypt_cipher_destroy_kernel(&c);
crypt_backend_memzero(buffer, sizeof(buffer));
return r;
}
#else /* ENABLE_AF_ALG */
int crypt_cipher_blocksize(const char *name)
{
return -EINVAL;
}
int crypt_cipher_init(struct crypt_cipher **ctx, const char *name,
const char *mode, const void *buffer, size_t length)
int crypt_cipher_init_kernel(struct crypt_cipher_kernel *ctx, const char *name,
const char *mode, const void *key, size_t key_length)
{
return -ENOTSUP;
}
int crypt_cipher_destroy(struct crypt_cipher *ctx)
void crypt_cipher_destroy_kernel(struct crypt_cipher_kernel *ctx)
{
return 0;
return;
}
int crypt_cipher_encrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
int crypt_cipher_encrypt_kernel(struct crypt_cipher_kernel *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
{
return -EINVAL;
}
int crypt_cipher_decrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
int crypt_cipher_decrypt_kernel(struct crypt_cipher_kernel *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
{
return -EINVAL;
}
int crypt_cipher_check_kernel(const char *name, const char *mode,
const char *integrity, size_t key_length)
{
/* Cannot check, expect success. */
return 0;
}
int crypt_bitlk_decrypt_key_kernel(const void *key, size_t key_length,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length,
const char *tag, size_t tag_length)
{
return -ENOTSUP;
}
#endif

View File

@@ -1,8 +1,8 @@
/*
* GCRYPT crypto backend implementation
*
* Copyright (C) 2010-2012, Red Hat, Inc. All rights reserved.
* Copyright (C) 2010-2014, Milan Broz
* Copyright (C) 2010-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2010-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -24,7 +24,7 @@
#include <errno.h>
#include <assert.h>
#include <gcrypt.h>
#include "crypto_backend.h"
#include "crypto_backend_internal.h"
static int crypto_backend_initialised = 0;
static int crypto_backend_secmem = 1;
@@ -43,9 +43,22 @@ struct crypt_hmac {
int hash_len;
};
struct crypt_cipher {
bool use_kernel;
union {
struct crypt_cipher_kernel kernel;
gcry_cipher_hd_t hd;
} u;
};
struct hash_alg {
const char *name;
const char *gcrypt_name;
};
/*
* Test for wrong Whirlpool variant,
* Ref: http://lists.gnupg.org/pipermail/gcrypt-devel/2014-January/002889.html
* Ref: https://lists.gnupg.org/pipermail/gcrypt-devel/2014-January/002889.html
*/
static void crypt_hash_test_whirlpool_bug(void)
{
@@ -81,8 +94,10 @@ static void crypt_hash_test_whirlpool_bug(void)
crypto_backend_whirlpool_bug = 1;
}
int crypt_backend_init(struct crypt_device *ctx)
int crypt_backend_init(void)
{
int r;
if (crypto_backend_initialised)
return 0;
@@ -112,15 +127,24 @@ int crypt_backend_init(struct crypt_device *ctx)
crypto_backend_initialised = 1;
crypt_hash_test_whirlpool_bug();
snprintf(version, 64, "gcrypt %s%s%s",
r = snprintf(version, sizeof(version), "gcrypt %s%s%s",
gcry_check_version(NULL),
crypto_backend_secmem ? "" : ", secmem disabled",
crypto_backend_whirlpool_bug > 0 ? ", flawed whirlpool" : ""
);
crypto_backend_whirlpool_bug > 0 ? ", flawed whirlpool" : "");
if (r < 0 || (size_t)r >= sizeof(version))
return -EINVAL;
return 0;
}
void crypt_backend_destroy(void)
{
if (crypto_backend_initialised)
gcry_control(GCRYCTL_TERM_SECMEM);
crypto_backend_initialised = 0;
}
const char *crypt_backend_version(void)
{
return crypto_backend_initialised ? version : "";
@@ -134,10 +158,24 @@ uint32_t crypt_backend_flags(void)
static const char *crypt_hash_compat_name(const char *name, unsigned int *flags)
{
const char *hash_name = name;
int i;
static struct hash_alg hash_algs[] = {
{ "blake2b-160", "blake2b_160" },
{ "blake2b-256", "blake2b_256" },
{ "blake2b-384", "blake2b_384" },
{ "blake2b-512", "blake2b_512" },
{ "blake2s-128", "blake2s_128" },
{ "blake2s-160", "blake2s_160" },
{ "blake2s-224", "blake2s_224" },
{ "blake2s-256", "blake2s_256" },
{ NULL, NULL, }};
if (!name)
return NULL;
/* "whirlpool_gcryptbug" is out shortcut to flawed whirlpool
* in libgcrypt < 1.6.0 */
if (name && !strcasecmp(name, "whirlpool_gcryptbug")) {
if (!strcasecmp(name, "whirlpool_gcryptbug")) {
#if GCRYPT_VERSION_NUMBER >= 0x010601
if (flags)
*flags |= GCRY_MD_FLAG_BUGEMU1;
@@ -145,6 +183,15 @@ static const char *crypt_hash_compat_name(const char *name, unsigned int *flags)
hash_name = "whirlpool";
}
i = 0;
while (hash_algs[i].name) {
if (!strcasecmp(name, hash_algs[i].name)) {
hash_name = hash_algs[i].gcrypt_name;
break;
}
i++;
}
return hash_name;
}
@@ -217,12 +264,11 @@ int crypt_hash_final(struct crypt_hash *ctx, char *buffer, size_t length)
return 0;
}
int crypt_hash_destroy(struct crypt_hash *ctx)
void crypt_hash_destroy(struct crypt_hash *ctx)
{
gcry_md_close(ctx->hd);
memset(ctx, 0, sizeof(*ctx));
free(ctx);
return 0;
}
/* HMAC */
@@ -232,7 +278,7 @@ int crypt_hmac_size(const char *name)
}
int crypt_hmac_init(struct crypt_hmac **ctx, const char *name,
const void *buffer, size_t length)
const void *key, size_t key_length)
{
struct crypt_hmac *h;
unsigned int flags = GCRY_MD_FLAG_HMAC;
@@ -254,7 +300,7 @@ int crypt_hmac_init(struct crypt_hmac **ctx, const char *name,
return -EINVAL;
}
if (gcry_md_setkey(h->hd, buffer, length)) {
if (gcry_md_setkey(h->hd, key, key_length)) {
gcry_md_close(h->hd);
free(h);
return -EINVAL;
@@ -293,12 +339,11 @@ int crypt_hmac_final(struct crypt_hmac *ctx, char *buffer, size_t length)
return 0;
}
int crypt_hmac_destroy(struct crypt_hmac *ctx)
void crypt_hmac_destroy(struct crypt_hmac *ctx)
{
gcry_md_close(ctx->hd);
memset(ctx, 0, sizeof(*ctx));
free(ctx);
return 0;
}
/* RNG */
@@ -317,38 +362,191 @@ int crypt_backend_rng(char *buffer, size_t length, int quality, int fips)
return 0;
}
/* PBKDF */
int crypt_pbkdf(const char *kdf, const char *hash,
const char *password, size_t password_length,
const char *salt, size_t salt_length,
char *key, size_t key_length,
unsigned int iterations)
static int pbkdf2(const char *hash,
const char *password, size_t password_length,
const char *salt, size_t salt_length,
char *key, size_t key_length,
uint32_t iterations)
{
const char *hash_name = crypt_hash_compat_name(hash, NULL);
#if USE_INTERNAL_PBKDF2
if (!kdf || strncmp(kdf, "pbkdf2", 6))
return -EINVAL;
return pkcs5_pbkdf2(hash_name, password, password_length, salt, salt_length,
iterations, key_length, key, 0);
#else /* USE_INTERNAL_PBKDF2 */
int hash_id = gcry_md_map_name(hash_name);
int kdf_id;
if (!hash_id)
return -EINVAL;
if (kdf && !strncmp(kdf, "pbkdf2", 6))
kdf_id = GCRY_KDF_PBKDF2;
else
return -EINVAL;
if (gcry_kdf_derive(password, password_length, kdf_id, hash_id,
if (gcry_kdf_derive(password, password_length, GCRY_KDF_PBKDF2, hash_id,
salt, salt_length, iterations, key_length, key))
return -EINVAL;
return 0;
#endif /* USE_INTERNAL_PBKDF2 */
}
/* PBKDF */
int crypt_pbkdf(const char *kdf, const char *hash,
const char *password, size_t password_length,
const char *salt, size_t salt_length,
char *key, size_t key_length,
uint32_t iterations, uint32_t memory, uint32_t parallel)
{
if (!kdf)
return -EINVAL;
if (!strcmp(kdf, "pbkdf2"))
return pbkdf2(hash, password, password_length, salt, salt_length,
key, key_length, iterations);
else if (!strncmp(kdf, "argon2", 6))
return argon2(kdf, password, password_length, salt, salt_length,
key, key_length, iterations, memory, parallel);
return -EINVAL;
}
/* Block ciphers */
static int _cipher_init(gcry_cipher_hd_t *hd, const char *name,
const char *mode, const void *buffer, size_t length)
{
int cipher_id, mode_id;
cipher_id = gcry_cipher_map_name(name);
if (cipher_id == GCRY_CIPHER_MODE_NONE)
return -ENOENT;
if (!strcmp(mode, "ecb"))
mode_id = GCRY_CIPHER_MODE_ECB;
else if (!strcmp(mode, "cbc"))
mode_id = GCRY_CIPHER_MODE_CBC;
#if HAVE_DECL_GCRY_CIPHER_MODE_XTS
else if (!strcmp(mode, "xts"))
mode_id = GCRY_CIPHER_MODE_XTS;
#endif
else
return -ENOENT;
if (gcry_cipher_open(hd, cipher_id, mode_id, 0))
return -EINVAL;
if (gcry_cipher_setkey(*hd, buffer, length)) {
gcry_cipher_close(*hd);
return -EINVAL;
}
return 0;
}
int crypt_cipher_init(struct crypt_cipher **ctx, const char *name,
const char *mode, const void *key, size_t key_length)
{
struct crypt_cipher *h;
int r;
h = malloc(sizeof(*h));
if (!h)
return -ENOMEM;
if (!_cipher_init(&h->u.hd, name, mode, key, key_length)) {
h->use_kernel = false;
*ctx = h;
return 0;
}
r = crypt_cipher_init_kernel(&h->u.kernel, name, mode, key, key_length);
if (r < 0) {
free(h);
return r;
}
h->use_kernel = true;
*ctx = h;
return 0;
}
void crypt_cipher_destroy(struct crypt_cipher *ctx)
{
if (ctx->use_kernel)
crypt_cipher_destroy_kernel(&ctx->u.kernel);
else
gcry_cipher_close(ctx->u.hd);
free(ctx);
}
int crypt_cipher_encrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
{
if (ctx->use_kernel)
return crypt_cipher_encrypt_kernel(&ctx->u.kernel, in, out, length, iv, iv_length);
if (iv && gcry_cipher_setiv(ctx->u.hd, iv, iv_length))
return -EINVAL;
if (gcry_cipher_encrypt(ctx->u.hd, out, length, in, length))
return -EINVAL;
return 0;
}
int crypt_cipher_decrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
{
if (ctx->use_kernel)
return crypt_cipher_decrypt_kernel(&ctx->u.kernel, in, out, length, iv, iv_length);
if (iv && gcry_cipher_setiv(ctx->u.hd, iv, iv_length))
return -EINVAL;
if (gcry_cipher_decrypt(ctx->u.hd, out, length, in, length))
return -EINVAL;
return 0;
}
bool crypt_cipher_kernel_only(struct crypt_cipher *ctx)
{
return ctx->use_kernel;
}
int crypt_bitlk_decrypt_key(const void *key, size_t key_length,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length,
const char *tag, size_t tag_length)
{
#ifdef GCRY_CCM_BLOCK_LEN
gcry_cipher_hd_t hd;
uint64_t l[3];
int r = -EINVAL;
if (gcry_cipher_open(&hd, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CCM, 0))
return -EINVAL;
if (gcry_cipher_setkey(hd, key, key_length))
goto out;
if (gcry_cipher_setiv(hd, iv, iv_length))
goto out;
l[0] = length;
l[1] = 0;
l[2] = tag_length;
if (gcry_cipher_ctl(hd, GCRYCTL_SET_CCM_LENGTHS, l, sizeof(l)))
goto out;
if (gcry_cipher_decrypt(hd, out, length, in, length))
goto out;
if (gcry_cipher_checktag(hd, tag, tag_length))
goto out;
r = 0;
out:
gcry_cipher_close(hd);
return r;
#else
return -ENOTSUP;
#endif
}

View File

@@ -1,8 +1,8 @@
/*
* Linux kernel userspace API crypto backend implementation
*
* Copyright (C) 2010-2012, Red Hat, Inc. All rights reserved.
* Copyright (C) 2010-2014, Milan Broz
* Copyright (C) 2010-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2010-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -27,7 +27,7 @@
#include <sys/socket.h>
#include <sys/utsname.h>
#include <linux/if_alg.h>
#include "crypto_backend.h"
#include "crypto_backend_internal.h"
/* FIXME: remove later */
#ifndef AF_ALG
@@ -38,7 +38,7 @@
#endif
static int crypto_backend_initialised = 0;
static char version[64];
static char version[256];
struct hash_alg {
const char *name;
@@ -48,12 +48,29 @@ struct hash_alg {
};
static struct hash_alg hash_algs[] = {
{ "sha1", "sha1", 20, 64 },
{ "sha256", "sha256", 32, 64 },
{ "sha512", "sha512", 64, 128 },
{ "ripemd160", "rmd160", 20, 64 },
{ "whirlpool", "wp512", 64, 64 },
{ NULL, NULL, 0, 0 }
{ "sha1", "sha1", 20, 64 },
{ "sha224", "sha224", 28, 64 },
{ "sha256", "sha256", 32, 64 },
{ "sha384", "sha384", 48, 128 },
{ "sha512", "sha512", 64, 128 },
{ "ripemd160", "rmd160", 20, 64 },
{ "whirlpool", "wp512", 64, 64 },
{ "sha3-224", "sha3-224", 28, 144 },
{ "sha3-256", "sha3-256", 32, 136 },
{ "sha3-384", "sha3-384", 48, 104 },
{ "sha3-512", "sha3-512", 64, 72 },
{ "stribog256","streebog256", 32, 64 },
{ "stribog512","streebog512", 64, 64 },
{ "sm3", "sm3", 32, 64 },
{ "blake2b-160","blake2b-160",20, 128 },
{ "blake2b-256","blake2b-256",32, 128 },
{ "blake2b-384","blake2b-384",48, 128 },
{ "blake2b-512","blake2b-512",64, 128 },
{ "blake2s-128","blake2s-128",16, 64 },
{ "blake2s-160","blake2s-160",20, 64 },
{ "blake2s-224","blake2s-224",28, 64 },
{ "blake2s-256","blake2s-256",32, 64 },
{ NULL, NULL, 0, 0 }
};
struct crypt_hash {
@@ -68,18 +85,48 @@ struct crypt_hmac {
int hash_len;
};
/* Defined in crypt_kernel_ciphers.c */
extern int crypt_kernel_socket_init(struct sockaddr_alg *sa, int *tfmfd, int *opfd);
struct crypt_cipher {
struct crypt_cipher_kernel ck;
};
int crypt_backend_init(struct crypt_device *ctx)
static int crypt_kernel_socket_init(struct sockaddr_alg *sa, int *tfmfd, int *opfd,
const void *key, size_t key_length)
{
*tfmfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
if (*tfmfd < 0)
return -ENOTSUP;
if (bind(*tfmfd, (struct sockaddr *)sa, sizeof(*sa)) < 0) {
close(*tfmfd);
*tfmfd = -1;
return -ENOENT;
}
if (key && setsockopt(*tfmfd, SOL_ALG, ALG_SET_KEY, key, key_length) < 0) {
close(*tfmfd);
*tfmfd = -1;
return -EINVAL;
}
*opfd = accept(*tfmfd, NULL, 0);
if (*opfd < 0) {
close(*tfmfd);
*tfmfd = -1;
return -EINVAL;
}
return 0;
}
int crypt_backend_init(void)
{
struct utsname uts;
struct sockaddr_alg sa = {
.salg_family = AF_ALG,
.salg_type = "hash",
.salg_name = "sha1",
.salg_name = "sha256",
};
int tfmfd = -1, opfd = -1;
int r, tfmfd = -1, opfd = -1;
if (crypto_backend_initialised)
return 0;
@@ -87,19 +134,26 @@ int crypt_backend_init(struct crypt_device *ctx)
if (uname(&uts) == -1 || strcmp(uts.sysname, "Linux"))
return -EINVAL;
if (crypt_kernel_socket_init(&sa, &tfmfd, &opfd) < 0)
r = snprintf(version, sizeof(version), "%s %s kernel cryptoAPI",
uts.sysname, uts.release);
if (r < 0 || (size_t)r >= sizeof(version))
return -EINVAL;
if (crypt_kernel_socket_init(&sa, &tfmfd, &opfd, NULL, 0) < 0)
return -EINVAL;
close(tfmfd);
close(opfd);
snprintf(version, sizeof(version), "%s %s kernel cryptoAPI",
uts.sysname, uts.release);
crypto_backend_initialised = 1;
return 0;
}
void crypt_backend_destroy(void)
{
crypto_backend_initialised = 0;
}
uint32_t crypt_backend_flags(void)
{
return CRYPT_BACKEND_KERNEL;
@@ -150,9 +204,9 @@ int crypt_hash_init(struct crypt_hash **ctx, const char *name)
}
h->hash_len = ha->length;
strncpy((char *)sa.salg_name, ha->kernel_name, sizeof(sa.salg_name));
strncpy((char *)sa.salg_name, ha->kernel_name, sizeof(sa.salg_name)-1);
if (crypt_kernel_socket_init(&sa, &h->tfmfd, &h->opfd) < 0) {
if (crypt_kernel_socket_init(&sa, &h->tfmfd, &h->opfd, NULL, 0) < 0) {
free(h);
return -EINVAL;
}
@@ -186,15 +240,14 @@ int crypt_hash_final(struct crypt_hash *ctx, char *buffer, size_t length)
return 0;
}
int crypt_hash_destroy(struct crypt_hash *ctx)
void crypt_hash_destroy(struct crypt_hash *ctx)
{
if (ctx->tfmfd != -1)
if (ctx->tfmfd >= 0)
close(ctx->tfmfd);
if (ctx->opfd != -1)
if (ctx->opfd >= 0)
close(ctx->opfd);
memset(ctx, 0, sizeof(*ctx));
free(ctx);
return 0;
}
/* HMAC */
@@ -204,7 +257,7 @@ int crypt_hmac_size(const char *name)
}
int crypt_hmac_init(struct crypt_hmac **ctx, const char *name,
const void *buffer, size_t length)
const void *key, size_t key_length)
{
struct crypt_hmac *h;
struct hash_alg *ha;
@@ -212,6 +265,7 @@ int crypt_hmac_init(struct crypt_hmac **ctx, const char *name,
.salg_family = AF_ALG,
.salg_type = "hash",
};
int r;
h = malloc(sizeof(*h));
if (!h)
@@ -224,16 +278,15 @@ int crypt_hmac_init(struct crypt_hmac **ctx, const char *name,
}
h->hash_len = ha->length;
snprintf((char *)sa.salg_name, sizeof(sa.salg_name),
r = snprintf((char *)sa.salg_name, sizeof(sa.salg_name),
"hmac(%s)", ha->kernel_name);
if (crypt_kernel_socket_init(&sa, &h->tfmfd, &h->opfd) < 0) {
if (r < 0 || (size_t)r >= sizeof(sa.salg_name)) {
free(h);
return -EINVAL;
}
if (setsockopt(h->tfmfd, SOL_ALG, ALG_SET_KEY, buffer, length) == -1) {
crypt_hmac_destroy(h);
if (crypt_kernel_socket_init(&sa, &h->tfmfd, &h->opfd, key, key_length) < 0) {
free(h);
return -EINVAL;
}
@@ -266,15 +319,14 @@ int crypt_hmac_final(struct crypt_hmac *ctx, char *buffer, size_t length)
return 0;
}
int crypt_hmac_destroy(struct crypt_hmac *ctx)
void crypt_hmac_destroy(struct crypt_hmac *ctx)
{
if (ctx->tfmfd != -1)
if (ctx->tfmfd >= 0)
close(ctx->tfmfd);
if (ctx->opfd != -1)
if (ctx->opfd >= 0)
close(ctx->opfd);
memset(ctx, 0, sizeof(*ctx));
free(ctx);
return 0;
}
/* RNG - N/A */
@@ -288,13 +340,79 @@ int crypt_pbkdf(const char *kdf, const char *hash,
const char *password, size_t password_length,
const char *salt, size_t salt_length,
char *key, size_t key_length,
unsigned int iterations)
uint32_t iterations, uint32_t memory, uint32_t parallel)
{
struct hash_alg *ha = _get_alg(hash);
struct hash_alg *ha;
if (!ha || !kdf || strncmp(kdf, "pbkdf2", 6))
if (!kdf)
return -EINVAL;
return pkcs5_pbkdf2(hash, password, password_length, salt, salt_length,
iterations, key_length, key, ha->block_length);
if (!strcmp(kdf, "pbkdf2")) {
ha = _get_alg(hash);
if (!ha)
return -EINVAL;
return pkcs5_pbkdf2(hash, password, password_length, salt, salt_length,
iterations, key_length, key, ha->block_length);
} else if (!strncmp(kdf, "argon2", 6)) {
return argon2(kdf, password, password_length, salt, salt_length,
key, key_length, iterations, memory, parallel);
}
return -EINVAL;
}
/* Block ciphers */
int crypt_cipher_init(struct crypt_cipher **ctx, const char *name,
const char *mode, const void *key, size_t key_length)
{
struct crypt_cipher *h;
int r;
h = malloc(sizeof(*h));
if (!h)
return -ENOMEM;
r = crypt_cipher_init_kernel(&h->ck, name, mode, key, key_length);
if (r < 0) {
free(h);
return r;
}
*ctx = h;
return 0;
}
void crypt_cipher_destroy(struct crypt_cipher *ctx)
{
crypt_cipher_destroy_kernel(&ctx->ck);
free(ctx);
}
int crypt_cipher_encrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
{
return crypt_cipher_encrypt_kernel(&ctx->ck, in, out, length, iv, iv_length);
}
int crypt_cipher_decrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
{
return crypt_cipher_decrypt_kernel(&ctx->ck, in, out, length, iv, iv_length);
}
bool crypt_cipher_kernel_only(struct crypt_cipher *ctx)
{
return true;
}
int crypt_bitlk_decrypt_key(const void *key, size_t key_length,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length,
const char *tag, size_t tag_length)
{
return crypt_bitlk_decrypt_key_kernel(key, key_length, in, out, length,
iv, iv_length, tag, tag_length);
}

View File

@@ -1,8 +1,8 @@
/*
* Nettle crypto backend implementation
*
* Copyright (C) 2011-2012 Red Hat, Inc. All rights reserved.
* Copyright (C) 2011-2014, Milan Broz
* Copyright (C) 2011-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2011-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -23,16 +23,24 @@
#include <string.h>
#include <errno.h>
#include <nettle/sha.h>
#include <nettle/sha3.h>
#include <nettle/hmac.h>
#include <nettle/pbkdf2.h>
#include "crypto_backend.h"
#include "crypto_backend_internal.h"
static char *version = "Nettle";
#if HAVE_NETTLE_VERSION_H
#include <nettle/version.h>
#define VSTR(s) STR(s)
#define STR(s) #s
static const char *version = "Nettle "VSTR(NETTLE_VERSION_MAJOR)"."VSTR(NETTLE_VERSION_MINOR);
#else
static const char *version = "Nettle";
#endif
typedef void (*init_func) (void *);
typedef void (*update_func) (void *, unsigned, const uint8_t *);
typedef void (*digest_func) (void *, unsigned, uint8_t *);
typedef void (*set_key_func) (void *, unsigned, const uint8_t *);
typedef void (*update_func) (void *, size_t, const uint8_t *);
typedef void (*digest_func) (void *, size_t, uint8_t *);
typedef void (*set_key_func) (void *, size_t, const uint8_t *);
struct hash_alg {
const char *name;
@@ -45,6 +53,24 @@ struct hash_alg {
set_key_func hmac_set_key;
};
/* Missing HMAC wrappers in Nettle */
#define HMAC_FCE(xxx) \
struct xhmac_##xxx##_ctx HMAC_CTX(struct xxx##_ctx); \
static void xhmac_##xxx##_set_key(struct xhmac_##xxx##_ctx *ctx, \
size_t key_length, const uint8_t *key) \
{HMAC_SET_KEY(ctx, &nettle_##xxx, key_length, key);} \
static void xhmac_##xxx##_update(struct xhmac_##xxx##_ctx *ctx, \
size_t length, const uint8_t *data) \
{xxx##_update(&ctx->state, length, data);} \
static void xhmac_##xxx##_digest(struct xhmac_##xxx##_ctx *ctx, \
size_t length, uint8_t *digest) \
{HMAC_DIGEST(ctx, &nettle_##xxx, length, digest);}
HMAC_FCE(sha3_224);
HMAC_FCE(sha3_256);
HMAC_FCE(sha3_384);
HMAC_FCE(sha3_512);
static struct hash_alg hash_algs[] = {
{ "sha1", SHA1_DIGEST_SIZE,
(init_func) sha1_init,
@@ -94,6 +120,41 @@ static struct hash_alg hash_algs[] = {
(digest_func) hmac_ripemd160_digest,
(set_key_func) hmac_ripemd160_set_key,
},
/* Nettle prior to version 3.2 has incompatible SHA3 implementation */
#if NETTLE_SHA3_FIPS202
{ "sha3-224", SHA3_224_DIGEST_SIZE,
(init_func) sha3_224_init,
(update_func) sha3_224_update,
(digest_func) sha3_224_digest,
(update_func) xhmac_sha3_224_update,
(digest_func) xhmac_sha3_224_digest,
(set_key_func) xhmac_sha3_224_set_key,
},
{ "sha3-256", SHA3_256_DIGEST_SIZE,
(init_func) sha3_256_init,
(update_func) sha3_256_update,
(digest_func) sha3_256_digest,
(update_func) xhmac_sha3_256_update,
(digest_func) xhmac_sha3_256_digest,
(set_key_func) xhmac_sha3_256_set_key,
},
{ "sha3-384", SHA3_384_DIGEST_SIZE,
(init_func) sha3_384_init,
(update_func) sha3_384_update,
(digest_func) sha3_384_digest,
(update_func) xhmac_sha3_384_update,
(digest_func) xhmac_sha3_384_digest,
(set_key_func) xhmac_sha3_384_set_key,
},
{ "sha3-512", SHA3_512_DIGEST_SIZE,
(init_func) sha3_512_init,
(update_func) sha3_512_update,
(digest_func) sha3_512_digest,
(update_func) xhmac_sha3_512_update,
(digest_func) xhmac_sha3_512_digest,
(set_key_func) xhmac_sha3_512_set_key,
},
#endif
{ NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, }
};
@@ -105,6 +166,11 @@ struct crypt_hash {
struct sha256_ctx sha256;
struct sha384_ctx sha384;
struct sha512_ctx sha512;
struct ripemd160_ctx ripemd160;
struct sha3_224_ctx sha3_224;
struct sha3_256_ctx sha3_256;
struct sha3_384_ctx sha3_384;
struct sha3_512_ctx sha3_512;
} nettle_ctx;
};
@@ -116,11 +182,20 @@ struct crypt_hmac {
struct hmac_sha256_ctx sha256;
struct hmac_sha384_ctx sha384;
struct hmac_sha512_ctx sha512;
struct hmac_ripemd160_ctx ripemd160;
struct xhmac_sha3_224_ctx sha3_224;
struct xhmac_sha3_256_ctx sha3_256;
struct xhmac_sha3_384_ctx sha3_384;
struct xhmac_sha3_512_ctx sha3_512;
} nettle_ctx;
size_t key_length;
uint8_t *key;
};
struct crypt_cipher {
struct crypt_cipher_kernel ck;
};
uint32_t crypt_backend_flags(void)
{
return 0;
@@ -138,11 +213,16 @@ static struct hash_alg *_get_alg(const char *name)
return NULL;
}
int crypt_backend_init(struct crypt_device *ctx)
int crypt_backend_init(void)
{
return 0;
}
void crypt_backend_destroy(void)
{
return;
}
const char *crypt_backend_version(void)
{
return version;
@@ -197,11 +277,10 @@ int crypt_hash_final(struct crypt_hash *ctx, char *buffer, size_t length)
return 0;
}
int crypt_hash_destroy(struct crypt_hash *ctx)
void crypt_hash_destroy(struct crypt_hash *ctx)
{
memset(ctx, 0, sizeof(*ctx));
free(ctx);
return 0;
}
/* HMAC */
@@ -211,7 +290,7 @@ int crypt_hmac_size(const char *name)
}
int crypt_hmac_init(struct crypt_hmac **ctx, const char *name,
const void *buffer, size_t length)
const void *key, size_t key_length)
{
struct crypt_hmac *h;
@@ -225,12 +304,12 @@ int crypt_hmac_init(struct crypt_hmac **ctx, const char *name,
if (!h->hash)
goto bad;
h->key = malloc(length);
h->key = malloc(key_length);
if (!h->key)
goto bad;
memcpy(h->key, buffer, length);
h->key_length = length;
memcpy(h->key, key, key_length);
h->key_length = key_length;
h->hash->init(&h->nettle_ctx);
h->hash->hmac_set_key(&h->nettle_ctx, h->key_length, h->key);
@@ -263,13 +342,12 @@ int crypt_hmac_final(struct crypt_hmac *ctx, char *buffer, size_t length)
return 0;
}
int crypt_hmac_destroy(struct crypt_hmac *ctx)
void crypt_hmac_destroy(struct crypt_hmac *ctx)
{
memset(ctx->key, 0, ctx->key_length);
free(ctx->key);
memset(ctx, 0, sizeof(*ctx));
free(ctx);
return 0;
}
/* RNG - N/A */
@@ -283,23 +361,84 @@ int crypt_pbkdf(const char *kdf, const char *hash,
const char *password, size_t password_length,
const char *salt, size_t salt_length,
char *key, size_t key_length,
unsigned int iterations)
uint32_t iterations, uint32_t memory, uint32_t parallel)
{
struct crypt_hmac *h;
int r;
if (!kdf || strncmp(kdf, "pbkdf2", 6))
if (!kdf)
return -EINVAL;
r = crypt_hmac_init(&h, hash, password, password_length);
if (r < 0)
if (!strcmp(kdf, "pbkdf2")) {
r = crypt_hmac_init(&h, hash, password, password_length);
if (r < 0)
return r;
nettle_pbkdf2(&h->nettle_ctx, h->hash->hmac_update,
h->hash->hmac_digest, h->hash->length, iterations,
salt_length, (const uint8_t *)salt, key_length,
(uint8_t *)key);
crypt_hmac_destroy(h);
return 0;
} else if (!strncmp(kdf, "argon2", 6)) {
return argon2(kdf, password, password_length, salt, salt_length,
key, key_length, iterations, memory, parallel);
}
return -EINVAL;
}
/* Block ciphers */
int crypt_cipher_init(struct crypt_cipher **ctx, const char *name,
const char *mode, const void *key, size_t key_length)
{
struct crypt_cipher *h;
int r;
h = malloc(sizeof(*h));
if (!h)
return -ENOMEM;
r = crypt_cipher_init_kernel(&h->ck, name, mode, key, key_length);
if (r < 0) {
free(h);
return r;
}
nettle_pbkdf2(&h->nettle_ctx, h->hash->nettle_hmac_update,
h->hash->nettle_hmac_digest, h->hash->length, iterations,
salt_length, (const uint8_t *)salt, key_length,
(uint8_t *)key);
crypt_hmac_destroy(h);
*ctx = h;
return 0;
}
void crypt_cipher_destroy(struct crypt_cipher *ctx)
{
crypt_cipher_destroy_kernel(&ctx->ck);
free(ctx);
}
int crypt_cipher_encrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
{
return crypt_cipher_encrypt_kernel(&ctx->ck, in, out, length, iv, iv_length);
}
int crypt_cipher_decrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
{
return crypt_cipher_decrypt_kernel(&ctx->ck, in, out, length, iv, iv_length);
}
bool crypt_cipher_kernel_only(struct crypt_cipher *ctx)
{
return true;
}
int crypt_bitlk_decrypt_key(const void *key, size_t key_length,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length,
const char *tag, size_t tag_length)
{
return crypt_bitlk_decrypt_key_kernel(key, key_length, in, out, length,
iv, iv_length, tag, tag_length);
}

View File

@@ -1,8 +1,8 @@
/*
* NSS crypto backend implementation
*
* Copyright (C) 2010-2012, Red Hat, Inc. All rights reserved.
* Copyright (C) 2010-2014, Milan Broz
* Copyright (C) 2010-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2010-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -23,7 +23,7 @@
#include <errno.h>
#include <nss.h>
#include <pk11pub.h>
#include "crypto_backend.h"
#include "crypto_backend_internal.h"
#define CONST_CAST(x) (x)(uintptr_t)
@@ -59,6 +59,10 @@ struct crypt_hmac {
const struct hash_alg *hash;
};
struct crypt_cipher {
struct crypt_cipher_kernel ck;
};
static struct hash_alg *_get_alg(const char *name)
{
int i = 0;
@@ -71,8 +75,10 @@ static struct hash_alg *_get_alg(const char *name)
return NULL;
}
int crypt_backend_init(struct crypt_device *ctx)
int crypt_backend_init(void)
{
int r;
if (crypto_backend_initialised)
return 0;
@@ -80,14 +86,22 @@ int crypt_backend_init(struct crypt_device *ctx)
return -EINVAL;
#if HAVE_DECL_NSS_GETVERSION
snprintf(version, 64, "NSS %s", NSS_GetVersion());
r = snprintf(version, sizeof(version), "NSS %s", NSS_GetVersion());
#else
snprintf(version, 64, "NSS");
r = snprintf(version, sizeof(version), "NSS");
#endif
if (r < 0 || (size_t)r >= sizeof(version))
return -EINVAL;
crypto_backend_initialised = 1;
return 0;
}
void crypt_backend_destroy(void)
{
crypto_backend_initialised = 0;
}
uint32_t crypt_backend_flags(void)
{
return 0;
@@ -164,7 +178,7 @@ int crypt_hash_final(struct crypt_hash *ctx, char *buffer, size_t length)
return -EINVAL;
memcpy(buffer, tmp, length);
memset(tmp, 0, sizeof(tmp));
crypt_backend_memzero(tmp, sizeof(tmp));
if (tmp_len < length)
return -EINVAL;
@@ -175,12 +189,11 @@ int crypt_hash_final(struct crypt_hash *ctx, char *buffer, size_t length)
return 0;
}
int crypt_hash_destroy(struct crypt_hash *ctx)
void crypt_hash_destroy(struct crypt_hash *ctx)
{
PK11_DestroyContext(ctx->md, PR_TRUE);
memset(ctx, 0, sizeof(*ctx));
free(ctx);
return 0;
}
/* HMAC */
@@ -190,15 +203,15 @@ int crypt_hmac_size(const char *name)
}
int crypt_hmac_init(struct crypt_hmac **ctx, const char *name,
const void *buffer, size_t length)
const void *key, size_t key_length)
{
struct crypt_hmac *h;
SECItem keyItem;
SECItem noParams;
keyItem.type = siBuffer;
keyItem.data = CONST_CAST(unsigned char *)buffer;
keyItem.len = (int)length;
keyItem.data = CONST_CAST(unsigned char *)key;
keyItem.len = (int)key_length;
noParams.type = siBuffer;
noParams.data = 0;
@@ -266,7 +279,7 @@ int crypt_hmac_final(struct crypt_hmac *ctx, char *buffer, size_t length)
return -EINVAL;
memcpy(buffer, tmp, length);
memset(tmp, 0, sizeof(tmp));
crypt_backend_memzero(tmp, sizeof(tmp));
if (tmp_len < length)
return -EINVAL;
@@ -277,7 +290,7 @@ int crypt_hmac_final(struct crypt_hmac *ctx, char *buffer, size_t length)
return 0;
}
int crypt_hmac_destroy(struct crypt_hmac *ctx)
void crypt_hmac_destroy(struct crypt_hmac *ctx)
{
if (ctx->key)
PK11_FreeSymKey(ctx->key);
@@ -287,7 +300,6 @@ int crypt_hmac_destroy(struct crypt_hmac *ctx)
PK11_DestroyContext(ctx->md, PR_TRUE);
memset(ctx, 0, sizeof(*ctx));
free(ctx);
return 0;
}
/* RNG */
@@ -307,13 +319,79 @@ int crypt_pbkdf(const char *kdf, const char *hash,
const char *password, size_t password_length,
const char *salt, size_t salt_length,
char *key, size_t key_length,
unsigned int iterations)
uint32_t iterations, uint32_t memory, uint32_t parallel)
{
struct hash_alg *ha = _get_alg(hash);
struct hash_alg *ha;
if (!ha || !kdf || strncmp(kdf, "pbkdf2", 6))
if (!kdf)
return -EINVAL;
return pkcs5_pbkdf2(hash, password, password_length, salt, salt_length,
iterations, key_length, key, ha->block_length);
if (!strcmp(kdf, "pbkdf2")) {
ha = _get_alg(hash);
if (!ha)
return -EINVAL;
return pkcs5_pbkdf2(hash, password, password_length, salt, salt_length,
iterations, key_length, key, ha->block_length);
} else if (!strncmp(kdf, "argon2", 6)) {
return argon2(kdf, password, password_length, salt, salt_length,
key, key_length, iterations, memory, parallel);
}
return -EINVAL;
}
/* Block ciphers */
int crypt_cipher_init(struct crypt_cipher **ctx, const char *name,
const char *mode, const void *key, size_t key_length)
{
struct crypt_cipher *h;
int r;
h = malloc(sizeof(*h));
if (!h)
return -ENOMEM;
r = crypt_cipher_init_kernel(&h->ck, name, mode, key, key_length);
if (r < 0) {
free(h);
return r;
}
*ctx = h;
return 0;
}
void crypt_cipher_destroy(struct crypt_cipher *ctx)
{
crypt_cipher_destroy_kernel(&ctx->ck);
free(ctx);
}
int crypt_cipher_encrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
{
return crypt_cipher_encrypt_kernel(&ctx->ck, in, out, length, iv, iv_length);
}
int crypt_cipher_decrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
{
return crypt_cipher_decrypt_kernel(&ctx->ck, in, out, length, iv, iv_length);
}
bool crypt_cipher_kernel_only(struct crypt_cipher *ctx)
{
return true;
}
int crypt_bitlk_decrypt_key(const void *key, size_t key_length,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length,
const char *tag, size_t tag_length)
{
return crypt_bitlk_decrypt_key_kernel(key, key_length, in, out, length,
iv, iv_length, tag, tag_length);
}

View File

@@ -1,8 +1,8 @@
/*
* OPENSSL crypto backend implementation
*
* Copyright (C) 2010-2012, Red Hat, Inc. All rights reserved.
* Copyright (C) 2010-2014, Milan Broz
* Copyright (C) 2010-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2010-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -33,33 +33,115 @@
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/rand.h>
#include "crypto_backend.h"
#include "crypto_backend_internal.h"
#define CONST_CAST(x) (x)(uintptr_t)
static int crypto_backend_initialised = 0;
struct crypt_hash {
EVP_MD_CTX md;
EVP_MD_CTX *md;
const EVP_MD *hash_id;
int hash_len;
};
struct crypt_hmac {
HMAC_CTX md;
HMAC_CTX *md;
const EVP_MD *hash_id;
int hash_len;
};
int crypt_backend_init(struct crypt_device *ctx)
struct crypt_cipher {
bool use_kernel;
union {
struct crypt_cipher_kernel kernel;
struct {
EVP_CIPHER_CTX *hd_enc;
EVP_CIPHER_CTX *hd_dec;
size_t iv_length;
} lib;
} u;
};
struct hash_alg {
const char *name;
const char *openssl_name;
};
/*
* Compatible wrappers for OpenSSL < 1.1.0 and LibreSSL < 2.7.0
*/
#if OPENSSL_VERSION_NUMBER < 0x10100000L || \
(defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL)
static void openssl_backend_init(void)
{
OpenSSL_add_all_algorithms();
}
static const char *openssl_backend_version(void)
{
return SSLeay_version(SSLEAY_VERSION);
}
static EVP_MD_CTX *EVP_MD_CTX_new(void)
{
EVP_MD_CTX *md = malloc(sizeof(*md));
if (md)
EVP_MD_CTX_init(md);
return md;
}
static void EVP_MD_CTX_free(EVP_MD_CTX *md)
{
EVP_MD_CTX_cleanup(md);
free(md);
}
static HMAC_CTX *HMAC_CTX_new(void)
{
HMAC_CTX *md = malloc(sizeof(*md));
if (md)
HMAC_CTX_init(md);
return md;
}
static void HMAC_CTX_free(HMAC_CTX *md)
{
HMAC_CTX_cleanup(md);
free(md);
}
#else
static void openssl_backend_init(void)
{
}
static const char *openssl_backend_version(void)
{
return OpenSSL_version(OPENSSL_VERSION);
}
#endif
int crypt_backend_init(void)
{
if (crypto_backend_initialised)
return 0;
OpenSSL_add_all_algorithms();
openssl_backend_init();
crypto_backend_initialised = 1;
return 0;
}
void crypt_backend_destroy(void)
{
crypto_backend_initialised = 0;
}
uint32_t crypt_backend_flags(void)
{
return 0;
@@ -67,14 +149,39 @@ uint32_t crypt_backend_flags(void)
const char *crypt_backend_version(void)
{
return SSLeay_version(SSLEAY_VERSION);
return openssl_backend_version();
}
static const char *crypt_hash_compat_name(const char *name)
{
const char *hash_name = name;
int i;
static struct hash_alg hash_algs[] = {
{ "blake2b-512", "blake2b512" },
{ "blake2s-256", "blake2s256" },
{ NULL, NULL, }};
if (!name)
return NULL;
i = 0;
while (hash_algs[i].name) {
if (!strcasecmp(name, hash_algs[i].name)) {
hash_name = hash_algs[i].openssl_name;
break;
}
i++;
}
return hash_name;
}
/* HASH */
int crypt_hash_size(const char *name)
{
const EVP_MD *hash_id = EVP_get_digestbyname(name);
const EVP_MD *hash_id;
hash_id = EVP_get_digestbyname(crypt_hash_compat_name(name));
if (!hash_id)
return -EINVAL;
@@ -89,13 +196,21 @@ int crypt_hash_init(struct crypt_hash **ctx, const char *name)
if (!h)
return -ENOMEM;
h->hash_id = EVP_get_digestbyname(name);
h->md = EVP_MD_CTX_new();
if (!h->md) {
free(h);
return -ENOMEM;
}
h->hash_id = EVP_get_digestbyname(crypt_hash_compat_name(name));
if (!h->hash_id) {
EVP_MD_CTX_free(h->md);
free(h);
return -EINVAL;
}
if (EVP_DigestInit(&h->md, h->hash_id) != 1) {
if (EVP_DigestInit_ex(h->md, h->hash_id, NULL) != 1) {
EVP_MD_CTX_free(h->md);
free(h);
return -EINVAL;
}
@@ -107,7 +222,7 @@ int crypt_hash_init(struct crypt_hash **ctx, const char *name)
static int crypt_hash_restart(struct crypt_hash *ctx)
{
if (EVP_DigestInit(&ctx->md, ctx->hash_id) != 1)
if (EVP_DigestInit_ex(ctx->md, ctx->hash_id, NULL) != 1)
return -EINVAL;
return 0;
@@ -115,7 +230,7 @@ static int crypt_hash_restart(struct crypt_hash *ctx)
int crypt_hash_write(struct crypt_hash *ctx, const char *buffer, size_t length)
{
if (EVP_DigestUpdate(&ctx->md, buffer, length) != 1)
if (EVP_DigestUpdate(ctx->md, buffer, length) != 1)
return -EINVAL;
return 0;
@@ -129,11 +244,11 @@ int crypt_hash_final(struct crypt_hash *ctx, char *buffer, size_t length)
if (length > (size_t)ctx->hash_len)
return -EINVAL;
if (EVP_DigestFinal_ex(&ctx->md, tmp, &tmp_len) != 1)
if (EVP_DigestFinal_ex(ctx->md, tmp, &tmp_len) != 1)
return -EINVAL;
memcpy(buffer, tmp, length);
memset(tmp, 0, sizeof(tmp));
crypt_backend_memzero(tmp, sizeof(tmp));
if (tmp_len < length)
return -EINVAL;
@@ -144,12 +259,11 @@ int crypt_hash_final(struct crypt_hash *ctx, char *buffer, size_t length)
return 0;
}
int crypt_hash_destroy(struct crypt_hash *ctx)
void crypt_hash_destroy(struct crypt_hash *ctx)
{
EVP_MD_CTX_cleanup(&ctx->md);
EVP_MD_CTX_free(ctx->md);
memset(ctx, 0, sizeof(*ctx));
free(ctx);
return 0;
}
/* HMAC */
@@ -159,7 +273,7 @@ int crypt_hmac_size(const char *name)
}
int crypt_hmac_init(struct crypt_hmac **ctx, const char *name,
const void *buffer, size_t length)
const void *key, size_t key_length)
{
struct crypt_hmac *h;
@@ -167,14 +281,20 @@ int crypt_hmac_init(struct crypt_hmac **ctx, const char *name,
if (!h)
return -ENOMEM;
h->hash_id = EVP_get_digestbyname(name);
h->md = HMAC_CTX_new();
if (!h->md) {
free(h);
return -ENOMEM;
}
h->hash_id = EVP_get_digestbyname(crypt_hash_compat_name(name));
if (!h->hash_id) {
HMAC_CTX_free(h->md);
free(h);
return -EINVAL;
}
HMAC_CTX_init(&h->md);
HMAC_Init_ex(&h->md, buffer, length, h->hash_id, NULL);
HMAC_Init_ex(h->md, key, key_length, h->hash_id, NULL);
h->hash_len = EVP_MD_size(h->hash_id);
*ctx = h;
@@ -183,12 +303,12 @@ int crypt_hmac_init(struct crypt_hmac **ctx, const char *name,
static void crypt_hmac_restart(struct crypt_hmac *ctx)
{
HMAC_Init_ex(&ctx->md, NULL, 0, ctx->hash_id, NULL);
HMAC_Init_ex(ctx->md, NULL, 0, ctx->hash_id, NULL);
}
int crypt_hmac_write(struct crypt_hmac *ctx, const char *buffer, size_t length)
{
HMAC_Update(&ctx->md, (const unsigned char *)buffer, length);
HMAC_Update(ctx->md, (const unsigned char *)buffer, length);
return 0;
}
@@ -200,10 +320,10 @@ int crypt_hmac_final(struct crypt_hmac *ctx, char *buffer, size_t length)
if (length > (size_t)ctx->hash_len)
return -EINVAL;
HMAC_Final(&ctx->md, tmp, &tmp_len);
HMAC_Final(ctx->md, tmp, &tmp_len);
memcpy(buffer, tmp, length);
memset(tmp, 0, sizeof(tmp));
crypt_backend_memzero(tmp, sizeof(tmp));
if (tmp_len < length)
return -EINVAL;
@@ -213,20 +333,16 @@ int crypt_hmac_final(struct crypt_hmac *ctx, char *buffer, size_t length)
return 0;
}
int crypt_hmac_destroy(struct crypt_hmac *ctx)
void crypt_hmac_destroy(struct crypt_hmac *ctx)
{
HMAC_CTX_cleanup(&ctx->md);
HMAC_CTX_free(ctx->md);
memset(ctx, 0, sizeof(*ctx));
free(ctx);
return 0;
}
/* RNG */
int crypt_backend_rng(char *buffer, size_t length, int quality, int fips)
{
if (fips)
return -EINVAL;
if (RAND_bytes((unsigned char *)buffer, length) != 1)
return -EINVAL;
@@ -238,21 +354,223 @@ int crypt_pbkdf(const char *kdf, const char *hash,
const char *password, size_t password_length,
const char *salt, size_t salt_length,
char *key, size_t key_length,
unsigned int iterations)
uint32_t iterations, uint32_t memory, uint32_t parallel)
{
const EVP_MD *hash_id;
if (!kdf || strncmp(kdf, "pbkdf2", 6))
if (!kdf)
return -EINVAL;
hash_id = EVP_get_digestbyname(hash);
if (!hash_id)
if (!strcmp(kdf, "pbkdf2")) {
hash_id = EVP_get_digestbyname(crypt_hash_compat_name(hash));
if (!hash_id)
return -EINVAL;
if (!PKCS5_PBKDF2_HMAC(password, (int)password_length,
(const unsigned char *)salt, (int)salt_length,
(int)iterations, hash_id, (int)key_length, (unsigned char *)key))
return -EINVAL;
return 0;
} else if (!strncmp(kdf, "argon2", 6)) {
return argon2(kdf, password, password_length, salt, salt_length,
key, key_length, iterations, memory, parallel);
}
return -EINVAL;
}
/* Block ciphers */
static void _cipher_destroy(EVP_CIPHER_CTX **hd_enc, EVP_CIPHER_CTX **hd_dec)
{
EVP_CIPHER_CTX_free(*hd_enc);
*hd_enc = NULL;
EVP_CIPHER_CTX_free(*hd_dec);
*hd_dec = NULL;
}
static int _cipher_init(EVP_CIPHER_CTX **hd_enc, EVP_CIPHER_CTX **hd_dec, const char *name,
const char *mode, const void *key, size_t key_length, size_t *iv_length)
{
char cipher_name[256];
const EVP_CIPHER *type;
int r, key_bits;
key_bits = key_length * 8;
if (!strcmp(mode, "xts"))
key_bits /= 2;
r = snprintf(cipher_name, sizeof(cipher_name), "%s-%d-%s", name, key_bits, mode);
if (r < 0 || (size_t)r >= sizeof(cipher_name))
return -EINVAL;
if (!PKCS5_PBKDF2_HMAC(password, (int)password_length,
(unsigned char *)salt, (int)salt_length,
(int)iterations, hash_id, (int)key_length, (unsigned char *)key))
type = EVP_get_cipherbyname(cipher_name);
if (!type)
return -ENOENT;
if (EVP_CIPHER_key_length(type) != (int)key_length)
return -EINVAL;
*hd_enc = EVP_CIPHER_CTX_new();
*hd_dec = EVP_CIPHER_CTX_new();
*iv_length = EVP_CIPHER_iv_length(type);
if (!*hd_enc || !*hd_dec)
return -EINVAL;
if (EVP_EncryptInit_ex(*hd_enc, type, NULL, key, NULL) != 1 ||
EVP_DecryptInit_ex(*hd_dec, type, NULL, key, NULL) != 1) {
_cipher_destroy(hd_enc, hd_dec);
return -EINVAL;
}
if (EVP_CIPHER_CTX_set_padding(*hd_enc, 0) != 1 ||
EVP_CIPHER_CTX_set_padding(*hd_dec, 0) != 1) {
_cipher_destroy(hd_enc, hd_dec);
return -EINVAL;
}
return 0;
}
int crypt_cipher_init(struct crypt_cipher **ctx, const char *name,
const char *mode, const void *key, size_t key_length)
{
struct crypt_cipher *h;
int r;
h = malloc(sizeof(*h));
if (!h)
return -ENOMEM;
if (!_cipher_init(&h->u.lib.hd_enc, &h->u.lib.hd_dec, name, mode, key,
key_length, &h->u.lib.iv_length)) {
h->use_kernel = false;
*ctx = h;
return 0;
}
r = crypt_cipher_init_kernel(&h->u.kernel, name, mode, key, key_length);
if (r < 0) {
free(h);
return r;
}
h->use_kernel = true;
*ctx = h;
return 0;
}
void crypt_cipher_destroy(struct crypt_cipher *ctx)
{
if (ctx->use_kernel)
crypt_cipher_destroy_kernel(&ctx->u.kernel);
else
_cipher_destroy(&ctx->u.lib.hd_enc, &ctx->u.lib.hd_dec);
free(ctx);
}
static int _cipher_encrypt(struct crypt_cipher *ctx, const unsigned char *in, unsigned char *out,
int length, const unsigned char *iv, size_t iv_length)
{
int len;
if (ctx->u.lib.iv_length != iv_length)
return -EINVAL;
if (EVP_EncryptInit_ex(ctx->u.lib.hd_enc, NULL, NULL, NULL, iv) != 1)
return -EINVAL;
if (EVP_EncryptUpdate(ctx->u.lib.hd_enc, out, &len, in, length) != 1)
return -EINVAL;
if (EVP_EncryptFinal(ctx->u.lib.hd_enc, out + len, &len) != 1)
return -EINVAL;
return 0;
}
static int _cipher_decrypt(struct crypt_cipher *ctx, const unsigned char *in, unsigned char *out,
int length, const unsigned char *iv, size_t iv_length)
{
int len;
if (ctx->u.lib.iv_length != iv_length)
return -EINVAL;
if (EVP_DecryptInit_ex(ctx->u.lib.hd_dec, NULL, NULL, NULL, iv) != 1)
return -EINVAL;
if (EVP_DecryptUpdate(ctx->u.lib.hd_dec, out, &len, in, length) != 1)
return -EINVAL;
if (EVP_DecryptFinal(ctx->u.lib.hd_dec, out + len, &len) != 1)
return -EINVAL;
return 0;
}
int crypt_cipher_encrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
{
if (ctx->use_kernel)
return crypt_cipher_encrypt_kernel(&ctx->u.kernel, in, out, length, iv, iv_length);
return _cipher_encrypt(ctx, (const unsigned char*)in,
(unsigned char *)out, length, (const unsigned char*)iv, iv_length);
}
int crypt_cipher_decrypt(struct crypt_cipher *ctx,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length)
{
if (ctx->use_kernel)
return crypt_cipher_decrypt_kernel(&ctx->u.kernel, in, out, length, iv, iv_length);
return _cipher_decrypt(ctx, (const unsigned char*)in,
(unsigned char *)out, length, (const unsigned char*)iv, iv_length);
}
bool crypt_cipher_kernel_only(struct crypt_cipher *ctx)
{
return ctx->use_kernel;
}
int crypt_bitlk_decrypt_key(const void *key, size_t key_length,
const char *in, char *out, size_t length,
const char *iv, size_t iv_length,
const char *tag, size_t tag_length)
{
#ifdef EVP_CTRL_CCM_SET_IVLEN
EVP_CIPHER_CTX *ctx;
int len = 0, r = -EINVAL;
ctx = EVP_CIPHER_CTX_new();
if (!ctx)
return -EINVAL;
if (EVP_DecryptInit_ex(ctx, EVP_aes_256_ccm(), NULL, NULL, NULL) != 1)
goto out;
//EVP_CIPHER_CTX_key_length(ctx)
//EVP_CIPHER_CTX_iv_length(ctx)
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_IVLEN, iv_length, NULL) != 1)
goto out;
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_TAG, tag_length, CONST_CAST(void*)tag) != 1)
goto out;
if (EVP_DecryptInit_ex(ctx, NULL, NULL, key, (const unsigned char*)iv) != 1)
goto out;
if (EVP_DecryptUpdate(ctx, (unsigned char*)out, &len, (const unsigned char*)in, length) == 1)
r = 0;
out:
EVP_CIPHER_CTX_free(ctx);
return r;
#else
return -ENOTSUP;
#endif
}

View File

@@ -2,7 +2,7 @@
* Generic wrapper for storage encryption modes and Initial Vectors
* (reimplementation of some functions from Linux dm-crypt kernel)
*
* Copyright (C) 2014, Milan Broz
* Copyright (C) 2014-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -25,23 +25,23 @@
#include "crypto_backend.h"
#define SECTOR_SHIFT 9
#define SECTOR_SIZE (1 << SECTOR_SHIFT)
/*
* Internal IV helper
* IV documentation: https://code.google.com/p/cryptsetup/wiki/DMCrypt
* IV documentation: https://gitlab.com/cryptsetup/cryptsetup/wikis/DMCrypt
*/
struct crypt_sector_iv {
enum { IV_NONE, IV_NULL, IV_PLAIN, IV_PLAIN64, IV_ESSIV, IV_BENBI } type;
enum { IV_NONE, IV_NULL, IV_PLAIN, IV_PLAIN64, IV_ESSIV, IV_BENBI, IV_PLAIN64BE, IV_EBOIV } type;
int iv_size;
char *iv;
struct crypt_cipher *essiv_cipher;
int benbi_shift;
struct crypt_cipher *cipher;
int shift;
};
/* Block encryption storage context */
struct crypt_storage {
uint64_t sector_start;
size_t sector_size;
unsigned iv_shift;
struct crypt_cipher *cipher;
struct crypt_sector_iv cipher_iv;
};
@@ -55,23 +55,33 @@ static int int_log2(unsigned int x)
}
static int crypt_sector_iv_init(struct crypt_sector_iv *ctx,
const char *cipher_name, const char *iv_name,
char *key, size_t key_length)
const char *cipher_name, const char *mode_name,
const char *iv_name, const void *key, size_t key_length,
size_t sector_size)
{
int r;
memset(ctx, 0, sizeof(*ctx));
ctx->iv_size = crypt_cipher_blocksize(cipher_name);
if (ctx->iv_size < 0)
ctx->iv_size = crypt_cipher_ivsize(cipher_name, mode_name);
if (ctx->iv_size < 0 || (strcmp(mode_name, "ecb") && ctx->iv_size < 8))
return -ENOENT;
if (!iv_name || !strcmp(cipher_name, "cipher_null")) {
if (!strcmp(cipher_name, "cipher_null") ||
!strcmp(mode_name, "ecb")) {
if (iv_name)
return -EINVAL;
ctx->type = IV_NONE;
ctx->iv_size = 0;
return 0;
} else if (!iv_name) {
return -EINVAL;
} else if (!strcasecmp(iv_name, "null")) {
ctx->type = IV_NULL;
} else if (!strcasecmp(iv_name, "plain64")) {
ctx->type = IV_PLAIN64;
} else if (!strcasecmp(iv_name, "plain64be")) {
ctx->type = IV_PLAIN64BE;
} else if (!strcasecmp(iv_name, "plain")) {
ctx->type = IV_PLAIN;
} else if (!strncasecmp(iv_name, "essiv:", 6)) {
@@ -79,7 +89,6 @@ static int crypt_sector_iv_init(struct crypt_sector_iv *ctx,
char *hash_name = strchr(iv_name, ':');
int hash_size;
char tmp[256];
int r;
if (!hash_name)
return -EINVAL;
@@ -103,13 +112,13 @@ static int crypt_sector_iv_init(struct crypt_sector_iv *ctx,
r = crypt_hash_final(h, tmp, hash_size);
crypt_hash_destroy(h);
if (r) {
memset(tmp, 0, sizeof(tmp));
crypt_backend_memzero(tmp, sizeof(tmp));
return r;
}
r = crypt_cipher_init(&ctx->essiv_cipher, cipher_name, "ecb",
r = crypt_cipher_init(&ctx->cipher, cipher_name, "ecb",
tmp, hash_size);
memset(tmp, 0, sizeof(tmp));
crypt_backend_memzero(tmp, sizeof(tmp));
if (r)
return r;
@@ -120,7 +129,15 @@ static int crypt_sector_iv_init(struct crypt_sector_iv *ctx,
return -EINVAL;
ctx->type = IV_BENBI;
ctx->benbi_shift = SECTOR_SHIFT - log;
ctx->shift = SECTOR_SHIFT - log;
} else if (!strncasecmp(iv_name, "eboiv", 5)) {
r = crypt_cipher_init(&ctx->cipher, cipher_name, "ecb",
key, key_length);
if (r)
return r;
ctx->type = IV_EBOIV;
ctx->shift = int_log2(sector_size);
} else
return -ENOENT;
@@ -149,17 +166,27 @@ static int crypt_sector_iv_generate(struct crypt_sector_iv *ctx, uint64_t sector
memset(ctx->iv, 0, ctx->iv_size);
*(uint64_t *)ctx->iv = cpu_to_le64(sector);
break;
case IV_PLAIN64BE:
memset(ctx->iv, 0, ctx->iv_size);
*(uint64_t *)&ctx->iv[ctx->iv_size - sizeof(uint64_t)] = cpu_to_be64(sector);
break;
case IV_ESSIV:
memset(ctx->iv, 0, ctx->iv_size);
*(uint64_t *)ctx->iv = cpu_to_le64(sector);
return crypt_cipher_encrypt(ctx->essiv_cipher,
return crypt_cipher_encrypt(ctx->cipher,
ctx->iv, ctx->iv, ctx->iv_size, NULL, 0);
break;
case IV_BENBI:
memset(ctx->iv, 0, ctx->iv_size);
val = cpu_to_be64((sector << ctx->benbi_shift) + 1);
val = cpu_to_be64((sector << ctx->shift) + 1);
memcpy(ctx->iv + ctx->iv_size - sizeof(val), &val, sizeof(val));
break;
case IV_EBOIV:
memset(ctx->iv, 0, ctx->iv_size);
*(uint64_t *)ctx->iv = cpu_to_le64(sector << ctx->shift);
return crypt_cipher_encrypt(ctx->cipher,
ctx->iv, ctx->iv, ctx->iv_size, NULL, 0);
break;
default:
return -EINVAL;
}
@@ -167,10 +194,10 @@ static int crypt_sector_iv_generate(struct crypt_sector_iv *ctx, uint64_t sector
return 0;
}
static int crypt_sector_iv_destroy(struct crypt_sector_iv *ctx)
static void crypt_sector_iv_destroy(struct crypt_sector_iv *ctx)
{
if (ctx->type == IV_ESSIV)
crypt_cipher_destroy(ctx->essiv_cipher);
if (ctx->type == IV_ESSIV || ctx->type == IV_EBOIV)
crypt_cipher_destroy(ctx->cipher);
if (ctx->iv) {
memset(ctx->iv, 0, ctx->iv_size);
@@ -178,22 +205,27 @@ static int crypt_sector_iv_destroy(struct crypt_sector_iv *ctx)
}
memset(ctx, 0, sizeof(*ctx));
return 0;
}
/* Block encryption storage wrappers */
int crypt_storage_init(struct crypt_storage **ctx,
uint64_t sector_start,
size_t sector_size,
const char *cipher,
const char *cipher_mode,
char *key, size_t key_length)
const void *key, size_t key_length,
bool large_iv)
{
struct crypt_storage *s;
char mode_name[64];
char *cipher_iv = NULL;
int r = -EIO;
if (sector_size < (1 << SECTOR_SHIFT) ||
sector_size > (1 << (SECTOR_SHIFT + 3)) ||
sector_size & (sector_size - 1))
return -EINVAL;
s = malloc(sizeof(*s));
if (!s)
return -ENOMEM;
@@ -214,33 +246,40 @@ int crypt_storage_init(struct crypt_storage **ctx,
return r;
}
r = crypt_sector_iv_init(&s->cipher_iv, cipher, cipher_iv, key, key_length);
r = crypt_sector_iv_init(&s->cipher_iv, cipher, mode_name, cipher_iv, key, key_length, sector_size);
if (r) {
crypt_storage_destroy(s);
return r;
}
s->sector_start = sector_start;
s->sector_size = sector_size;
s->iv_shift = large_iv ? int_log2(sector_size) - SECTOR_SHIFT : 0;
*ctx = s;
return 0;
}
int crypt_storage_decrypt(struct crypt_storage *ctx,
uint64_t sector, size_t count,
char *buffer)
uint64_t iv_offset,
uint64_t length, char *buffer)
{
unsigned int i;
uint64_t i;
int r = 0;
for (i = 0; i < count; i++) {
r = crypt_sector_iv_generate(&ctx->cipher_iv, sector + i);
if (length & (ctx->sector_size - 1))
return -EINVAL;
if (iv_offset & ((ctx->sector_size >> SECTOR_SHIFT) - 1))
return -EINVAL;
for (i = 0; i < length; i += ctx->sector_size) {
r = crypt_sector_iv_generate(&ctx->cipher_iv, (iv_offset + (i >> SECTOR_SHIFT)) >> ctx->iv_shift);
if (r)
break;
r = crypt_cipher_decrypt(ctx->cipher,
&buffer[i * SECTOR_SIZE],
&buffer[i * SECTOR_SIZE],
SECTOR_SIZE,
&buffer[i],
&buffer[i],
ctx->sector_size,
ctx->cipher_iv.iv,
ctx->cipher_iv.iv_size);
if (r)
@@ -251,20 +290,26 @@ int crypt_storage_decrypt(struct crypt_storage *ctx,
}
int crypt_storage_encrypt(struct crypt_storage *ctx,
uint64_t sector, size_t count,
char *buffer)
uint64_t iv_offset,
uint64_t length, char *buffer)
{
unsigned int i;
uint64_t i;
int r = 0;
for (i = 0; i < count; i++) {
r = crypt_sector_iv_generate(&ctx->cipher_iv, sector + i);
if (length & (ctx->sector_size - 1))
return -EINVAL;
if (iv_offset & ((ctx->sector_size >> SECTOR_SHIFT) - 1))
return -EINVAL;
for (i = 0; i < length; i += ctx->sector_size) {
r = crypt_sector_iv_generate(&ctx->cipher_iv, (iv_offset + (i >> SECTOR_SHIFT)) >> ctx->iv_shift);
if (r)
break;
r = crypt_cipher_encrypt(ctx->cipher,
&buffer[i * SECTOR_SIZE],
&buffer[i * SECTOR_SIZE],
SECTOR_SIZE,
&buffer[i],
&buffer[i],
ctx->sector_size,
ctx->cipher_iv.iv,
ctx->cipher_iv.iv_size);
if (r)
@@ -274,10 +319,10 @@ int crypt_storage_encrypt(struct crypt_storage *ctx,
return r;
}
int crypt_storage_destroy(struct crypt_storage *ctx)
void crypt_storage_destroy(struct crypt_storage *ctx)
{
if (!ctx)
return 0;
return;
crypt_sector_iv_destroy(&ctx->cipher_iv);
@@ -286,6 +331,9 @@ int crypt_storage_destroy(struct crypt_storage *ctx)
memset(ctx, 0, sizeof(*ctx));
free(ctx);
return 0;
}
bool crypt_storage_kernel_only(struct crypt_storage *ctx)
{
return crypt_cipher_kernel_only(ctx->cipher);
}

View File

@@ -4,8 +4,8 @@
* Copyright (C) 2004 Free Software Foundation
*
* cryptsetup related changes
* Copyright (C) 2012, Red Hat, Inc. All rights reserved.
* Copyright (C) 2012-2014, Milan Broz
* Copyright (C) 2012-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2012-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -25,7 +25,7 @@
#include <errno.h>
#include <alloca.h>
#include "crypto_backend.h"
#include "crypto_backend_internal.h"
static int hash_buf(const char *src, size_t src_len,
char *dst, size_t dst_len,
@@ -188,7 +188,7 @@ int pkcs5_pbkdf2(const char *hash,
if (crypt_hmac_init(&hmac, hash, P_hash, hLen))
return -EINVAL;
memset(P_hash, 0, sizeof(P_hash));
crypt_backend_memzero(P_hash, sizeof(P_hash));
} else {
if (crypt_hmac_init(&hmac, hash, P, Plen))
return -EINVAL;
@@ -224,203 +224,9 @@ int pkcs5_pbkdf2(const char *hash,
rc = 0;
out:
crypt_hmac_destroy(hmac);
memset(U, 0, sizeof(U));
memset(T, 0, sizeof(T));
memset(tmp, 0, tmplen);
crypt_backend_memzero(U, sizeof(U));
crypt_backend_memzero(T, sizeof(T));
crypt_backend_memzero(tmp, tmplen);
return rc;
}
#if 0
#include <stdio.h>
struct test_vector {
const char *hash;
unsigned int hash_block_length;
unsigned int iterations;
const char *password;
unsigned int password_length;
const char *salt;
unsigned int salt_length;
const char *output;
unsigned int output_length;
};
struct test_vector test_vectors[] = {
/* RFC 3962 */
{
"sha1", 64, 1,
"password", 8,
"ATHENA.MIT.EDUraeburn", 21,
"\xcd\xed\xb5\x28\x1b\xb2\xf8\x01"
"\x56\x5a\x11\x22\xb2\x56\x35\x15"
"\x0a\xd1\xf7\xa0\x4b\xb9\xf3\xa3"
"\x33\xec\xc0\xe2\xe1\xf7\x08\x37", 32
}, {
"sha1", 64, 2,
"password", 8,
"ATHENA.MIT.EDUraeburn", 21,
"\x01\xdb\xee\x7f\x4a\x9e\x24\x3e"
"\x98\x8b\x62\xc7\x3c\xda\x93\x5d"
"\xa0\x53\x78\xb9\x32\x44\xec\x8f"
"\x48\xa9\x9e\x61\xad\x79\x9d\x86", 32
}, {
"sha1", 64, 1200,
"password", 8,
"ATHENA.MIT.EDUraeburn", 21,
"\x5c\x08\xeb\x61\xfd\xf7\x1e\x4e"
"\x4e\xc3\xcf\x6b\xa1\xf5\x51\x2b"
"\xa7\xe5\x2d\xdb\xc5\xe5\x14\x2f"
"\x70\x8a\x31\xe2\xe6\x2b\x1e\x13", 32
}, {
"sha1", 64, 5,
"password", 8,
"\0224VxxV4\022", 8, // "\x1234567878563412
"\xd1\xda\xa7\x86\x15\xf2\x87\xe6"
"\xa1\xc8\xb1\x20\xd7\x06\x2a\x49"
"\x3f\x98\xd2\x03\xe6\xbe\x49\xa6"
"\xad\xf4\xfa\x57\x4b\x6e\x64\xee", 32
}, {
"sha1", 64, 1200,
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 64,
"pass phrase equals block size", 29,
"\x13\x9c\x30\xc0\x96\x6b\xc3\x2b"
"\xa5\x5f\xdb\xf2\x12\x53\x0a\xc9"
"\xc5\xec\x59\xf1\xa4\x52\xf5\xcc"
"\x9a\xd9\x40\xfe\xa0\x59\x8e\xd1", 32
}, {
"sha1", 64, 1200,
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 65,
"pass phrase exceeds block size", 30,
"\x9c\xca\xd6\xd4\x68\x77\x0c\xd5"
"\x1b\x10\xe6\xa6\x87\x21\xbe\x61"
"\x1a\x8b\x4d\x28\x26\x01\xdb\x3b"
"\x36\xbe\x92\x46\x91\x5e\xc8\x2a", 32
}, {
"sha1", 64, 50,
"\360\235\204\236", 4, // g-clef ("\xf09d849e)
"EXAMPLE.COMpianist", 18,
"\x6b\x9c\xf2\x6d\x45\x45\x5a\x43"
"\xa5\xb8\xbb\x27\x6a\x40\x3b\x39"
"\xe7\xfe\x37\xa0\xc4\x1e\x02\xc2"
"\x81\xff\x30\x69\xe1\xe9\x4f\x52", 32
}, {
/* RFC-6070 */
"sha1", 64, 1,
"password", 8,
"salt", 4,
"\x0c\x60\xc8\x0f\x96\x1f\x0e\x71\xf3\xa9"
"\xb5\x24\xaf\x60\x12\x06\x2f\xe0\x37\xa6", 20
}, {
"sha1", 64, 2,
"password", 8,
"salt", 4,
"\xea\x6c\x01\x4d\xc7\x2d\x6f\x8c\xcd\x1e"
"\xd9\x2a\xce\x1d\x41\xf0\xd8\xde\x89\x57", 20
}, {
"sha1", 64, 4096,
"password", 8,
"salt", 4,
"\x4b\x00\x79\x01\xb7\x65\x48\x9a\xbe\xad"
"\x49\xd9\x26\xf7\x21\xd0\x65\xa4\x29\xc1", 20
}, {
"sha1", 64, 16777216,
"password", 8,
"salt", 4,
"\xee\xfe\x3d\x61\xcd\x4d\xa4\xe4\xe9\x94"
"\x5b\x3d\x6b\xa2\x15\x8c\x26\x34\xe9\x84", 20
}, {
"sha1", 64, 4096,
"passwordPASSWORDpassword", 24,
"saltSALTsaltSALTsaltSALTsaltSALTsalt", 36,
"\x3d\x2e\xec\x4f\xe4\x1c\x84\x9b\x80\xc8"
"\xd8\x36\x62\xc0\xe4\x4a\x8b\x29\x1a\x96"
"\x4c\xf2\xf0\x70\x38", 25
}, {
"sha1", 64, 4096,
"pass\0word", 9,
"sa\0lt", 5,
"\x56\xfa\x6a\xa7\x55\x48\x09\x9d\xcc\x37"
"\xd7\xf0\x34\x25\xe0\xc3", 16
}, {
/* empty password test */
"sha1", 64, 2,
"", 0,
"salt", 4,
"\x13\x3a\x4c\xe8\x37\xb4\xd2\x52\x1e\xe2"
"\xbf\x03\xe1\x1c\x71\xca\x79\x4e\x07\x97", 20
}, {
/* Password exceeds block size test */
"sha256", 64, 1200,
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 65,
"pass phrase exceeds block size", 30,
"\x22\x34\x4b\xc4\xb6\xe3\x26\x75"
"\xa8\x09\x0f\x3e\xa8\x0b\xe0\x1d"
"\x5f\x95\x12\x6a\x2c\xdd\xc3\xfa"
"\xcc\x4a\x5e\x6d\xca\x04\xec\x58", 32
}, {
"sha512", 128, 1200,
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 129,
"pass phrase exceeds block size", 30,
"\x0f\xb2\xed\x2c\x0e\x6e\xfb\x7d"
"\x7d\x8e\xdd\x58\x01\xb4\x59\x72"
"\x99\x92\x16\x30\x5e\xa4\x36\x8d"
"\x76\x14\x80\xf3\xe3\x7a\x22\xb9", 32
}, {
"whirlpool", 64, 1200,
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 65,
"pass phrase exceeds block size", 30,
"\x9c\x1c\x74\xf5\x88\x26\xe7\x6a"
"\x53\x58\xf4\x0c\x39\xe7\x80\x89"
"\x07\xc0\x31\x19\x9a\x50\xa2\x48"
"\xf1\xd9\xfe\x78\x64\xe5\x84\x50", 32
}
};
static void printhex(const char *s, const char *buf, size_t len)
{
size_t i;
printf("%s: ", s);
for (i = 0; i < len; i++)
printf("\\x%02x", (unsigned char)buf[i]);
printf("\n");
fflush(stdout);
}
static int pkcs5_pbkdf2_test_vectors(void)
{
char result[64];
unsigned int i, j;
struct test_vector *vec;
for (i = 0; i < (sizeof(test_vectors) / sizeof(*test_vectors)); i++) {
vec = &test_vectors[i];
for (j = 1; j <= vec->output_length; j++) {
if (pkcs5_pbkdf2(vec->hash,
vec->password, vec->password_length,
vec->salt, vec->salt_length,
vec->iterations,
j, result, vec->hash_block_length)) {
printf("pbkdf2 failed, vector %d\n", i);
return -EINVAL;
}
if (memcmp(result, vec->output, j) != 0) {
printf("vector %u\n", i);
printhex(" got", result, j);
printhex("want", vec->output, j);
return -EINVAL;
}
memset(result, 0, sizeof(result));
}
}
return 0;
}
#endif

View File

@@ -1,7 +1,8 @@
/*
* PBKDF performance check
* Copyright (C) 2012, Red Hat, Inc. All rights reserved.
* Copyright (C) 2012-2014, Milan Broz
* Copyright (C) 2012-2021 Red Hat, Inc. All rights reserved.
* Copyright (C) 2012-2021 Milan Broz
* Copyright (C) 2016-2020 Ondrej Mosnacek
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -18,11 +19,52 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "crypto_backend.h"
#ifndef CLOCK_MONOTONIC_RAW
#define CLOCK_MONOTONIC_RAW CLOCK_MONOTONIC
#endif
#define BENCH_MIN_MS 250
#define BENCH_MIN_MS_FAST 10
#define BENCH_PERCENT_ATLEAST 95
#define BENCH_PERCENT_ATMOST 110
#define BENCH_SAMPLES_FAST 3
#define BENCH_SAMPLES_SLOW 1
/* These PBKDF2 limits must be never violated */
int crypt_pbkdf_get_limits(const char *kdf, struct crypt_pbkdf_limits *limits)
{
if (!kdf || !limits)
return -EINVAL;
if (!strcmp(kdf, "pbkdf2")) {
limits->min_iterations = 1000; /* recommendation in NIST SP 800-132 */
limits->max_iterations = UINT32_MAX;
limits->min_memory = 0; /* N/A */
limits->max_memory = 0; /* N/A */
limits->min_parallel = 0; /* N/A */
limits->max_parallel = 0; /* N/A */
return 0;
} else if (!strcmp(kdf, "argon2i") || !strcmp(kdf, "argon2id")) {
limits->min_iterations = 4;
limits->max_iterations = UINT32_MAX;
limits->min_memory = 32;
limits->max_memory = 4*1024*1024; /* 4GiB */
limits->min_parallel = 1;
limits->max_parallel = 4;
return 0;
}
return -EINVAL;
}
static long time_ms(struct rusage *start, struct rusage *end)
{
int count_kernel_time = 0;
@@ -50,35 +92,287 @@ static long time_ms(struct rusage *start, struct rusage *end)
return ms;
}
static long timespec_ms(struct timespec *start, struct timespec *end)
{
return (end->tv_sec - start->tv_sec) * 1000 +
(end->tv_nsec - start->tv_nsec) / (1000 * 1000);
}
static int measure_argon2(const char *kdf, const char *password, size_t password_length,
const char *salt, size_t salt_length,
char *key, size_t key_length,
uint32_t t_cost, uint32_t m_cost, uint32_t parallel,
size_t samples, long ms_atleast, long *out_ms)
{
long ms, ms_min = LONG_MAX;
int r;
size_t i;
for (i = 0; i < samples; i++) {
struct timespec tstart, tend;
/*
* NOTE: We must use clock_gettime here, because Argon2 can run over
* multiple threads, and thus we care about real time, not CPU time!
*/
if (clock_gettime(CLOCK_MONOTONIC_RAW, &tstart) < 0)
return -EINVAL;
r = crypt_pbkdf(kdf, NULL, password, password_length, salt,
salt_length, key, key_length, t_cost, m_cost, parallel);
if (r < 0)
return r;
if (clock_gettime(CLOCK_MONOTONIC_RAW, &tend) < 0)
return -EINVAL;
ms = timespec_ms(&tstart, &tend);
if (ms < 0)
return -EINVAL;
if (ms < ms_atleast) {
/* early exit */
ms_min = ms;
break;
}
if (ms < ms_min) {
ms_min = ms;
}
}
*out_ms = ms_min;
return 0;
}
#define CONTINUE 0
#define FINAL 1
static int next_argon2_params(uint32_t *t_cost, uint32_t *m_cost,
uint32_t min_t_cost, uint32_t min_m_cost,
uint32_t max_m_cost, long ms, uint32_t target_ms)
{
uint32_t old_t_cost, old_m_cost, new_t_cost, new_m_cost;
uint64_t num, denom;
old_t_cost = *t_cost;
old_m_cost = *m_cost;
if ((uint32_t)ms > target_ms) {
/* decreasing, first try to lower t_cost, then m_cost */
num = (uint64_t)*t_cost * (uint64_t)target_ms;
denom = (uint64_t)ms;
new_t_cost = (uint32_t)(num / denom);
if (new_t_cost < min_t_cost) {
num = (uint64_t)*t_cost * (uint64_t)*m_cost *
(uint64_t)target_ms;
denom = (uint64_t)min_t_cost * (uint64_t)ms;
*t_cost = min_t_cost;
*m_cost = (uint32_t)(num / denom);
if (*m_cost < min_m_cost) {
*m_cost = min_m_cost;
return FINAL;
}
} else {
*t_cost = new_t_cost;
}
} else {
/* increasing, first try to increase m_cost, then t_cost */
num = (uint64_t)*m_cost * (uint64_t)target_ms;
denom = (uint64_t)ms;
new_m_cost = (uint32_t)(num / denom);
if (new_m_cost > max_m_cost) {
num = (uint64_t)*t_cost * (uint64_t)*m_cost *
(uint64_t)target_ms;
denom = (uint64_t)max_m_cost * (uint64_t)ms;
*t_cost = (uint32_t)(num / denom);
*m_cost = max_m_cost;
if (*t_cost <= min_t_cost) {
*t_cost = min_t_cost;
return FINAL;
}
} else if (new_m_cost < min_m_cost) {
*m_cost = min_m_cost;
return FINAL;
} else {
*m_cost = new_m_cost;
}
}
/* do not continue if it is the same as in the previous run */
if (old_t_cost == *t_cost && old_m_cost == *m_cost)
return FINAL;
return CONTINUE;
}
static int crypt_argon2_check(const char *kdf, const char *password,
size_t password_length, const char *salt,
size_t salt_length, size_t key_length,
uint32_t min_t_cost, uint32_t min_m_cost, uint32_t max_m_cost,
uint32_t parallel, uint32_t target_ms,
uint32_t *out_t_cost, uint32_t *out_m_cost,
int (*progress)(uint32_t time_ms, void *usrptr),
void *usrptr)
{
int r = 0;
char *key = NULL;
uint32_t t_cost, m_cost;
long ms;
long ms_atleast = (long)target_ms * BENCH_PERCENT_ATLEAST / 100;
long ms_atmost = (long)target_ms * BENCH_PERCENT_ATMOST / 100;
if (key_length <= 0 || target_ms <= 0)
return -EINVAL;
if (min_m_cost < (parallel * 8))
min_m_cost = parallel * 8;
if (max_m_cost < min_m_cost)
return -EINVAL;
key = malloc(key_length);
if (!key)
return -ENOMEM;
t_cost = min_t_cost;
m_cost = min_m_cost;
/* 1. Find some small parameters, s. t. ms >= BENCH_MIN_MS: */
while (1) {
r = measure_argon2(kdf, password, password_length, salt, salt_length,
key, key_length, t_cost, m_cost, parallel,
BENCH_SAMPLES_FAST, BENCH_MIN_MS, &ms);
if (!r) {
/* Update parameters to actual measurement */
*out_t_cost = t_cost;
*out_m_cost = m_cost;
if (progress && progress((uint32_t)ms, usrptr))
r = -EINTR;
}
if (r < 0)
goto out;
if (ms >= BENCH_MIN_MS)
break;
if (m_cost == max_m_cost) {
if (ms < BENCH_MIN_MS_FAST)
t_cost *= 16;
else {
uint32_t new = (t_cost * BENCH_MIN_MS) / (uint32_t)ms;
if (new == t_cost)
break;
t_cost = new;
}
} else {
if (ms < BENCH_MIN_MS_FAST)
m_cost *= 16;
else {
uint32_t new = (m_cost * BENCH_MIN_MS) / (uint32_t)ms;
if (new == m_cost)
break;
m_cost = new;
}
if (m_cost > max_m_cost) {
m_cost = max_m_cost;
}
}
}
/*
* 2. Use the params obtained in (1.) to estimate the target params.
* 3. Then repeatedly measure the candidate params and if they fall out of
* the acceptance range (+-5 %), try to improve the estimate:
*/
do {
if (next_argon2_params(&t_cost, &m_cost, min_t_cost, min_m_cost,
max_m_cost, ms, target_ms)) {
/* Update parameters to final computation */
*out_t_cost = t_cost;
*out_m_cost = m_cost;
break;
}
r = measure_argon2(kdf, password, password_length, salt, salt_length,
key, key_length, t_cost, m_cost, parallel,
BENCH_SAMPLES_SLOW, ms_atleast, &ms);
if (!r) {
/* Update parameters to actual measurement */
*out_t_cost = t_cost;
*out_m_cost = m_cost;
if (progress && progress((uint32_t)ms, usrptr))
r = -EINTR;
}
if (r < 0)
break;
} while (ms < ms_atleast || ms > ms_atmost);
out:
if (key) {
crypt_backend_memzero(key, key_length);
free(key);
}
return r;
}
/* This code benchmarks PBKDF and returns iterations/second using specified hash */
int crypt_pbkdf_check(const char *kdf, const char *hash,
const char *password, size_t password_size,
const char *salt, size_t salt_size,
uint64_t *iter_secs)
static int crypt_pbkdf_check(const char *kdf, const char *hash,
const char *password, size_t password_length,
const char *salt, size_t salt_length,
size_t key_length, uint32_t *iter_secs, uint32_t target_ms,
int (*progress)(uint32_t time_ms, void *usrptr), void *usrptr)
{
struct rusage rstart, rend;
int r = 0, step = 0;
long ms = 0;
char buf;
unsigned int iterations;
char *key = NULL;
uint32_t iterations;
double PBKDF2_temp;
if (!kdf || !hash)
if (!kdf || !hash || key_length <= 0)
return -EINVAL;
key = malloc(key_length);
if (!key)
return -ENOMEM;
*iter_secs = 0;
iterations = 1 << 15;
while (ms < 500) {
if (getrusage(RUSAGE_SELF, &rstart) < 0)
return -EINVAL;
while (1) {
if (getrusage(RUSAGE_SELF, &rstart) < 0) {
r = -EINVAL;
goto out;
}
r = crypt_pbkdf(kdf, hash, password, password_length, salt,
salt_length, key, key_length, iterations, 0, 0);
r = crypt_pbkdf(kdf, hash, password, password_size, salt,
salt_size, &buf, 1, iterations);
if (r < 0)
return r;
goto out;
if (getrusage(RUSAGE_SELF, &rend) < 0)
return -EINVAL;
if (getrusage(RUSAGE_SELF, &rend) < 0) {
r = -EINVAL;
goto out;
}
ms = time_ms(&rstart, &rend);
if (ms) {
PBKDF2_temp = (double)iterations * target_ms / ms;
if (PBKDF2_temp > UINT32_MAX) {
r = -EINVAL;
goto out;
}
*iter_secs = (uint32_t)PBKDF2_temp;
}
if (progress && progress((uint32_t)ms, usrptr)) {
r = -EINTR;
goto out;
}
if (ms > 500)
break;
@@ -91,11 +385,53 @@ int crypt_pbkdf_check(const char *kdf, const char *hash,
else
iterations <<= 1;
if (++step > 10 || !iterations)
return -EINVAL;
if (++step > 10 || !iterations) {
r = -EINVAL;
goto out;
}
}
out:
if (key) {
crypt_backend_memzero(key, key_length);
free(key);
}
if (iter_secs)
*iter_secs = (iterations * 1000) / ms;
return r;
}
int crypt_pbkdf_perf(const char *kdf, const char *hash,
const char *password, size_t password_size,
const char *salt, size_t salt_size,
size_t volume_key_size, uint32_t time_ms,
uint32_t max_memory_kb, uint32_t parallel_threads,
uint32_t *iterations_out, uint32_t *memory_out,
int (*progress)(uint32_t time_ms, void *usrptr), void *usrptr)
{
struct crypt_pbkdf_limits pbkdf_limits;
int r = -EINVAL;
if (!kdf || !iterations_out || !memory_out)
return -EINVAL;
/* FIXME: whole limits propagation should be more clear here */
r = crypt_pbkdf_get_limits(kdf, &pbkdf_limits);
if (r < 0)
return r;
*memory_out = 0;
*iterations_out = 0;
if (!strcmp(kdf, "pbkdf2"))
r = crypt_pbkdf_check(kdf, hash, password, password_size,
salt, salt_size, volume_key_size,
iterations_out, time_ms, progress, usrptr);
else if (!strncmp(kdf, "argon2", 6))
r = crypt_argon2_check(kdf, password, password_size,
salt, salt_size, volume_key_size,
pbkdf_limits.min_iterations,
pbkdf_limits.min_memory,
max_memory_kb,
parallel_threads, time_ms, iterations_out,
memory_out, progress, usrptr);
return r;
}

378
lib/integrity/integrity.c Normal file
View File

@@ -0,0 +1,378 @@
/*
* Integrity volume handling
*
* Copyright (C) 2016-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uuid/uuid.h>
#include "integrity.h"
#include "internal.h"
static int INTEGRITY_read_superblock(struct crypt_device *cd,
struct device *device,
uint64_t offset, struct superblock *sb)
{
int devfd, r;
devfd = device_open(cd, device, O_RDONLY);
if(devfd < 0)
return -EINVAL;
if (read_lseek_blockwise(devfd, device_block_size(cd, device),
device_alignment(device), sb, sizeof(*sb), offset) != sizeof(*sb) ||
memcmp(sb->magic, SB_MAGIC, sizeof(sb->magic)) ||
sb->version < SB_VERSION_1 || sb->version > SB_VERSION_5) {
log_std(cd, "No integrity superblock detected on %s.\n",
device_path(device));
r = -EINVAL;
} else {
sb->integrity_tag_size = le16toh(sb->integrity_tag_size);
sb->journal_sections = le32toh(sb->journal_sections);
sb->provided_data_sectors = le64toh(sb->provided_data_sectors);
sb->recalc_sector = le64toh(sb->recalc_sector);
sb->flags = le32toh(sb->flags);
r = 0;
}
return r;
}
int INTEGRITY_read_sb(struct crypt_device *cd,
struct crypt_params_integrity *params,
uint32_t *flags)
{
struct superblock sb;
int r;
r = INTEGRITY_read_superblock(cd, crypt_metadata_device(cd), 0, &sb);
if (r)
return r;
params->sector_size = SECTOR_SIZE << sb.log2_sectors_per_block;
params->tag_size = sb.integrity_tag_size;
if (flags)
*flags = sb.flags;
return 0;
}
int INTEGRITY_dump(struct crypt_device *cd, struct device *device, uint64_t offset)
{
struct superblock sb;
int r;
r = INTEGRITY_read_superblock(cd, device, offset, &sb);
if (r)
return r;
log_std(cd, "Info for integrity device %s.\n", device_path(device));
log_std(cd, "superblock_version %d\n", (unsigned)sb.version);
log_std(cd, "log2_interleave_sectors %d\n", sb.log2_interleave_sectors);
log_std(cd, "integrity_tag_size %u\n", sb.integrity_tag_size);
log_std(cd, "journal_sections %u\n", sb.journal_sections);
log_std(cd, "provided_data_sectors %" PRIu64 "\n", sb.provided_data_sectors);
log_std(cd, "sector_size %u\n", SECTOR_SIZE << sb.log2_sectors_per_block);
if (sb.version >= SB_VERSION_2 && (sb.flags & SB_FLAG_RECALCULATING))
log_std(cd, "recalc_sector %" PRIu64 "\n", sb.recalc_sector);
log_std(cd, "log2_blocks_per_bitmap %u\n", sb.log2_blocks_per_bitmap_bit);
log_std(cd, "flags %s%s%s%s%s\n",
sb.flags & SB_FLAG_HAVE_JOURNAL_MAC ? "have_journal_mac " : "",
sb.flags & SB_FLAG_RECALCULATING ? "recalculating " : "",
sb.flags & SB_FLAG_DIRTY_BITMAP ? "dirty_bitmap " : "",
sb.flags & SB_FLAG_FIXED_PADDING ? "fix_padding " : "",
sb.flags & SB_FLAG_FIXED_HMAC ? "fix_hmac " : "");
return 0;
}
int INTEGRITY_data_sectors(struct crypt_device *cd,
struct device *device, uint64_t offset,
uint64_t *data_sectors)
{
struct superblock sb;
int r;
r = INTEGRITY_read_superblock(cd, device, offset, &sb);
if (r)
return r;
*data_sectors = sb.provided_data_sectors;
return 0;
}
int INTEGRITY_key_size(struct crypt_device *cd, const char *integrity)
{
if (!integrity)
return 0;
//FIXME: use crypto backend hash size
if (!strcmp(integrity, "aead"))
return 0;
else if (!strcmp(integrity, "hmac(sha1)"))
return 20;
else if (!strcmp(integrity, "hmac(sha256)"))
return 32;
else if (!strcmp(integrity, "hmac(sha512)"))
return 64;
else if (!strcmp(integrity, "poly1305"))
return 0;
else if (!strcmp(integrity, "none"))
return 0;
return -EINVAL;
}
/* Return hash or hmac(hash) size, if known */
int INTEGRITY_hash_tag_size(const char *integrity)
{
char hash[MAX_CIPHER_LEN];
int r;
if (!integrity)
return 0;
if (!strcmp(integrity, "crc32") || !strcmp(integrity, "crc32c"))
return 4;
r = sscanf(integrity, "hmac(%" MAX_CIPHER_LEN_STR "[^)]s", hash);
if (r == 1)
r = crypt_hash_size(hash);
else
r = crypt_hash_size(integrity);
return r < 0 ? 0 : r;
}
int INTEGRITY_tag_size(struct crypt_device *cd,
const char *integrity,
const char *cipher,
const char *cipher_mode)
{
int iv_tag_size = 0, auth_tag_size = 0;
if (!cipher_mode)
iv_tag_size = 0;
else if (!strcmp(cipher_mode, "xts-random"))
iv_tag_size = 16;
else if (!strcmp(cipher_mode, "gcm-random"))
iv_tag_size = 12;
else if (!strcmp(cipher_mode, "ccm-random"))
iv_tag_size = 8;
else if (!strcmp(cipher_mode, "ctr-random"))
iv_tag_size = 16;
else if (!strcmp(cipher, "aegis256") && !strcmp(cipher_mode, "random"))
iv_tag_size = 32;
else if (!strcmp(cipher_mode, "random"))
iv_tag_size = 16;
//FIXME: use crypto backend hash size
if (!integrity || !strcmp(integrity, "none"))
auth_tag_size = 0;
else if (!strcmp(integrity, "aead"))
auth_tag_size = 16; //FIXME gcm- mode only
else if (!strcmp(integrity, "cmac(aes)"))
auth_tag_size = 16;
else if (!strcmp(integrity, "hmac(sha1)"))
auth_tag_size = 20;
else if (!strcmp(integrity, "hmac(sha256)"))
auth_tag_size = 32;
else if (!strcmp(integrity, "hmac(sha512)"))
auth_tag_size = 64;
else if (!strcmp(integrity, "poly1305")) {
if (iv_tag_size)
iv_tag_size = 12;
auth_tag_size = 16;
}
return iv_tag_size + auth_tag_size;
}
int INTEGRITY_create_dmd_device(struct crypt_device *cd,
const struct crypt_params_integrity *params,
struct volume_key *vk,
struct volume_key *journal_crypt_key,
struct volume_key *journal_mac_key,
struct crypt_dm_active_device *dmd,
uint32_t flags, uint32_t sb_flags)
{
int r;
if (!dmd)
return -EINVAL;
*dmd = (struct crypt_dm_active_device) {
.flags = flags,
};
/* Workaround for kernel dm-integrity table bug */
if (sb_flags & SB_FLAG_RECALCULATING)
dmd->flags |= CRYPT_ACTIVATE_RECALCULATE;
r = INTEGRITY_data_sectors(cd, crypt_metadata_device(cd),
crypt_get_data_offset(cd) * SECTOR_SIZE, &dmd->size);
if (r < 0)
return r;
return dm_integrity_target_set(cd, &dmd->segment, 0, dmd->size,
crypt_metadata_device(cd), crypt_data_device(cd),
crypt_get_integrity_tag_size(cd), crypt_get_data_offset(cd),
crypt_get_sector_size(cd), vk, journal_crypt_key,
journal_mac_key, params);
}
int INTEGRITY_activate_dmd_device(struct crypt_device *cd,
const char *name,
const char *type,
struct crypt_dm_active_device *dmd,
uint32_t sb_flags)
{
int r;
uint32_t dmi_flags;
struct dm_target *tgt = &dmd->segment;
if (!single_segment(dmd) || tgt->type != DM_INTEGRITY)
return -EINVAL;
log_dbg(cd, "Trying to activate INTEGRITY device on top of %s, using name %s, tag size %d, provided sectors %" PRIu64".",
device_path(tgt->data_device), name, tgt->u.integrity.tag_size, dmd->size);
r = device_block_adjust(cd, tgt->data_device, DEV_EXCL,
tgt->u.integrity.offset, NULL, &dmd->flags);
if (r)
return r;
if (tgt->u.integrity.meta_device) {
r = device_block_adjust(cd, tgt->u.integrity.meta_device, DEV_EXCL, 0, NULL, NULL);
if (r)
return r;
}
r = dm_create_device(cd, name, type, dmd);
if (r < 0 && (dm_flags(cd, DM_INTEGRITY, &dmi_flags) || !(dmi_flags & DM_INTEGRITY_SUPPORTED))) {
log_err(cd, _("Kernel does not support dm-integrity mapping."));
return -ENOTSUP;
}
if (r < 0 && (sb_flags & SB_FLAG_FIXED_PADDING) && !dm_flags(cd, DM_INTEGRITY, &dmi_flags) &&
!(dmi_flags & DM_INTEGRITY_FIX_PADDING_SUPPORTED)) {
log_err(cd, _("Kernel does not support dm-integrity fixed metadata alignment."));
return -ENOTSUP;
}
if (r < 0 && (dmd->flags & CRYPT_ACTIVATE_RECALCULATE) &&
!(crypt_get_compatibility(cd) & CRYPT_COMPAT_LEGACY_INTEGRITY_RECALC) &&
((sb_flags & SB_FLAG_FIXED_HMAC) ?
(tgt->u.integrity.vk && !tgt->u.integrity.journal_integrity_key) :
(tgt->u.integrity.vk || tgt->u.integrity.journal_integrity_key))) {
log_err(cd, _("Kernel refuses to activate insecure recalculate option (see legacy activation options to override)."));
return -ENOTSUP;
}
return r;
}
int INTEGRITY_activate(struct crypt_device *cd,
const char *name,
const struct crypt_params_integrity *params,
struct volume_key *vk,
struct volume_key *journal_crypt_key,
struct volume_key *journal_mac_key,
uint32_t flags, uint32_t sb_flags)
{
struct crypt_dm_active_device dmd = {};
int r = INTEGRITY_create_dmd_device(cd, params, vk, journal_crypt_key,
journal_mac_key, &dmd, flags, sb_flags);
if (r < 0)
return r;
r = INTEGRITY_activate_dmd_device(cd, name, CRYPT_INTEGRITY, &dmd, sb_flags);
dm_targets_free(cd, &dmd);
return r;
}
int INTEGRITY_format(struct crypt_device *cd,
const struct crypt_params_integrity *params,
struct volume_key *journal_crypt_key,
struct volume_key *journal_mac_key)
{
uint32_t dmi_flags;
char tmp_name[64], tmp_uuid[40];
struct crypt_dm_active_device dmdi = {
.size = 8,
.flags = CRYPT_ACTIVATE_PRIVATE, /* We always create journal but it can be unused later */
};
struct dm_target *tgt = &dmdi.segment;
int r;
uuid_t tmp_uuid_bin;
struct volume_key *vk = NULL;
uuid_generate(tmp_uuid_bin);
uuid_unparse(tmp_uuid_bin, tmp_uuid);
r = snprintf(tmp_name, sizeof(tmp_name), "temporary-cryptsetup-%s", tmp_uuid);
if (r < 0 || (size_t)r >= sizeof(tmp_name))
return -EINVAL;
/* There is no data area, we can actually use fake zeroed key */
if (params && params->integrity_key_size)
vk = crypt_alloc_volume_key(params->integrity_key_size, NULL);
r = dm_integrity_target_set(cd, tgt, 0, dmdi.size, crypt_metadata_device(cd),
crypt_data_device(cd), crypt_get_integrity_tag_size(cd),
crypt_get_data_offset(cd), crypt_get_sector_size(cd), vk,
journal_crypt_key, journal_mac_key, params);
if (r < 0) {
crypt_free_volume_key(vk);
return r;
}
log_dbg(cd, "Trying to format INTEGRITY device on top of %s, tmp name %s, tag size %d.",
device_path(tgt->data_device), tmp_name, tgt->u.integrity.tag_size);
r = device_block_adjust(cd, tgt->data_device, DEV_EXCL, tgt->u.integrity.offset, NULL, NULL);
if (r < 0 && (dm_flags(cd, DM_INTEGRITY, &dmi_flags) || !(dmi_flags & DM_INTEGRITY_SUPPORTED))) {
log_err(cd, _("Kernel does not support dm-integrity mapping."));
r = -ENOTSUP;
}
if (r) {
dm_targets_free(cd, &dmdi);
return r;
}
if (tgt->u.integrity.meta_device) {
r = device_block_adjust(cd, tgt->u.integrity.meta_device, DEV_EXCL, 0, NULL, NULL);
if (r) {
dm_targets_free(cd, &dmdi);
return r;
}
}
r = dm_create_device(cd, tmp_name, CRYPT_INTEGRITY, &dmdi);
crypt_free_volume_key(vk);
dm_targets_free(cd, &dmdi);
if (r)
return r;
return dm_remove_device(cd, tmp_name, CRYPT_DEACTIVATE_FORCE);
}

103
lib/integrity/integrity.h Normal file
View File

@@ -0,0 +1,103 @@
/*
* Integrity header definition
*
* Copyright (C) 2016-2021 Milan Broz
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef _CRYPTSETUP_INTEGRITY_H
#define _CRYPTSETUP_INTEGRITY_H
#include <stdint.h>
struct crypt_device;
struct device;
struct crypt_params_integrity;
struct volume_key;
struct crypt_dm_active_device;
/* dm-integrity helper */
#define SB_MAGIC "integrt"
#define SB_VERSION_1 1
#define SB_VERSION_2 2
#define SB_VERSION_3 3
#define SB_VERSION_4 4
#define SB_VERSION_5 5
#define SB_FLAG_HAVE_JOURNAL_MAC (1 << 0)
#define SB_FLAG_RECALCULATING (1 << 1) /* V2 only */
#define SB_FLAG_DIRTY_BITMAP (1 << 2) /* V3 only */
#define SB_FLAG_FIXED_PADDING (1 << 3) /* V4 only */
#define SB_FLAG_FIXED_HMAC (1 << 4) /* V5 only */
struct superblock {
uint8_t magic[8];
uint8_t version;
int8_t log2_interleave_sectors;
uint16_t integrity_tag_size;
uint32_t journal_sections;
uint64_t provided_data_sectors;
uint32_t flags;
uint8_t log2_sectors_per_block;
uint8_t log2_blocks_per_bitmap_bit; /* V3 only */
uint8_t pad[2];
uint64_t recalc_sector; /* V2 only */
} __attribute__ ((packed));
int INTEGRITY_read_sb(struct crypt_device *cd,
struct crypt_params_integrity *params,
uint32_t *flags);
int INTEGRITY_dump(struct crypt_device *cd, struct device *device, uint64_t offset);
int INTEGRITY_data_sectors(struct crypt_device *cd,
struct device *device, uint64_t offset,
uint64_t *data_sectors);
int INTEGRITY_key_size(struct crypt_device *cd,
const char *integrity);
int INTEGRITY_tag_size(struct crypt_device *cd,
const char *integrity,
const char *cipher,
const char *cipher_mode);
int INTEGRITY_hash_tag_size(const char *integrity);
int INTEGRITY_format(struct crypt_device *cd,
const struct crypt_params_integrity *params,
struct volume_key *journal_crypt_key,
struct volume_key *journal_mac_key);
int INTEGRITY_activate(struct crypt_device *cd,
const char *name,
const struct crypt_params_integrity *params,
struct volume_key *vk,
struct volume_key *journal_crypt_key,
struct volume_key *journal_mac_key,
uint32_t flags, uint32_t sb_flags);
int INTEGRITY_create_dmd_device(struct crypt_device *cd,
const struct crypt_params_integrity *params,
struct volume_key *vk,
struct volume_key *journal_crypt_key,
struct volume_key *journal_mac_key,
struct crypt_dm_active_device *dmd,
uint32_t flags, uint32_t sb_flags);
int INTEGRITY_activate_dmd_device(struct crypt_device *cd,
const char *name,
const char *type,
struct crypt_dm_active_device *dmd,
uint32_t sb_flags);
#endif

Some files were not shown because too many files have changed in this diff Show More