xref: /freebsd-src/sys/contrib/openzfs/module/os/freebsd/zfs/zio_crypt.c (revision 17aab35a77a1b1bf02fc85bb8ffadccb0ca5006d)
1eda14cbcSMatt Macy /*
2eda14cbcSMatt Macy  * CDDL HEADER START
3eda14cbcSMatt Macy  *
4eda14cbcSMatt Macy  * This file and its contents are supplied under the terms of the
5eda14cbcSMatt Macy  * Common Development and Distribution License ("CDDL"), version 1.0.
6eda14cbcSMatt Macy  * You may only use this file in accordance with the terms of version
7eda14cbcSMatt Macy  * 1.0 of the CDDL.
8eda14cbcSMatt Macy  *
9eda14cbcSMatt Macy  * A full copy of the text of the CDDL should have accompanied this
10eda14cbcSMatt Macy  * source.  A copy of the CDDL is also available via the Internet at
11eda14cbcSMatt Macy  * http://www.illumos.org/license/CDDL.
12eda14cbcSMatt Macy  *
13eda14cbcSMatt Macy  * CDDL HEADER END
14eda14cbcSMatt Macy  */
15eda14cbcSMatt Macy 
16eda14cbcSMatt Macy /*
17eda14cbcSMatt Macy  * Copyright (c) 2017, Datto, Inc. All rights reserved.
18eda14cbcSMatt Macy  */
19eda14cbcSMatt Macy 
20eda14cbcSMatt Macy #include <sys/zio_crypt.h>
21eda14cbcSMatt Macy #include <sys/dmu.h>
22eda14cbcSMatt Macy #include <sys/dmu_objset.h>
23eda14cbcSMatt Macy #include <sys/dnode.h>
24eda14cbcSMatt Macy #include <sys/fs/zfs.h>
25eda14cbcSMatt Macy #include <sys/zio.h>
26eda14cbcSMatt Macy #include <sys/zil.h>
27eda14cbcSMatt Macy #include <sys/sha2.h>
28eda14cbcSMatt Macy #include <sys/hkdf.h>
29eda14cbcSMatt Macy 
30eda14cbcSMatt Macy /*
31eda14cbcSMatt Macy  * This file is responsible for handling all of the details of generating
32eda14cbcSMatt Macy  * encryption parameters and performing encryption and authentication.
33eda14cbcSMatt Macy  *
34eda14cbcSMatt Macy  * BLOCK ENCRYPTION PARAMETERS:
35eda14cbcSMatt Macy  * Encryption /Authentication Algorithm Suite (crypt):
36eda14cbcSMatt Macy  * The encryption algorithm, mode, and key length we are going to use. We
37eda14cbcSMatt Macy  * currently support AES in either GCM or CCM modes with 128, 192, and 256 bit
38eda14cbcSMatt Macy  * keys. All authentication is currently done with SHA512-HMAC.
39eda14cbcSMatt Macy  *
40eda14cbcSMatt Macy  * Plaintext:
41eda14cbcSMatt Macy  * The unencrypted data that we want to encrypt.
42eda14cbcSMatt Macy  *
43eda14cbcSMatt Macy  * Initialization Vector (IV):
44eda14cbcSMatt Macy  * An initialization vector for the encryption algorithms. This is used to
45eda14cbcSMatt Macy  * "tweak" the encryption algorithms so that two blocks of the same data are
46eda14cbcSMatt Macy  * encrypted into different ciphertext outputs, thus obfuscating block patterns.
47eda14cbcSMatt Macy  * The supported encryption modes (AES-GCM and AES-CCM) require that an IV is
48eda14cbcSMatt Macy  * never reused with the same encryption key. This value is stored unencrypted
49eda14cbcSMatt Macy  * and must simply be provided to the decryption function. We use a 96 bit IV
50eda14cbcSMatt Macy  * (as recommended by NIST) for all block encryption. For non-dedup blocks we
51eda14cbcSMatt Macy  * derive the IV randomly. The first 64 bits of the IV are stored in the second
52eda14cbcSMatt Macy  * word of DVA[2] and the remaining 32 bits are stored in the upper 32 bits of
53eda14cbcSMatt Macy  * blk_fill. This is safe because encrypted blocks can't use the upper 32 bits
54eda14cbcSMatt Macy  * of blk_fill. We only encrypt level 0 blocks, which normally have a fill count
55eda14cbcSMatt Macy  * of 1. The only exception is for DMU_OT_DNODE objects, where the fill count of
56eda14cbcSMatt Macy  * level 0 blocks is the number of allocated dnodes in that block. The on-disk
57eda14cbcSMatt Macy  * format supports at most 2^15 slots per L0 dnode block, because the maximum
58eda14cbcSMatt Macy  * block size is 16MB (2^24). In either case, for level 0 blocks this number
59eda14cbcSMatt Macy  * will still be smaller than UINT32_MAX so it is safe to store the IV in the
60eda14cbcSMatt Macy  * top 32 bits of blk_fill, while leaving the bottom 32 bits of the fill count
61eda14cbcSMatt Macy  * for the dnode code.
62eda14cbcSMatt Macy  *
63eda14cbcSMatt Macy  * Master key:
64eda14cbcSMatt Macy  * This is the most important secret data of an encrypted dataset. It is used
65eda14cbcSMatt Macy  * along with the salt to generate that actual encryption keys via HKDF. We
66eda14cbcSMatt Macy  * do not use the master key to directly encrypt any data because there are
67eda14cbcSMatt Macy  * theoretical limits on how much data can actually be safely encrypted with
68eda14cbcSMatt Macy  * any encryption mode. The master key is stored encrypted on disk with the
69eda14cbcSMatt Macy  * user's wrapping key. Its length is determined by the encryption algorithm.
70eda14cbcSMatt Macy  * For details on how this is stored see the block comment in dsl_crypt.c
71eda14cbcSMatt Macy  *
72eda14cbcSMatt Macy  * Salt:
73eda14cbcSMatt Macy  * Used as an input to the HKDF function, along with the master key. We use a
74eda14cbcSMatt Macy  * 64 bit salt, stored unencrypted in the first word of DVA[2]. Any given salt
75eda14cbcSMatt Macy  * can be used for encrypting many blocks, so we cache the current salt and the
76eda14cbcSMatt Macy  * associated derived key in zio_crypt_t so we do not need to derive it again
77eda14cbcSMatt Macy  * needlessly.
78eda14cbcSMatt Macy  *
79eda14cbcSMatt Macy  * Encryption Key:
80eda14cbcSMatt Macy  * A secret binary key, generated from an HKDF function used to encrypt and
81eda14cbcSMatt Macy  * decrypt data.
82eda14cbcSMatt Macy  *
83eda14cbcSMatt Macy  * Message Authentication Code (MAC)
84eda14cbcSMatt Macy  * The MAC is an output of authenticated encryption modes such as AES-GCM and
85eda14cbcSMatt Macy  * AES-CCM. Its purpose is to ensure that an attacker cannot modify encrypted
86eda14cbcSMatt Macy  * data on disk and return garbage to the application. Effectively, it is a
87eda14cbcSMatt Macy  * checksum that can not be reproduced by an attacker. We store the MAC in the
88eda14cbcSMatt Macy  * second 128 bits of blk_cksum, leaving the first 128 bits for a truncated
89eda14cbcSMatt Macy  * regular checksum of the ciphertext which can be used for scrubbing.
90eda14cbcSMatt Macy  *
91eda14cbcSMatt Macy  * OBJECT AUTHENTICATION:
92eda14cbcSMatt Macy  * Some object types, such as DMU_OT_MASTER_NODE cannot be encrypted because
93eda14cbcSMatt Macy  * they contain some info that always needs to be readable. To prevent this
94eda14cbcSMatt Macy  * data from being altered, we authenticate this data using SHA512-HMAC. This
95eda14cbcSMatt Macy  * will produce a MAC (similar to the one produced via encryption) which can
96eda14cbcSMatt Macy  * be used to verify the object was not modified. HMACs do not require key
97eda14cbcSMatt Macy  * rotation or IVs, so we can keep up to the full 3 copies of authenticated
98eda14cbcSMatt Macy  * data.
99eda14cbcSMatt Macy  *
100eda14cbcSMatt Macy  * ZIL ENCRYPTION:
101eda14cbcSMatt Macy  * ZIL blocks have their bp written to disk ahead of the associated data, so we
102eda14cbcSMatt Macy  * cannot store the MAC there as we normally do. For these blocks the MAC is
103eda14cbcSMatt Macy  * stored in the embedded checksum within the zil_chain_t header. The salt and
104eda14cbcSMatt Macy  * IV are generated for the block on bp allocation instead of at encryption
105eda14cbcSMatt Macy  * time. In addition, ZIL blocks have some pieces that must be left in plaintext
106eda14cbcSMatt Macy  * for claiming even though all of the sensitive user data still needs to be
107eda14cbcSMatt Macy  * encrypted. The function zio_crypt_init_uios_zil() handles parsing which
108eda14cbcSMatt Macy  * pieces of the block need to be encrypted. All data that is not encrypted is
109eda14cbcSMatt Macy  * authenticated using the AAD mechanisms that the supported encryption modes
110eda14cbcSMatt Macy  * provide for. In order to preserve the semantics of the ZIL for encrypted
111eda14cbcSMatt Macy  * datasets, the ZIL is not protected at the objset level as described below.
112eda14cbcSMatt Macy  *
113eda14cbcSMatt Macy  * DNODE ENCRYPTION:
114eda14cbcSMatt Macy  * Similarly to ZIL blocks, the core part of each dnode_phys_t needs to be left
115eda14cbcSMatt Macy  * in plaintext for scrubbing and claiming, but the bonus buffers might contain
116eda14cbcSMatt Macy  * sensitive user data. The function zio_crypt_init_uios_dnode() handles parsing
11716038816SMartin Matuska  * which pieces of the block need to be encrypted. For more details about
118eda14cbcSMatt Macy  * dnode authentication and encryption, see zio_crypt_init_uios_dnode().
119eda14cbcSMatt Macy  *
120eda14cbcSMatt Macy  * OBJECT SET AUTHENTICATION:
121eda14cbcSMatt Macy  * Up to this point, everything we have encrypted and authenticated has been
122eda14cbcSMatt Macy  * at level 0 (or -2 for the ZIL). If we did not do any further work the
123eda14cbcSMatt Macy  * on-disk format would be susceptible to attacks that deleted or rearranged
124eda14cbcSMatt Macy  * the order of level 0 blocks. Ideally, the cleanest solution would be to
125eda14cbcSMatt Macy  * maintain a tree of authentication MACs going up the bp tree. However, this
126eda14cbcSMatt Macy  * presents a problem for raw sends. Send files do not send information about
127eda14cbcSMatt Macy  * indirect blocks so there would be no convenient way to transfer the MACs and
128eda14cbcSMatt Macy  * they cannot be recalculated on the receive side without the master key which
129eda14cbcSMatt Macy  * would defeat one of the purposes of raw sends in the first place. Instead,
130eda14cbcSMatt Macy  * for the indirect levels of the bp tree, we use a regular SHA512 of the MACs
131eda14cbcSMatt Macy  * from the level below. We also include some portable fields from blk_prop such
132eda14cbcSMatt Macy  * as the lsize and compression algorithm to prevent the data from being
133eda14cbcSMatt Macy  * misinterpreted.
134eda14cbcSMatt Macy  *
135eda14cbcSMatt Macy  * At the objset level, we maintain 2 separate 256 bit MACs in the
136eda14cbcSMatt Macy  * objset_phys_t. The first one is "portable" and is the logical root of the
137eda14cbcSMatt Macy  * MAC tree maintained in the metadnode's bps. The second, is "local" and is
138eda14cbcSMatt Macy  * used as the root MAC for the user accounting objects, which are also not
139eda14cbcSMatt Macy  * transferred via "zfs send". The portable MAC is sent in the DRR_BEGIN payload
140eda14cbcSMatt Macy  * of the send file. The useraccounting code ensures that the useraccounting
141eda14cbcSMatt Macy  * info is not present upon a receive, so the local MAC can simply be cleared
142eda14cbcSMatt Macy  * out at that time. For more info about objset_phys_t authentication, see
143eda14cbcSMatt Macy  * zio_crypt_do_objset_hmacs().
144eda14cbcSMatt Macy  *
145eda14cbcSMatt Macy  * CONSIDERATIONS FOR DEDUP:
146eda14cbcSMatt Macy  * In order for dedup to work, blocks that we want to dedup with one another
147eda14cbcSMatt Macy  * need to use the same IV and encryption key, so that they will have the same
148eda14cbcSMatt Macy  * ciphertext. Normally, one should never reuse an IV with the same encryption
149eda14cbcSMatt Macy  * key or else AES-GCM and AES-CCM can both actually leak the plaintext of both
150eda14cbcSMatt Macy  * blocks. In this case, however, since we are using the same plaintext as
151eda14cbcSMatt Macy  * well all that we end up with is a duplicate of the original ciphertext we
152eda14cbcSMatt Macy  * already had. As a result, an attacker with read access to the raw disk will
153eda14cbcSMatt Macy  * be able to tell which blocks are the same but this information is given away
154eda14cbcSMatt Macy  * by dedup anyway. In order to get the same IVs and encryption keys for
155eda14cbcSMatt Macy  * equivalent blocks of data we use an HMAC of the plaintext. We use an HMAC
156eda14cbcSMatt Macy  * here so that a reproducible checksum of the plaintext is never available to
157eda14cbcSMatt Macy  * the attacker. The HMAC key is kept alongside the master key, encrypted on
158eda14cbcSMatt Macy  * disk. The first 64 bits of the HMAC are used in place of the random salt, and
159eda14cbcSMatt Macy  * the next 96 bits are used as the IV. As a result of this mechanism, dedup
160eda14cbcSMatt Macy  * will only work within a clone family since encrypted dedup requires use of
161eda14cbcSMatt Macy  * the same master and HMAC keys.
162eda14cbcSMatt Macy  */
163eda14cbcSMatt Macy 
164eda14cbcSMatt Macy /*
165eda14cbcSMatt Macy  * After encrypting many blocks with the same key we may start to run up
166eda14cbcSMatt Macy  * against the theoretical limits of how much data can securely be encrypted
167eda14cbcSMatt Macy  * with a single key using the supported encryption modes. The most obvious
168eda14cbcSMatt Macy  * limitation is that our risk of generating 2 equivalent 96 bit IVs increases
169eda14cbcSMatt Macy  * the more IVs we generate (which both GCM and CCM modes strictly forbid).
170eda14cbcSMatt Macy  * This risk actually grows surprisingly quickly over time according to the
171eda14cbcSMatt Macy  * Birthday Problem. With a total IV space of 2^(96 bits), and assuming we have
172eda14cbcSMatt Macy  * generated n IVs with a cryptographically secure RNG, the approximate
173eda14cbcSMatt Macy  * probability p(n) of a collision is given as:
174eda14cbcSMatt Macy  *
175eda14cbcSMatt Macy  * p(n) ~= e^(-n*(n-1)/(2*(2^96)))
176eda14cbcSMatt Macy  *
177eda14cbcSMatt Macy  * [http://www.math.cornell.edu/~mec/2008-2009/TianyiZheng/Birthday.html]
178eda14cbcSMatt Macy  *
179eda14cbcSMatt Macy  * Assuming that we want to ensure that p(n) never goes over 1 / 1 trillion
180eda14cbcSMatt Macy  * we must not write more than 398,065,730 blocks with the same encryption key.
181eda14cbcSMatt Macy  * Therefore, we rotate our keys after 400,000,000 blocks have been written by
182eda14cbcSMatt Macy  * generating a new random 64 bit salt for our HKDF encryption key generation
183eda14cbcSMatt Macy  * function.
184eda14cbcSMatt Macy  */
185eda14cbcSMatt Macy #define	ZFS_KEY_MAX_SALT_USES_DEFAULT	400000000
186eda14cbcSMatt Macy #define	ZFS_CURRENT_MAX_SALT_USES	\
187eda14cbcSMatt Macy 	(MIN(zfs_key_max_salt_uses, ZFS_KEY_MAX_SALT_USES_DEFAULT))
188e92ffd9bSMartin Matuska static unsigned long zfs_key_max_salt_uses = ZFS_KEY_MAX_SALT_USES_DEFAULT;
189eda14cbcSMatt Macy 
190eda14cbcSMatt Macy typedef struct blkptr_auth_buf {
191eda14cbcSMatt Macy 	uint64_t bab_prop;			/* blk_prop - portable mask */
192eda14cbcSMatt Macy 	uint8_t bab_mac[ZIO_DATA_MAC_LEN];	/* MAC from blk_cksum */
193eda14cbcSMatt Macy 	uint64_t bab_pad;			/* reserved for future use */
194eda14cbcSMatt Macy } blkptr_auth_buf_t;
195eda14cbcSMatt Macy 
196e92ffd9bSMartin Matuska const zio_crypt_info_t zio_crypt_table[ZIO_CRYPT_FUNCTIONS] = {
197eda14cbcSMatt Macy 	{"",			ZC_TYPE_NONE,	0,	"inherit"},
198eda14cbcSMatt Macy 	{"",			ZC_TYPE_NONE,	0,	"on"},
199eda14cbcSMatt Macy 	{"",			ZC_TYPE_NONE,	0,	"off"},
200eda14cbcSMatt Macy 	{SUN_CKM_AES_CCM,	ZC_TYPE_CCM,	16,	"aes-128-ccm"},
201eda14cbcSMatt Macy 	{SUN_CKM_AES_CCM,	ZC_TYPE_CCM,	24,	"aes-192-ccm"},
202eda14cbcSMatt Macy 	{SUN_CKM_AES_CCM,	ZC_TYPE_CCM,	32,	"aes-256-ccm"},
203eda14cbcSMatt Macy 	{SUN_CKM_AES_GCM,	ZC_TYPE_GCM,	16,	"aes-128-gcm"},
204eda14cbcSMatt Macy 	{SUN_CKM_AES_GCM,	ZC_TYPE_GCM,	24,	"aes-192-gcm"},
205eda14cbcSMatt Macy 	{SUN_CKM_AES_GCM,	ZC_TYPE_GCM,	32,	"aes-256-gcm"}
206eda14cbcSMatt Macy };
207eda14cbcSMatt Macy 
208eda14cbcSMatt Macy static void
209eda14cbcSMatt Macy zio_crypt_key_destroy_early(zio_crypt_key_t *key)
210eda14cbcSMatt Macy {
211eda14cbcSMatt Macy 	rw_destroy(&key->zk_salt_lock);
212eda14cbcSMatt Macy 
213eda14cbcSMatt Macy 	/* free crypto templates */
214da5137abSMartin Matuska 	memset(&key->zk_session, 0, sizeof (key->zk_session));
215eda14cbcSMatt Macy 
216eda14cbcSMatt Macy 	/* zero out sensitive data */
217da5137abSMartin Matuska 	memset(key, 0, sizeof (zio_crypt_key_t));
218eda14cbcSMatt Macy }
219eda14cbcSMatt Macy 
220eda14cbcSMatt Macy void
221eda14cbcSMatt Macy zio_crypt_key_destroy(zio_crypt_key_t *key)
222eda14cbcSMatt Macy {
223eda14cbcSMatt Macy 
224eda14cbcSMatt Macy 	freebsd_crypt_freesession(&key->zk_session);
225eda14cbcSMatt Macy 	zio_crypt_key_destroy_early(key);
226eda14cbcSMatt Macy }
227eda14cbcSMatt Macy 
228eda14cbcSMatt Macy int
229eda14cbcSMatt Macy zio_crypt_key_init(uint64_t crypt, zio_crypt_key_t *key)
230eda14cbcSMatt Macy {
231eda14cbcSMatt Macy 	int ret;
232eda14cbcSMatt Macy 	crypto_mechanism_t mech __unused;
233eda14cbcSMatt Macy 	uint_t keydata_len;
234e92ffd9bSMartin Matuska 	const zio_crypt_info_t *ci = NULL;
235eda14cbcSMatt Macy 
23616038816SMartin Matuska 	ASSERT3P(key, !=, NULL);
237eda14cbcSMatt Macy 	ASSERT3U(crypt, <, ZIO_CRYPT_FUNCTIONS);
238eda14cbcSMatt Macy 
239eda14cbcSMatt Macy 	ci = &zio_crypt_table[crypt];
240eda14cbcSMatt Macy 	if (ci->ci_crypt_type != ZC_TYPE_GCM &&
241eda14cbcSMatt Macy 	    ci->ci_crypt_type != ZC_TYPE_CCM)
242eda14cbcSMatt Macy 		return (ENOTSUP);
243eda14cbcSMatt Macy 
244eda14cbcSMatt Macy 	keydata_len = zio_crypt_table[crypt].ci_keylen;
245da5137abSMartin Matuska 	memset(key, 0, sizeof (zio_crypt_key_t));
246eda14cbcSMatt Macy 	rw_init(&key->zk_salt_lock, NULL, RW_DEFAULT, NULL);
247eda14cbcSMatt Macy 
248eda14cbcSMatt Macy 	/* fill keydata buffers and salt with random data */
249eda14cbcSMatt Macy 	ret = random_get_bytes((uint8_t *)&key->zk_guid, sizeof (uint64_t));
250eda14cbcSMatt Macy 	if (ret != 0)
251eda14cbcSMatt Macy 		goto error;
252eda14cbcSMatt Macy 
253eda14cbcSMatt Macy 	ret = random_get_bytes(key->zk_master_keydata, keydata_len);
254eda14cbcSMatt Macy 	if (ret != 0)
255eda14cbcSMatt Macy 		goto error;
256eda14cbcSMatt Macy 
257eda14cbcSMatt Macy 	ret = random_get_bytes(key->zk_hmac_keydata, SHA512_HMAC_KEYLEN);
258eda14cbcSMatt Macy 	if (ret != 0)
259eda14cbcSMatt Macy 		goto error;
260eda14cbcSMatt Macy 
261eda14cbcSMatt Macy 	ret = random_get_bytes(key->zk_salt, ZIO_DATA_SALT_LEN);
262eda14cbcSMatt Macy 	if (ret != 0)
263eda14cbcSMatt Macy 		goto error;
264eda14cbcSMatt Macy 
265eda14cbcSMatt Macy 	/* derive the current key from the master key */
266eda14cbcSMatt Macy 	ret = hkdf_sha512(key->zk_master_keydata, keydata_len, NULL, 0,
267eda14cbcSMatt Macy 	    key->zk_salt, ZIO_DATA_SALT_LEN, key->zk_current_keydata,
268eda14cbcSMatt Macy 	    keydata_len);
269eda14cbcSMatt Macy 	if (ret != 0)
270eda14cbcSMatt Macy 		goto error;
271eda14cbcSMatt Macy 
272eda14cbcSMatt Macy 	/* initialize keys for the ICP */
273eda14cbcSMatt Macy 	key->zk_current_key.ck_data = key->zk_current_keydata;
274eda14cbcSMatt Macy 	key->zk_current_key.ck_length = CRYPTO_BYTES2BITS(keydata_len);
275eda14cbcSMatt Macy 
276eda14cbcSMatt Macy 	key->zk_hmac_key.ck_data = &key->zk_hmac_key;
277eda14cbcSMatt Macy 	key->zk_hmac_key.ck_length = CRYPTO_BYTES2BITS(SHA512_HMAC_KEYLEN);
278eda14cbcSMatt Macy 
279eda14cbcSMatt Macy 	ci = &zio_crypt_table[crypt];
280eda14cbcSMatt Macy 	if (ci->ci_crypt_type != ZC_TYPE_GCM &&
281eda14cbcSMatt Macy 	    ci->ci_crypt_type != ZC_TYPE_CCM)
282eda14cbcSMatt Macy 		return (ENOTSUP);
283eda14cbcSMatt Macy 
284eda14cbcSMatt Macy 	ret = freebsd_crypt_newsession(&key->zk_session, ci,
285eda14cbcSMatt Macy 	    &key->zk_current_key);
286eda14cbcSMatt Macy 	if (ret)
287eda14cbcSMatt Macy 		goto error;
288eda14cbcSMatt Macy 
289eda14cbcSMatt Macy 	key->zk_crypt = crypt;
290eda14cbcSMatt Macy 	key->zk_version = ZIO_CRYPT_KEY_CURRENT_VERSION;
291eda14cbcSMatt Macy 	key->zk_salt_count = 0;
292eda14cbcSMatt Macy 
293eda14cbcSMatt Macy 	return (0);
294eda14cbcSMatt Macy 
295eda14cbcSMatt Macy error:
296eda14cbcSMatt Macy 	zio_crypt_key_destroy_early(key);
297eda14cbcSMatt Macy 	return (ret);
298eda14cbcSMatt Macy }
299eda14cbcSMatt Macy 
300eda14cbcSMatt Macy static int
301eda14cbcSMatt Macy zio_crypt_key_change_salt(zio_crypt_key_t *key)
302eda14cbcSMatt Macy {
303eda14cbcSMatt Macy 	int ret = 0;
304eda14cbcSMatt Macy 	uint8_t salt[ZIO_DATA_SALT_LEN];
305eda14cbcSMatt Macy 	crypto_mechanism_t mech __unused;
306eda14cbcSMatt Macy 
307eda14cbcSMatt Macy 	uint_t keydata_len = zio_crypt_table[key->zk_crypt].ci_keylen;
308eda14cbcSMatt Macy 
309eda14cbcSMatt Macy 	/* generate a new salt */
310eda14cbcSMatt Macy 	ret = random_get_bytes(salt, ZIO_DATA_SALT_LEN);
311eda14cbcSMatt Macy 	if (ret != 0)
312eda14cbcSMatt Macy 		goto error;
313eda14cbcSMatt Macy 
314eda14cbcSMatt Macy 	rw_enter(&key->zk_salt_lock, RW_WRITER);
315eda14cbcSMatt Macy 
316eda14cbcSMatt Macy 	/* someone beat us to the salt rotation, just unlock and return */
317eda14cbcSMatt Macy 	if (key->zk_salt_count < ZFS_CURRENT_MAX_SALT_USES)
318eda14cbcSMatt Macy 		goto out_unlock;
319eda14cbcSMatt Macy 
320eda14cbcSMatt Macy 	/* derive the current key from the master key and the new salt */
321eda14cbcSMatt Macy 	ret = hkdf_sha512(key->zk_master_keydata, keydata_len, NULL, 0,
322eda14cbcSMatt Macy 	    salt, ZIO_DATA_SALT_LEN, key->zk_current_keydata, keydata_len);
323eda14cbcSMatt Macy 	if (ret != 0)
324eda14cbcSMatt Macy 		goto out_unlock;
325eda14cbcSMatt Macy 
326eda14cbcSMatt Macy 	/* assign the salt and reset the usage count */
327da5137abSMartin Matuska 	memcpy(key->zk_salt, salt, ZIO_DATA_SALT_LEN);
328eda14cbcSMatt Macy 	key->zk_salt_count = 0;
329eda14cbcSMatt Macy 
330eda14cbcSMatt Macy 	freebsd_crypt_freesession(&key->zk_session);
331eda14cbcSMatt Macy 	ret = freebsd_crypt_newsession(&key->zk_session,
332eda14cbcSMatt Macy 	    &zio_crypt_table[key->zk_crypt], &key->zk_current_key);
333eda14cbcSMatt Macy 	if (ret != 0)
334eda14cbcSMatt Macy 		goto out_unlock;
335eda14cbcSMatt Macy 
336eda14cbcSMatt Macy 	rw_exit(&key->zk_salt_lock);
337eda14cbcSMatt Macy 
338eda14cbcSMatt Macy 	return (0);
339eda14cbcSMatt Macy 
340eda14cbcSMatt Macy out_unlock:
341eda14cbcSMatt Macy 	rw_exit(&key->zk_salt_lock);
342eda14cbcSMatt Macy error:
343eda14cbcSMatt Macy 	return (ret);
344eda14cbcSMatt Macy }
345eda14cbcSMatt Macy 
346eda14cbcSMatt Macy /* See comment above zfs_key_max_salt_uses definition for details */
347eda14cbcSMatt Macy int
348eda14cbcSMatt Macy zio_crypt_key_get_salt(zio_crypt_key_t *key, uint8_t *salt)
349eda14cbcSMatt Macy {
350eda14cbcSMatt Macy 	int ret;
351eda14cbcSMatt Macy 	boolean_t salt_change;
352eda14cbcSMatt Macy 
353eda14cbcSMatt Macy 	rw_enter(&key->zk_salt_lock, RW_READER);
354eda14cbcSMatt Macy 
355da5137abSMartin Matuska 	memcpy(salt, key->zk_salt, ZIO_DATA_SALT_LEN);
356eda14cbcSMatt Macy 	salt_change = (atomic_inc_64_nv(&key->zk_salt_count) >=
357eda14cbcSMatt Macy 	    ZFS_CURRENT_MAX_SALT_USES);
358eda14cbcSMatt Macy 
359eda14cbcSMatt Macy 	rw_exit(&key->zk_salt_lock);
360eda14cbcSMatt Macy 
361eda14cbcSMatt Macy 	if (salt_change) {
362eda14cbcSMatt Macy 		ret = zio_crypt_key_change_salt(key);
363eda14cbcSMatt Macy 		if (ret != 0)
364eda14cbcSMatt Macy 			goto error;
365eda14cbcSMatt Macy 	}
366eda14cbcSMatt Macy 
367eda14cbcSMatt Macy 	return (0);
368eda14cbcSMatt Macy 
369eda14cbcSMatt Macy error:
370eda14cbcSMatt Macy 	return (ret);
371eda14cbcSMatt Macy }
372eda14cbcSMatt Macy 
373eda14cbcSMatt Macy void *failed_decrypt_buf;
374eda14cbcSMatt Macy int failed_decrypt_size;
375eda14cbcSMatt Macy 
376eda14cbcSMatt Macy /*
377eda14cbcSMatt Macy  * This function handles all encryption and decryption in zfs. When
378eda14cbcSMatt Macy  * encrypting it expects puio to reference the plaintext and cuio to
379eda14cbcSMatt Macy  * reference the ciphertext. cuio must have enough space for the
380eda14cbcSMatt Macy  * ciphertext + room for a MAC. datalen should be the length of the
381eda14cbcSMatt Macy  * plaintext / ciphertext alone.
382eda14cbcSMatt Macy  */
383eda14cbcSMatt Macy /*
384eda14cbcSMatt Macy  * The implementation for FreeBSD's OpenCrypto.
385eda14cbcSMatt Macy  *
386eda14cbcSMatt Macy  * The big difference between ICP and FOC is that FOC uses a single
387eda14cbcSMatt Macy  * buffer for input and output.  This means that (for AES-GCM, the
388eda14cbcSMatt Macy  * only one supported right now) the source must be copied into the
389eda14cbcSMatt Macy  * destination, and the destination must have the AAD, and the tag/MAC,
390eda14cbcSMatt Macy  * already associated with it.  (Both implementations can use a uio.)
391eda14cbcSMatt Macy  *
392eda14cbcSMatt Macy  * Since the auth data is part of the iovec array, all we need to know
393eda14cbcSMatt Macy  * is the length:  0 means there's no AAD.
394eda14cbcSMatt Macy  *
395eda14cbcSMatt Macy  */
396eda14cbcSMatt Macy static int
397eda14cbcSMatt Macy zio_do_crypt_uio_opencrypto(boolean_t encrypt, freebsd_crypt_session_t *sess,
398eda14cbcSMatt Macy     uint64_t crypt, crypto_key_t *key, uint8_t *ivbuf, uint_t datalen,
399184c1b94SMartin Matuska     zfs_uio_t *uio, uint_t auth_len)
400eda14cbcSMatt Macy {
401e92ffd9bSMartin Matuska 	const zio_crypt_info_t *ci = &zio_crypt_table[crypt];
402eda14cbcSMatt Macy 	if (ci->ci_crypt_type != ZC_TYPE_GCM &&
403eda14cbcSMatt Macy 	    ci->ci_crypt_type != ZC_TYPE_CCM)
404eda14cbcSMatt Macy 		return (ENOTSUP);
405eda14cbcSMatt Macy 
406eda14cbcSMatt Macy 
407e92ffd9bSMartin Matuska 	int ret = freebsd_crypt_uio(encrypt, sess, ci, uio, key, ivbuf,
408eda14cbcSMatt Macy 	    datalen, auth_len);
409eda14cbcSMatt Macy 	if (ret != 0) {
410eda14cbcSMatt Macy #ifdef FCRYPTO_DEBUG
411eda14cbcSMatt Macy 		printf("%s(%d):  Returning error %s\n",
412eda14cbcSMatt Macy 		    __FUNCTION__, __LINE__, encrypt ? "EIO" : "ECKSUM");
413eda14cbcSMatt Macy #endif
414eda14cbcSMatt Macy 		ret = SET_ERROR(encrypt ? EIO : ECKSUM);
415eda14cbcSMatt Macy 	}
416eda14cbcSMatt Macy 
417eda14cbcSMatt Macy 	return (ret);
418eda14cbcSMatt Macy }
419eda14cbcSMatt Macy 
420eda14cbcSMatt Macy int
421eda14cbcSMatt Macy zio_crypt_key_wrap(crypto_key_t *cwkey, zio_crypt_key_t *key, uint8_t *iv,
422eda14cbcSMatt Macy     uint8_t *mac, uint8_t *keydata_out, uint8_t *hmac_keydata_out)
423eda14cbcSMatt Macy {
424eda14cbcSMatt Macy 	int ret;
425eda14cbcSMatt Macy 	uint64_t aad[3];
426eda14cbcSMatt Macy 	/*
427eda14cbcSMatt Macy 	 * With OpenCrypto in FreeBSD, the same buffer is used for
428eda14cbcSMatt Macy 	 * input and output.  Also, the AAD (for AES-GMC at least)
429eda14cbcSMatt Macy 	 * needs to logically go in front.
430eda14cbcSMatt Macy 	 */
431184c1b94SMartin Matuska 	zfs_uio_t cuio;
432184c1b94SMartin Matuska 	struct uio cuio_s;
433eda14cbcSMatt Macy 	iovec_t iovecs[4];
434eda14cbcSMatt Macy 	uint64_t crypt = key->zk_crypt;
435eda14cbcSMatt Macy 	uint_t enc_len, keydata_len, aad_len;
436eda14cbcSMatt Macy 
437eda14cbcSMatt Macy 	ASSERT3U(crypt, <, ZIO_CRYPT_FUNCTIONS);
438eda14cbcSMatt Macy 
439184c1b94SMartin Matuska 	zfs_uio_init(&cuio, &cuio_s);
440184c1b94SMartin Matuska 
441eda14cbcSMatt Macy 	keydata_len = zio_crypt_table[crypt].ci_keylen;
442eda14cbcSMatt Macy 
443eda14cbcSMatt Macy 	/* generate iv for wrapping the master and hmac key */
444eda14cbcSMatt Macy 	ret = random_get_pseudo_bytes(iv, WRAPPING_IV_LEN);
445eda14cbcSMatt Macy 	if (ret != 0)
446eda14cbcSMatt Macy 		goto error;
447eda14cbcSMatt Macy 
448eda14cbcSMatt Macy 	/*
449eda14cbcSMatt Macy 	 * Since we only support one buffer, we need to copy
450eda14cbcSMatt Macy 	 * the plain text (source) to the cipher buffer (dest).
451eda14cbcSMatt Macy 	 * We set iovecs[0] -- the authentication data -- below.
452eda14cbcSMatt Macy 	 */
453da5137abSMartin Matuska 	memcpy(keydata_out, key->zk_master_keydata, keydata_len);
454da5137abSMartin Matuska 	memcpy(hmac_keydata_out, key->zk_hmac_keydata, SHA512_HMAC_KEYLEN);
455eda14cbcSMatt Macy 	iovecs[1].iov_base = keydata_out;
456eda14cbcSMatt Macy 	iovecs[1].iov_len = keydata_len;
457eda14cbcSMatt Macy 	iovecs[2].iov_base = hmac_keydata_out;
458eda14cbcSMatt Macy 	iovecs[2].iov_len = SHA512_HMAC_KEYLEN;
459eda14cbcSMatt Macy 	iovecs[3].iov_base = mac;
460eda14cbcSMatt Macy 	iovecs[3].iov_len = WRAPPING_MAC_LEN;
461eda14cbcSMatt Macy 
462eda14cbcSMatt Macy 	/*
463eda14cbcSMatt Macy 	 * Although we don't support writing to the old format, we do
464eda14cbcSMatt Macy 	 * support rewrapping the key so that the user can move and
465eda14cbcSMatt Macy 	 * quarantine datasets on the old format.
466eda14cbcSMatt Macy 	 */
467eda14cbcSMatt Macy 	if (key->zk_version == 0) {
468eda14cbcSMatt Macy 		aad_len = sizeof (uint64_t);
469eda14cbcSMatt Macy 		aad[0] = LE_64(key->zk_guid);
470eda14cbcSMatt Macy 	} else {
471eda14cbcSMatt Macy 		ASSERT3U(key->zk_version, ==, ZIO_CRYPT_KEY_CURRENT_VERSION);
472eda14cbcSMatt Macy 		aad_len = sizeof (uint64_t) * 3;
473eda14cbcSMatt Macy 		aad[0] = LE_64(key->zk_guid);
474eda14cbcSMatt Macy 		aad[1] = LE_64(crypt);
475eda14cbcSMatt Macy 		aad[2] = LE_64(key->zk_version);
476eda14cbcSMatt Macy 	}
477eda14cbcSMatt Macy 
478eda14cbcSMatt Macy 	iovecs[0].iov_base = aad;
479eda14cbcSMatt Macy 	iovecs[0].iov_len = aad_len;
480eda14cbcSMatt Macy 	enc_len = zio_crypt_table[crypt].ci_keylen + SHA512_HMAC_KEYLEN;
481eda14cbcSMatt Macy 
482184c1b94SMartin Matuska 	GET_UIO_STRUCT(&cuio)->uio_iov = iovecs;
483184c1b94SMartin Matuska 	zfs_uio_iovcnt(&cuio) = 4;
484184c1b94SMartin Matuska 	zfs_uio_segflg(&cuio) = UIO_SYSSPACE;
485eda14cbcSMatt Macy 
486eda14cbcSMatt Macy 	/* encrypt the keys and store the resulting ciphertext and mac */
487eda14cbcSMatt Macy 	ret = zio_do_crypt_uio_opencrypto(B_TRUE, NULL, crypt, cwkey,
488eda14cbcSMatt Macy 	    iv, enc_len, &cuio, aad_len);
489eda14cbcSMatt Macy 	if (ret != 0)
490eda14cbcSMatt Macy 		goto error;
491eda14cbcSMatt Macy 
492eda14cbcSMatt Macy 	return (0);
493eda14cbcSMatt Macy 
494eda14cbcSMatt Macy error:
495eda14cbcSMatt Macy 	return (ret);
496eda14cbcSMatt Macy }
497eda14cbcSMatt Macy 
498eda14cbcSMatt Macy int
499eda14cbcSMatt Macy zio_crypt_key_unwrap(crypto_key_t *cwkey, uint64_t crypt, uint64_t version,
500eda14cbcSMatt Macy     uint64_t guid, uint8_t *keydata, uint8_t *hmac_keydata, uint8_t *iv,
501eda14cbcSMatt Macy     uint8_t *mac, zio_crypt_key_t *key)
502eda14cbcSMatt Macy {
503eda14cbcSMatt Macy 	int ret;
504eda14cbcSMatt Macy 	uint64_t aad[3];
505eda14cbcSMatt Macy 	/*
506eda14cbcSMatt Macy 	 * With OpenCrypto in FreeBSD, the same buffer is used for
507eda14cbcSMatt Macy 	 * input and output.  Also, the AAD (for AES-GMC at least)
508eda14cbcSMatt Macy 	 * needs to logically go in front.
509eda14cbcSMatt Macy 	 */
510184c1b94SMartin Matuska 	zfs_uio_t cuio;
511184c1b94SMartin Matuska 	struct uio cuio_s;
512eda14cbcSMatt Macy 	iovec_t iovecs[4];
513eda14cbcSMatt Macy 	void *src, *dst;
514eda14cbcSMatt Macy 	uint_t enc_len, keydata_len, aad_len;
515eda14cbcSMatt Macy 
516eda14cbcSMatt Macy 	ASSERT3U(crypt, <, ZIO_CRYPT_FUNCTIONS);
517eda14cbcSMatt Macy 
518eda14cbcSMatt Macy 	keydata_len = zio_crypt_table[crypt].ci_keylen;
519eda14cbcSMatt Macy 	rw_init(&key->zk_salt_lock, NULL, RW_DEFAULT, NULL);
520eda14cbcSMatt Macy 
521184c1b94SMartin Matuska 	zfs_uio_init(&cuio, &cuio_s);
522184c1b94SMartin Matuska 
523eda14cbcSMatt Macy 	/*
524eda14cbcSMatt Macy 	 * Since we only support one buffer, we need to copy
525eda14cbcSMatt Macy 	 * the encrypted buffer (source) to the plain buffer
526eda14cbcSMatt Macy 	 * (dest).  We set iovecs[0] -- the authentication data --
527eda14cbcSMatt Macy 	 * below.
528eda14cbcSMatt Macy 	 */
529eda14cbcSMatt Macy 	dst = key->zk_master_keydata;
530eda14cbcSMatt Macy 	src = keydata;
531da5137abSMartin Matuska 	memcpy(dst, src, keydata_len);
532eda14cbcSMatt Macy 
533eda14cbcSMatt Macy 	dst = key->zk_hmac_keydata;
534eda14cbcSMatt Macy 	src = hmac_keydata;
535da5137abSMartin Matuska 	memcpy(dst, src, SHA512_HMAC_KEYLEN);
536eda14cbcSMatt Macy 
537eda14cbcSMatt Macy 	iovecs[1].iov_base = key->zk_master_keydata;
538eda14cbcSMatt Macy 	iovecs[1].iov_len = keydata_len;
539eda14cbcSMatt Macy 	iovecs[2].iov_base = key->zk_hmac_keydata;
540eda14cbcSMatt Macy 	iovecs[2].iov_len = SHA512_HMAC_KEYLEN;
541eda14cbcSMatt Macy 	iovecs[3].iov_base = mac;
542eda14cbcSMatt Macy 	iovecs[3].iov_len = WRAPPING_MAC_LEN;
543eda14cbcSMatt Macy 
544eda14cbcSMatt Macy 	if (version == 0) {
545eda14cbcSMatt Macy 		aad_len = sizeof (uint64_t);
546eda14cbcSMatt Macy 		aad[0] = LE_64(guid);
547eda14cbcSMatt Macy 	} else {
548eda14cbcSMatt Macy 		ASSERT3U(version, ==, ZIO_CRYPT_KEY_CURRENT_VERSION);
549eda14cbcSMatt Macy 		aad_len = sizeof (uint64_t) * 3;
550eda14cbcSMatt Macy 		aad[0] = LE_64(guid);
551eda14cbcSMatt Macy 		aad[1] = LE_64(crypt);
552eda14cbcSMatt Macy 		aad[2] = LE_64(version);
553eda14cbcSMatt Macy 	}
554eda14cbcSMatt Macy 
555eda14cbcSMatt Macy 	enc_len = keydata_len + SHA512_HMAC_KEYLEN;
556eda14cbcSMatt Macy 	iovecs[0].iov_base = aad;
557eda14cbcSMatt Macy 	iovecs[0].iov_len = aad_len;
558eda14cbcSMatt Macy 
559184c1b94SMartin Matuska 	GET_UIO_STRUCT(&cuio)->uio_iov = iovecs;
560184c1b94SMartin Matuska 	zfs_uio_iovcnt(&cuio) = 4;
561184c1b94SMartin Matuska 	zfs_uio_segflg(&cuio) = UIO_SYSSPACE;
562eda14cbcSMatt Macy 
563eda14cbcSMatt Macy 	/* decrypt the keys and store the result in the output buffers */
564eda14cbcSMatt Macy 	ret = zio_do_crypt_uio_opencrypto(B_FALSE, NULL, crypt, cwkey,
565eda14cbcSMatt Macy 	    iv, enc_len, &cuio, aad_len);
566eda14cbcSMatt Macy 
567eda14cbcSMatt Macy 	if (ret != 0)
568eda14cbcSMatt Macy 		goto error;
569eda14cbcSMatt Macy 
570eda14cbcSMatt Macy 	/* generate a fresh salt */
571eda14cbcSMatt Macy 	ret = random_get_bytes(key->zk_salt, ZIO_DATA_SALT_LEN);
572eda14cbcSMatt Macy 	if (ret != 0)
573eda14cbcSMatt Macy 		goto error;
574eda14cbcSMatt Macy 
575eda14cbcSMatt Macy 	/* derive the current key from the master key */
576eda14cbcSMatt Macy 	ret = hkdf_sha512(key->zk_master_keydata, keydata_len, NULL, 0,
577eda14cbcSMatt Macy 	    key->zk_salt, ZIO_DATA_SALT_LEN, key->zk_current_keydata,
578eda14cbcSMatt Macy 	    keydata_len);
579eda14cbcSMatt Macy 	if (ret != 0)
580eda14cbcSMatt Macy 		goto error;
581eda14cbcSMatt Macy 
582eda14cbcSMatt Macy 	/* initialize keys for ICP */
583eda14cbcSMatt Macy 	key->zk_current_key.ck_data = key->zk_current_keydata;
584eda14cbcSMatt Macy 	key->zk_current_key.ck_length = CRYPTO_BYTES2BITS(keydata_len);
585eda14cbcSMatt Macy 
586eda14cbcSMatt Macy 	key->zk_hmac_key.ck_data = key->zk_hmac_keydata;
587eda14cbcSMatt Macy 	key->zk_hmac_key.ck_length = CRYPTO_BYTES2BITS(SHA512_HMAC_KEYLEN);
588eda14cbcSMatt Macy 
589eda14cbcSMatt Macy 	ret = freebsd_crypt_newsession(&key->zk_session,
590eda14cbcSMatt Macy 	    &zio_crypt_table[crypt], &key->zk_current_key);
591eda14cbcSMatt Macy 	if (ret != 0)
592eda14cbcSMatt Macy 		goto error;
593eda14cbcSMatt Macy 
594eda14cbcSMatt Macy 	key->zk_crypt = crypt;
595eda14cbcSMatt Macy 	key->zk_version = version;
596eda14cbcSMatt Macy 	key->zk_guid = guid;
597eda14cbcSMatt Macy 	key->zk_salt_count = 0;
598eda14cbcSMatt Macy 
599eda14cbcSMatt Macy 	return (0);
600eda14cbcSMatt Macy 
601eda14cbcSMatt Macy error:
602eda14cbcSMatt Macy 	zio_crypt_key_destroy_early(key);
603eda14cbcSMatt Macy 	return (ret);
604eda14cbcSMatt Macy }
605eda14cbcSMatt Macy 
606eda14cbcSMatt Macy int
607eda14cbcSMatt Macy zio_crypt_generate_iv(uint8_t *ivbuf)
608eda14cbcSMatt Macy {
609eda14cbcSMatt Macy 	int ret;
610eda14cbcSMatt Macy 
611eda14cbcSMatt Macy 	/* randomly generate the IV */
612eda14cbcSMatt Macy 	ret = random_get_pseudo_bytes(ivbuf, ZIO_DATA_IV_LEN);
613eda14cbcSMatt Macy 	if (ret != 0)
614eda14cbcSMatt Macy 		goto error;
615eda14cbcSMatt Macy 
616eda14cbcSMatt Macy 	return (0);
617eda14cbcSMatt Macy 
618eda14cbcSMatt Macy error:
619da5137abSMartin Matuska 	memset(ivbuf, 0, ZIO_DATA_IV_LEN);
620eda14cbcSMatt Macy 	return (ret);
621eda14cbcSMatt Macy }
622eda14cbcSMatt Macy 
623eda14cbcSMatt Macy int
624eda14cbcSMatt Macy zio_crypt_do_hmac(zio_crypt_key_t *key, uint8_t *data, uint_t datalen,
625eda14cbcSMatt Macy     uint8_t *digestbuf, uint_t digestlen)
626eda14cbcSMatt Macy {
627eda14cbcSMatt Macy 	uint8_t raw_digestbuf[SHA512_DIGEST_LENGTH];
628eda14cbcSMatt Macy 
629eda14cbcSMatt Macy 	ASSERT3U(digestlen, <=, SHA512_DIGEST_LENGTH);
630eda14cbcSMatt Macy 
631eda14cbcSMatt Macy 	crypto_mac(&key->zk_hmac_key, data, datalen,
632eda14cbcSMatt Macy 	    raw_digestbuf, SHA512_DIGEST_LENGTH);
633eda14cbcSMatt Macy 
634da5137abSMartin Matuska 	memcpy(digestbuf, raw_digestbuf, digestlen);
635eda14cbcSMatt Macy 
636eda14cbcSMatt Macy 	return (0);
637eda14cbcSMatt Macy }
638eda14cbcSMatt Macy 
639eda14cbcSMatt Macy int
640eda14cbcSMatt Macy zio_crypt_generate_iv_salt_dedup(zio_crypt_key_t *key, uint8_t *data,
641eda14cbcSMatt Macy     uint_t datalen, uint8_t *ivbuf, uint8_t *salt)
642eda14cbcSMatt Macy {
643eda14cbcSMatt Macy 	int ret;
644eda14cbcSMatt Macy 	uint8_t digestbuf[SHA512_DIGEST_LENGTH];
645eda14cbcSMatt Macy 
646eda14cbcSMatt Macy 	ret = zio_crypt_do_hmac(key, data, datalen,
647eda14cbcSMatt Macy 	    digestbuf, SHA512_DIGEST_LENGTH);
648eda14cbcSMatt Macy 	if (ret != 0)
649eda14cbcSMatt Macy 		return (ret);
650eda14cbcSMatt Macy 
651da5137abSMartin Matuska 	memcpy(salt, digestbuf, ZIO_DATA_SALT_LEN);
652da5137abSMartin Matuska 	memcpy(ivbuf, digestbuf + ZIO_DATA_SALT_LEN, ZIO_DATA_IV_LEN);
653eda14cbcSMatt Macy 
654eda14cbcSMatt Macy 	return (0);
655eda14cbcSMatt Macy }
656eda14cbcSMatt Macy 
657eda14cbcSMatt Macy /*
658eda14cbcSMatt Macy  * The following functions are used to encode and decode encryption parameters
659eda14cbcSMatt Macy  * into blkptr_t and zil_header_t. The ICP wants to use these parameters as
660eda14cbcSMatt Macy  * byte strings, which normally means that these strings would not need to deal
661eda14cbcSMatt Macy  * with byteswapping at all. However, both blkptr_t and zil_header_t may be
662eda14cbcSMatt Macy  * byteswapped by lower layers and so we must "undo" that byteswap here upon
663eda14cbcSMatt Macy  * decoding and encoding in a non-native byteorder. These functions require
664eda14cbcSMatt Macy  * that the byteorder bit is correct before being called.
665eda14cbcSMatt Macy  */
666eda14cbcSMatt Macy void
667eda14cbcSMatt Macy zio_crypt_encode_params_bp(blkptr_t *bp, uint8_t *salt, uint8_t *iv)
668eda14cbcSMatt Macy {
669eda14cbcSMatt Macy 	uint64_t val64;
670eda14cbcSMatt Macy 	uint32_t val32;
671eda14cbcSMatt Macy 
672eda14cbcSMatt Macy 	ASSERT(BP_IS_ENCRYPTED(bp));
673eda14cbcSMatt Macy 
674eda14cbcSMatt Macy 	if (!BP_SHOULD_BYTESWAP(bp)) {
675da5137abSMartin Matuska 		memcpy(&bp->blk_dva[2].dva_word[0], salt, sizeof (uint64_t));
676da5137abSMartin Matuska 		memcpy(&bp->blk_dva[2].dva_word[1], iv, sizeof (uint64_t));
677da5137abSMartin Matuska 		memcpy(&val32, iv + sizeof (uint64_t), sizeof (uint32_t));
678eda14cbcSMatt Macy 		BP_SET_IV2(bp, val32);
679eda14cbcSMatt Macy 	} else {
680da5137abSMartin Matuska 		memcpy(&val64, salt, sizeof (uint64_t));
681eda14cbcSMatt Macy 		bp->blk_dva[2].dva_word[0] = BSWAP_64(val64);
682eda14cbcSMatt Macy 
683da5137abSMartin Matuska 		memcpy(&val64, iv, sizeof (uint64_t));
684eda14cbcSMatt Macy 		bp->blk_dva[2].dva_word[1] = BSWAP_64(val64);
685eda14cbcSMatt Macy 
686da5137abSMartin Matuska 		memcpy(&val32, iv + sizeof (uint64_t), sizeof (uint32_t));
687eda14cbcSMatt Macy 		BP_SET_IV2(bp, BSWAP_32(val32));
688eda14cbcSMatt Macy 	}
689eda14cbcSMatt Macy }
690eda14cbcSMatt Macy 
691eda14cbcSMatt Macy void
692eda14cbcSMatt Macy zio_crypt_decode_params_bp(const blkptr_t *bp, uint8_t *salt, uint8_t *iv)
693eda14cbcSMatt Macy {
694eda14cbcSMatt Macy 	uint64_t val64;
695eda14cbcSMatt Macy 	uint32_t val32;
696eda14cbcSMatt Macy 
697eda14cbcSMatt Macy 	ASSERT(BP_IS_PROTECTED(bp));
698eda14cbcSMatt Macy 
699eda14cbcSMatt Macy 	/* for convenience, so callers don't need to check */
700eda14cbcSMatt Macy 	if (BP_IS_AUTHENTICATED(bp)) {
701da5137abSMartin Matuska 		memset(salt, 0, ZIO_DATA_SALT_LEN);
702da5137abSMartin Matuska 		memset(iv, 0, ZIO_DATA_IV_LEN);
703eda14cbcSMatt Macy 		return;
704eda14cbcSMatt Macy 	}
705eda14cbcSMatt Macy 
706eda14cbcSMatt Macy 	if (!BP_SHOULD_BYTESWAP(bp)) {
707da5137abSMartin Matuska 		memcpy(salt, &bp->blk_dva[2].dva_word[0], sizeof (uint64_t));
708da5137abSMartin Matuska 		memcpy(iv, &bp->blk_dva[2].dva_word[1], sizeof (uint64_t));
709eda14cbcSMatt Macy 
710eda14cbcSMatt Macy 		val32 = (uint32_t)BP_GET_IV2(bp);
711da5137abSMartin Matuska 		memcpy(iv + sizeof (uint64_t), &val32, sizeof (uint32_t));
712eda14cbcSMatt Macy 	} else {
713eda14cbcSMatt Macy 		val64 = BSWAP_64(bp->blk_dva[2].dva_word[0]);
714da5137abSMartin Matuska 		memcpy(salt, &val64, sizeof (uint64_t));
715eda14cbcSMatt Macy 
716eda14cbcSMatt Macy 		val64 = BSWAP_64(bp->blk_dva[2].dva_word[1]);
717da5137abSMartin Matuska 		memcpy(iv, &val64, sizeof (uint64_t));
718eda14cbcSMatt Macy 
719eda14cbcSMatt Macy 		val32 = BSWAP_32((uint32_t)BP_GET_IV2(bp));
720da5137abSMartin Matuska 		memcpy(iv + sizeof (uint64_t), &val32, sizeof (uint32_t));
721eda14cbcSMatt Macy 	}
722eda14cbcSMatt Macy }
723eda14cbcSMatt Macy 
724eda14cbcSMatt Macy void
725eda14cbcSMatt Macy zio_crypt_encode_mac_bp(blkptr_t *bp, uint8_t *mac)
726eda14cbcSMatt Macy {
727eda14cbcSMatt Macy 	uint64_t val64;
728eda14cbcSMatt Macy 
729eda14cbcSMatt Macy 	ASSERT(BP_USES_CRYPT(bp));
730eda14cbcSMatt Macy 	ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_OBJSET);
731eda14cbcSMatt Macy 
732eda14cbcSMatt Macy 	if (!BP_SHOULD_BYTESWAP(bp)) {
733da5137abSMartin Matuska 		memcpy(&bp->blk_cksum.zc_word[2], mac, sizeof (uint64_t));
734da5137abSMartin Matuska 		memcpy(&bp->blk_cksum.zc_word[3], mac + sizeof (uint64_t),
735eda14cbcSMatt Macy 		    sizeof (uint64_t));
736eda14cbcSMatt Macy 	} else {
737da5137abSMartin Matuska 		memcpy(&val64, mac, sizeof (uint64_t));
738eda14cbcSMatt Macy 		bp->blk_cksum.zc_word[2] = BSWAP_64(val64);
739eda14cbcSMatt Macy 
740da5137abSMartin Matuska 		memcpy(&val64, mac + sizeof (uint64_t), sizeof (uint64_t));
741eda14cbcSMatt Macy 		bp->blk_cksum.zc_word[3] = BSWAP_64(val64);
742eda14cbcSMatt Macy 	}
743eda14cbcSMatt Macy }
744eda14cbcSMatt Macy 
745eda14cbcSMatt Macy void
746eda14cbcSMatt Macy zio_crypt_decode_mac_bp(const blkptr_t *bp, uint8_t *mac)
747eda14cbcSMatt Macy {
748eda14cbcSMatt Macy 	uint64_t val64;
749eda14cbcSMatt Macy 
750eda14cbcSMatt Macy 	ASSERT(BP_USES_CRYPT(bp) || BP_IS_HOLE(bp));
751eda14cbcSMatt Macy 
752eda14cbcSMatt Macy 	/* for convenience, so callers don't need to check */
753eda14cbcSMatt Macy 	if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
754da5137abSMartin Matuska 		memset(mac, 0, ZIO_DATA_MAC_LEN);
755eda14cbcSMatt Macy 		return;
756eda14cbcSMatt Macy 	}
757eda14cbcSMatt Macy 
758eda14cbcSMatt Macy 	if (!BP_SHOULD_BYTESWAP(bp)) {
759da5137abSMartin Matuska 		memcpy(mac, &bp->blk_cksum.zc_word[2], sizeof (uint64_t));
760da5137abSMartin Matuska 		memcpy(mac + sizeof (uint64_t), &bp->blk_cksum.zc_word[3],
761eda14cbcSMatt Macy 		    sizeof (uint64_t));
762eda14cbcSMatt Macy 	} else {
763eda14cbcSMatt Macy 		val64 = BSWAP_64(bp->blk_cksum.zc_word[2]);
764da5137abSMartin Matuska 		memcpy(mac, &val64, sizeof (uint64_t));
765eda14cbcSMatt Macy 
766eda14cbcSMatt Macy 		val64 = BSWAP_64(bp->blk_cksum.zc_word[3]);
767da5137abSMartin Matuska 		memcpy(mac + sizeof (uint64_t), &val64, sizeof (uint64_t));
768eda14cbcSMatt Macy 	}
769eda14cbcSMatt Macy }
770eda14cbcSMatt Macy 
771eda14cbcSMatt Macy void
772eda14cbcSMatt Macy zio_crypt_encode_mac_zil(void *data, uint8_t *mac)
773eda14cbcSMatt Macy {
774eda14cbcSMatt Macy 	zil_chain_t *zilc = data;
775eda14cbcSMatt Macy 
776da5137abSMartin Matuska 	memcpy(&zilc->zc_eck.zec_cksum.zc_word[2], mac, sizeof (uint64_t));
777da5137abSMartin Matuska 	memcpy(&zilc->zc_eck.zec_cksum.zc_word[3], mac + sizeof (uint64_t),
778eda14cbcSMatt Macy 	    sizeof (uint64_t));
779eda14cbcSMatt Macy }
780eda14cbcSMatt Macy 
781eda14cbcSMatt Macy void
782eda14cbcSMatt Macy zio_crypt_decode_mac_zil(const void *data, uint8_t *mac)
783eda14cbcSMatt Macy {
784eda14cbcSMatt Macy 	/*
785eda14cbcSMatt Macy 	 * The ZIL MAC is embedded in the block it protects, which will
786eda14cbcSMatt Macy 	 * not have been byteswapped by the time this function has been called.
787eda14cbcSMatt Macy 	 * As a result, we don't need to worry about byteswapping the MAC.
788eda14cbcSMatt Macy 	 */
789eda14cbcSMatt Macy 	const zil_chain_t *zilc = data;
790eda14cbcSMatt Macy 
791da5137abSMartin Matuska 	memcpy(mac, &zilc->zc_eck.zec_cksum.zc_word[2], sizeof (uint64_t));
792da5137abSMartin Matuska 	memcpy(mac + sizeof (uint64_t), &zilc->zc_eck.zec_cksum.zc_word[3],
793eda14cbcSMatt Macy 	    sizeof (uint64_t));
794eda14cbcSMatt Macy }
795eda14cbcSMatt Macy 
796eda14cbcSMatt Macy /*
797eda14cbcSMatt Macy  * This routine takes a block of dnodes (src_abd) and copies only the bonus
798eda14cbcSMatt Macy  * buffers to the same offsets in the dst buffer. datalen should be the size
799eda14cbcSMatt Macy  * of both the src_abd and the dst buffer (not just the length of the bonus
800eda14cbcSMatt Macy  * buffers).
801eda14cbcSMatt Macy  */
802eda14cbcSMatt Macy void
803eda14cbcSMatt Macy zio_crypt_copy_dnode_bonus(abd_t *src_abd, uint8_t *dst, uint_t datalen)
804eda14cbcSMatt Macy {
805eda14cbcSMatt Macy 	uint_t i, max_dnp = datalen >> DNODE_SHIFT;
806eda14cbcSMatt Macy 	uint8_t *src;
807eda14cbcSMatt Macy 	dnode_phys_t *dnp, *sdnp, *ddnp;
808eda14cbcSMatt Macy 
809eda14cbcSMatt Macy 	src = abd_borrow_buf_copy(src_abd, datalen);
810eda14cbcSMatt Macy 
811eda14cbcSMatt Macy 	sdnp = (dnode_phys_t *)src;
812eda14cbcSMatt Macy 	ddnp = (dnode_phys_t *)dst;
813eda14cbcSMatt Macy 
814eda14cbcSMatt Macy 	for (i = 0; i < max_dnp; i += sdnp[i].dn_extra_slots + 1) {
815eda14cbcSMatt Macy 		dnp = &sdnp[i];
816eda14cbcSMatt Macy 		if (dnp->dn_type != DMU_OT_NONE &&
817eda14cbcSMatt Macy 		    DMU_OT_IS_ENCRYPTED(dnp->dn_bonustype) &&
818eda14cbcSMatt Macy 		    dnp->dn_bonuslen != 0) {
819da5137abSMartin Matuska 			memcpy(DN_BONUS(&ddnp[i]), DN_BONUS(dnp),
820eda14cbcSMatt Macy 			    DN_MAX_BONUS_LEN(dnp));
821eda14cbcSMatt Macy 		}
822eda14cbcSMatt Macy 	}
823eda14cbcSMatt Macy 
824eda14cbcSMatt Macy 	abd_return_buf(src_abd, src, datalen);
825eda14cbcSMatt Macy }
826eda14cbcSMatt Macy 
827eda14cbcSMatt Macy /*
828eda14cbcSMatt Macy  * This function decides what fields from blk_prop are included in
829eda14cbcSMatt Macy  * the on-disk various MAC algorithms.
830eda14cbcSMatt Macy  */
831eda14cbcSMatt Macy static void
832eda14cbcSMatt Macy zio_crypt_bp_zero_nonportable_blkprop(blkptr_t *bp, uint64_t version)
833eda14cbcSMatt Macy {
834eda14cbcSMatt Macy 	int avoidlint = SPA_MINBLOCKSIZE;
835eda14cbcSMatt Macy 	/*
836eda14cbcSMatt Macy 	 * Version 0 did not properly zero out all non-portable fields
837eda14cbcSMatt Macy 	 * as it should have done. We maintain this code so that we can
838eda14cbcSMatt Macy 	 * do read-only imports of pools on this version.
839eda14cbcSMatt Macy 	 */
840eda14cbcSMatt Macy 	if (version == 0) {
841eda14cbcSMatt Macy 		BP_SET_DEDUP(bp, 0);
842eda14cbcSMatt Macy 		BP_SET_CHECKSUM(bp, 0);
843eda14cbcSMatt Macy 		BP_SET_PSIZE(bp, avoidlint);
844eda14cbcSMatt Macy 		return;
845eda14cbcSMatt Macy 	}
846eda14cbcSMatt Macy 
847eda14cbcSMatt Macy 	ASSERT3U(version, ==, ZIO_CRYPT_KEY_CURRENT_VERSION);
848eda14cbcSMatt Macy 
849eda14cbcSMatt Macy 	/*
850eda14cbcSMatt Macy 	 * The hole_birth feature might set these fields even if this bp
851eda14cbcSMatt Macy 	 * is a hole. We zero them out here to guarantee that raw sends
852eda14cbcSMatt Macy 	 * will function with or without the feature.
853eda14cbcSMatt Macy 	 */
854eda14cbcSMatt Macy 	if (BP_IS_HOLE(bp)) {
855eda14cbcSMatt Macy 		bp->blk_prop = 0ULL;
856eda14cbcSMatt Macy 		return;
857eda14cbcSMatt Macy 	}
858eda14cbcSMatt Macy 
859eda14cbcSMatt Macy 	/*
860eda14cbcSMatt Macy 	 * At L0 we want to verify these fields to ensure that data blocks
861eda14cbcSMatt Macy 	 * can not be reinterpreted. For instance, we do not want an attacker
862eda14cbcSMatt Macy 	 * to trick us into returning raw lz4 compressed data to the user
863eda14cbcSMatt Macy 	 * by modifying the compression bits. At higher levels, we cannot
864eda14cbcSMatt Macy 	 * enforce this policy since raw sends do not convey any information
865eda14cbcSMatt Macy 	 * about indirect blocks, so these values might be different on the
866eda14cbcSMatt Macy 	 * receive side. Fortunately, this does not open any new attack
867eda14cbcSMatt Macy 	 * vectors, since any alterations that can be made to a higher level
868eda14cbcSMatt Macy 	 * bp must still verify the correct order of the layer below it.
869eda14cbcSMatt Macy 	 */
870eda14cbcSMatt Macy 	if (BP_GET_LEVEL(bp) != 0) {
871eda14cbcSMatt Macy 		BP_SET_BYTEORDER(bp, 0);
872eda14cbcSMatt Macy 		BP_SET_COMPRESS(bp, 0);
873eda14cbcSMatt Macy 
874eda14cbcSMatt Macy 		/*
875eda14cbcSMatt Macy 		 * psize cannot be set to zero or it will trigger
876eda14cbcSMatt Macy 		 * asserts, but the value doesn't really matter as
877eda14cbcSMatt Macy 		 * long as it is constant.
878eda14cbcSMatt Macy 		 */
879eda14cbcSMatt Macy 		BP_SET_PSIZE(bp, avoidlint);
880eda14cbcSMatt Macy 	}
881eda14cbcSMatt Macy 
882eda14cbcSMatt Macy 	BP_SET_DEDUP(bp, 0);
883eda14cbcSMatt Macy 	BP_SET_CHECKSUM(bp, 0);
884eda14cbcSMatt Macy }
885eda14cbcSMatt Macy 
886eda14cbcSMatt Macy static void
887eda14cbcSMatt Macy zio_crypt_bp_auth_init(uint64_t version, boolean_t should_bswap, blkptr_t *bp,
888eda14cbcSMatt Macy     blkptr_auth_buf_t *bab, uint_t *bab_len)
889eda14cbcSMatt Macy {
890eda14cbcSMatt Macy 	blkptr_t tmpbp = *bp;
891eda14cbcSMatt Macy 
892eda14cbcSMatt Macy 	if (should_bswap)
893eda14cbcSMatt Macy 		byteswap_uint64_array(&tmpbp, sizeof (blkptr_t));
894eda14cbcSMatt Macy 
895eda14cbcSMatt Macy 	ASSERT(BP_USES_CRYPT(&tmpbp) || BP_IS_HOLE(&tmpbp));
896eda14cbcSMatt Macy 	ASSERT0(BP_IS_EMBEDDED(&tmpbp));
897eda14cbcSMatt Macy 
898eda14cbcSMatt Macy 	zio_crypt_decode_mac_bp(&tmpbp, bab->bab_mac);
899eda14cbcSMatt Macy 
900eda14cbcSMatt Macy 	/*
901eda14cbcSMatt Macy 	 * We always MAC blk_prop in LE to ensure portability. This
902eda14cbcSMatt Macy 	 * must be done after decoding the mac, since the endianness
903eda14cbcSMatt Macy 	 * will get zero'd out here.
904eda14cbcSMatt Macy 	 */
905eda14cbcSMatt Macy 	zio_crypt_bp_zero_nonportable_blkprop(&tmpbp, version);
906eda14cbcSMatt Macy 	bab->bab_prop = LE_64(tmpbp.blk_prop);
907eda14cbcSMatt Macy 	bab->bab_pad = 0ULL;
908eda14cbcSMatt Macy 
909eda14cbcSMatt Macy 	/* version 0 did not include the padding */
910eda14cbcSMatt Macy 	*bab_len = sizeof (blkptr_auth_buf_t);
911eda14cbcSMatt Macy 	if (version == 0)
912eda14cbcSMatt Macy 		*bab_len -= sizeof (uint64_t);
913eda14cbcSMatt Macy }
914eda14cbcSMatt Macy 
915eda14cbcSMatt Macy static int
916eda14cbcSMatt Macy zio_crypt_bp_do_hmac_updates(crypto_context_t ctx, uint64_t version,
917eda14cbcSMatt Macy     boolean_t should_bswap, blkptr_t *bp)
918eda14cbcSMatt Macy {
919eda14cbcSMatt Macy 	uint_t bab_len;
920eda14cbcSMatt Macy 	blkptr_auth_buf_t bab;
921eda14cbcSMatt Macy 
922eda14cbcSMatt Macy 	zio_crypt_bp_auth_init(version, should_bswap, bp, &bab, &bab_len);
923eda14cbcSMatt Macy 	crypto_mac_update(ctx, &bab, bab_len);
924eda14cbcSMatt Macy 
925eda14cbcSMatt Macy 	return (0);
926eda14cbcSMatt Macy }
927eda14cbcSMatt Macy 
928eda14cbcSMatt Macy static void
929eda14cbcSMatt Macy zio_crypt_bp_do_indrect_checksum_updates(SHA2_CTX *ctx, uint64_t version,
930eda14cbcSMatt Macy     boolean_t should_bswap, blkptr_t *bp)
931eda14cbcSMatt Macy {
932eda14cbcSMatt Macy 	uint_t bab_len;
933eda14cbcSMatt Macy 	blkptr_auth_buf_t bab;
934eda14cbcSMatt Macy 
935eda14cbcSMatt Macy 	zio_crypt_bp_auth_init(version, should_bswap, bp, &bab, &bab_len);
936eda14cbcSMatt Macy 	SHA2Update(ctx, &bab, bab_len);
937eda14cbcSMatt Macy }
938eda14cbcSMatt Macy 
939eda14cbcSMatt Macy static void
940eda14cbcSMatt Macy zio_crypt_bp_do_aad_updates(uint8_t **aadp, uint_t *aad_len, uint64_t version,
941eda14cbcSMatt Macy     boolean_t should_bswap, blkptr_t *bp)
942eda14cbcSMatt Macy {
943eda14cbcSMatt Macy 	uint_t bab_len;
944eda14cbcSMatt Macy 	blkptr_auth_buf_t bab;
945eda14cbcSMatt Macy 
946eda14cbcSMatt Macy 	zio_crypt_bp_auth_init(version, should_bswap, bp, &bab, &bab_len);
947da5137abSMartin Matuska 	memcpy(*aadp, &bab, bab_len);
948eda14cbcSMatt Macy 	*aadp += bab_len;
949eda14cbcSMatt Macy 	*aad_len += bab_len;
950eda14cbcSMatt Macy }
951eda14cbcSMatt Macy 
952eda14cbcSMatt Macy static int
953eda14cbcSMatt Macy zio_crypt_do_dnode_hmac_updates(crypto_context_t ctx, uint64_t version,
954eda14cbcSMatt Macy     boolean_t should_bswap, dnode_phys_t *dnp)
955eda14cbcSMatt Macy {
956eda14cbcSMatt Macy 	int ret, i;
957eda14cbcSMatt Macy 	dnode_phys_t *adnp;
958eda14cbcSMatt Macy 	boolean_t le_bswap = (should_bswap == ZFS_HOST_BYTEORDER);
959eda14cbcSMatt Macy 	uint8_t tmp_dncore[offsetof(dnode_phys_t, dn_blkptr)];
960eda14cbcSMatt Macy 
961eda14cbcSMatt Macy 	/* authenticate the core dnode (masking out non-portable bits) */
962da5137abSMartin Matuska 	memcpy(tmp_dncore, dnp, sizeof (tmp_dncore));
963eda14cbcSMatt Macy 	adnp = (dnode_phys_t *)tmp_dncore;
964eda14cbcSMatt Macy 	if (le_bswap) {
965eda14cbcSMatt Macy 		adnp->dn_datablkszsec = BSWAP_16(adnp->dn_datablkszsec);
966eda14cbcSMatt Macy 		adnp->dn_bonuslen = BSWAP_16(adnp->dn_bonuslen);
967eda14cbcSMatt Macy 		adnp->dn_maxblkid = BSWAP_64(adnp->dn_maxblkid);
968eda14cbcSMatt Macy 		adnp->dn_used = BSWAP_64(adnp->dn_used);
969eda14cbcSMatt Macy 	}
970eda14cbcSMatt Macy 	adnp->dn_flags &= DNODE_CRYPT_PORTABLE_FLAGS_MASK;
971eda14cbcSMatt Macy 	adnp->dn_used = 0;
972eda14cbcSMatt Macy 
973eda14cbcSMatt Macy 	crypto_mac_update(ctx, adnp, sizeof (tmp_dncore));
974eda14cbcSMatt Macy 
975eda14cbcSMatt Macy 	for (i = 0; i < dnp->dn_nblkptr; i++) {
976eda14cbcSMatt Macy 		ret = zio_crypt_bp_do_hmac_updates(ctx, version,
977eda14cbcSMatt Macy 		    should_bswap, &dnp->dn_blkptr[i]);
978eda14cbcSMatt Macy 		if (ret != 0)
979eda14cbcSMatt Macy 			goto error;
980eda14cbcSMatt Macy 	}
981eda14cbcSMatt Macy 
982eda14cbcSMatt Macy 	if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
983eda14cbcSMatt Macy 		ret = zio_crypt_bp_do_hmac_updates(ctx, version,
984eda14cbcSMatt Macy 		    should_bswap, DN_SPILL_BLKPTR(dnp));
985eda14cbcSMatt Macy 		if (ret != 0)
986eda14cbcSMatt Macy 			goto error;
987eda14cbcSMatt Macy 	}
988eda14cbcSMatt Macy 
989eda14cbcSMatt Macy 	return (0);
990eda14cbcSMatt Macy 
991eda14cbcSMatt Macy error:
992eda14cbcSMatt Macy 	return (ret);
993eda14cbcSMatt Macy }
994eda14cbcSMatt Macy 
995eda14cbcSMatt Macy /*
996eda14cbcSMatt Macy  * objset_phys_t blocks introduce a number of exceptions to the normal
997eda14cbcSMatt Macy  * authentication process. objset_phys_t's contain 2 separate HMACS for
998eda14cbcSMatt Macy  * protecting the integrity of their data. The portable_mac protects the
999eda14cbcSMatt Macy  * metadnode. This MAC can be sent with a raw send and protects against
1000eda14cbcSMatt Macy  * reordering of data within the metadnode. The local_mac protects the user
1001eda14cbcSMatt Macy  * accounting objects which are not sent from one system to another.
1002eda14cbcSMatt Macy  *
1003eda14cbcSMatt Macy  * In addition, objset blocks are the only blocks that can be modified and
1004eda14cbcSMatt Macy  * written to disk without the key loaded under certain circumstances. During
1005eda14cbcSMatt Macy  * zil_claim() we need to be able to update the zil_header_t to complete
1006eda14cbcSMatt Macy  * claiming log blocks and during raw receives we need to write out the
1007eda14cbcSMatt Macy  * portable_mac from the send file. Both of these actions are possible
1008eda14cbcSMatt Macy  * because these fields are not protected by either MAC so neither one will
1009eda14cbcSMatt Macy  * need to modify the MACs without the key. However, when the modified blocks
1010eda14cbcSMatt Macy  * are written out they will be byteswapped into the host machine's native
1011eda14cbcSMatt Macy  * endianness which will modify fields protected by the MAC. As a result, MAC
1012eda14cbcSMatt Macy  * calculation for objset blocks works slightly differently from other block
1013eda14cbcSMatt Macy  * types. Where other block types MAC the data in whatever endianness is
1014eda14cbcSMatt Macy  * written to disk, objset blocks always MAC little endian version of their
1015eda14cbcSMatt Macy  * values. In the code, should_bswap is the value from BP_SHOULD_BYTESWAP()
1016eda14cbcSMatt Macy  * and le_bswap indicates whether a byteswap is needed to get this block
1017eda14cbcSMatt Macy  * into little endian format.
1018eda14cbcSMatt Macy  */
1019eda14cbcSMatt Macy int
1020eda14cbcSMatt Macy zio_crypt_do_objset_hmacs(zio_crypt_key_t *key, void *data, uint_t datalen,
1021eda14cbcSMatt Macy     boolean_t should_bswap, uint8_t *portable_mac, uint8_t *local_mac)
1022eda14cbcSMatt Macy {
1023eda14cbcSMatt Macy 	int ret;
1024eda14cbcSMatt Macy 	struct hmac_ctx hash_ctx;
1025eda14cbcSMatt Macy 	struct hmac_ctx *ctx = &hash_ctx;
1026eda14cbcSMatt Macy 	objset_phys_t *osp = data;
1027eda14cbcSMatt Macy 	uint64_t intval;
1028eda14cbcSMatt Macy 	boolean_t le_bswap = (should_bswap == ZFS_HOST_BYTEORDER);
1029eda14cbcSMatt Macy 	uint8_t raw_portable_mac[SHA512_DIGEST_LENGTH];
1030eda14cbcSMatt Macy 	uint8_t raw_local_mac[SHA512_DIGEST_LENGTH];
1031eda14cbcSMatt Macy 
1032eda14cbcSMatt Macy 
1033eda14cbcSMatt Macy 	/* calculate the portable MAC from the portable fields and metadnode */
1034eda14cbcSMatt Macy 	crypto_mac_init(ctx, &key->zk_hmac_key);
1035eda14cbcSMatt Macy 
1036eda14cbcSMatt Macy 	/* add in the os_type */
1037eda14cbcSMatt Macy 	intval = (le_bswap) ? osp->os_type : BSWAP_64(osp->os_type);
1038eda14cbcSMatt Macy 	crypto_mac_update(ctx, &intval, sizeof (uint64_t));
1039eda14cbcSMatt Macy 
1040eda14cbcSMatt Macy 	/* add in the portable os_flags */
1041eda14cbcSMatt Macy 	intval = osp->os_flags;
1042eda14cbcSMatt Macy 	if (should_bswap)
1043eda14cbcSMatt Macy 		intval = BSWAP_64(intval);
1044eda14cbcSMatt Macy 	intval &= OBJSET_CRYPT_PORTABLE_FLAGS_MASK;
1045eda14cbcSMatt Macy 	if (!ZFS_HOST_BYTEORDER)
1046eda14cbcSMatt Macy 		intval = BSWAP_64(intval);
1047eda14cbcSMatt Macy 
1048eda14cbcSMatt Macy 	crypto_mac_update(ctx, &intval, sizeof (uint64_t));
1049eda14cbcSMatt Macy 
1050eda14cbcSMatt Macy 	/* add in fields from the metadnode */
1051eda14cbcSMatt Macy 	ret = zio_crypt_do_dnode_hmac_updates(ctx, key->zk_version,
1052eda14cbcSMatt Macy 	    should_bswap, &osp->os_meta_dnode);
1053eda14cbcSMatt Macy 	if (ret)
1054eda14cbcSMatt Macy 		goto error;
1055eda14cbcSMatt Macy 
1056eda14cbcSMatt Macy 	crypto_mac_final(ctx, raw_portable_mac, SHA512_DIGEST_LENGTH);
1057eda14cbcSMatt Macy 
1058da5137abSMartin Matuska 	memcpy(portable_mac, raw_portable_mac, ZIO_OBJSET_MAC_LEN);
1059eda14cbcSMatt Macy 
1060eda14cbcSMatt Macy 	/*
1061e92ffd9bSMartin Matuska 	 * This is necessary here as we check next whether
1062e92ffd9bSMartin Matuska 	 * OBJSET_FLAG_USERACCOUNTING_COMPLETE is set in order to
1063e92ffd9bSMartin Matuska 	 * decide if the local_mac should be zeroed out. That flag will always
1064e92ffd9bSMartin Matuska 	 * be set by dmu_objset_id_quota_upgrade_cb() and
1065e92ffd9bSMartin Matuska 	 * dmu_objset_userspace_upgrade_cb() if useraccounting has been
1066e92ffd9bSMartin Matuska 	 * completed.
1067e92ffd9bSMartin Matuska 	 */
1068e92ffd9bSMartin Matuska 	intval = osp->os_flags;
1069e92ffd9bSMartin Matuska 	if (should_bswap)
1070e92ffd9bSMartin Matuska 		intval = BSWAP_64(intval);
1071e92ffd9bSMartin Matuska 	boolean_t uacct_incomplete =
1072e92ffd9bSMartin Matuska 	    !(intval & OBJSET_FLAG_USERACCOUNTING_COMPLETE);
1073e92ffd9bSMartin Matuska 
1074e92ffd9bSMartin Matuska 	/*
1075eda14cbcSMatt Macy 	 * The local MAC protects the user, group and project accounting.
1076eda14cbcSMatt Macy 	 * If these objects are not present, the local MAC is zeroed out.
1077eda14cbcSMatt Macy 	 */
1078e92ffd9bSMartin Matuska 	if (uacct_incomplete ||
1079e92ffd9bSMartin Matuska 	    (datalen >= OBJSET_PHYS_SIZE_V3 &&
1080eda14cbcSMatt Macy 	    osp->os_userused_dnode.dn_type == DMU_OT_NONE &&
1081eda14cbcSMatt Macy 	    osp->os_groupused_dnode.dn_type == DMU_OT_NONE &&
1082eda14cbcSMatt Macy 	    osp->os_projectused_dnode.dn_type == DMU_OT_NONE) ||
1083eda14cbcSMatt Macy 	    (datalen >= OBJSET_PHYS_SIZE_V2 &&
1084eda14cbcSMatt Macy 	    osp->os_userused_dnode.dn_type == DMU_OT_NONE &&
1085eda14cbcSMatt Macy 	    osp->os_groupused_dnode.dn_type == DMU_OT_NONE) ||
108616038816SMartin Matuska 	    (datalen <= OBJSET_PHYS_SIZE_V1)) {
1087da5137abSMartin Matuska 		memset(local_mac, 0, ZIO_OBJSET_MAC_LEN);
1088eda14cbcSMatt Macy 		return (0);
1089eda14cbcSMatt Macy 	}
1090eda14cbcSMatt Macy 
1091eda14cbcSMatt Macy 	/* calculate the local MAC from the userused and groupused dnodes */
1092eda14cbcSMatt Macy 	crypto_mac_init(ctx, &key->zk_hmac_key);
1093eda14cbcSMatt Macy 
1094eda14cbcSMatt Macy 	/* add in the non-portable os_flags */
1095eda14cbcSMatt Macy 	intval = osp->os_flags;
1096eda14cbcSMatt Macy 	if (should_bswap)
1097eda14cbcSMatt Macy 		intval = BSWAP_64(intval);
1098eda14cbcSMatt Macy 	intval &= ~OBJSET_CRYPT_PORTABLE_FLAGS_MASK;
1099eda14cbcSMatt Macy 	if (!ZFS_HOST_BYTEORDER)
1100eda14cbcSMatt Macy 		intval = BSWAP_64(intval);
1101eda14cbcSMatt Macy 
1102eda14cbcSMatt Macy 	crypto_mac_update(ctx, &intval, sizeof (uint64_t));
1103eda14cbcSMatt Macy 
1104eda14cbcSMatt Macy 	/* XXX check dnode type ... */
1105eda14cbcSMatt Macy 	/* add in fields from the user accounting dnodes */
1106eda14cbcSMatt Macy 	if (osp->os_userused_dnode.dn_type != DMU_OT_NONE) {
1107eda14cbcSMatt Macy 		ret = zio_crypt_do_dnode_hmac_updates(ctx, key->zk_version,
1108eda14cbcSMatt Macy 		    should_bswap, &osp->os_userused_dnode);
1109eda14cbcSMatt Macy 		if (ret)
1110eda14cbcSMatt Macy 			goto error;
1111eda14cbcSMatt Macy 	}
1112eda14cbcSMatt Macy 
1113eda14cbcSMatt Macy 	if (osp->os_groupused_dnode.dn_type != DMU_OT_NONE) {
1114eda14cbcSMatt Macy 		ret = zio_crypt_do_dnode_hmac_updates(ctx, key->zk_version,
1115eda14cbcSMatt Macy 		    should_bswap, &osp->os_groupused_dnode);
1116eda14cbcSMatt Macy 		if (ret)
1117eda14cbcSMatt Macy 			goto error;
1118eda14cbcSMatt Macy 	}
1119eda14cbcSMatt Macy 
1120eda14cbcSMatt Macy 	if (osp->os_projectused_dnode.dn_type != DMU_OT_NONE &&
1121eda14cbcSMatt Macy 	    datalen >= OBJSET_PHYS_SIZE_V3) {
1122eda14cbcSMatt Macy 		ret = zio_crypt_do_dnode_hmac_updates(ctx, key->zk_version,
1123eda14cbcSMatt Macy 		    should_bswap, &osp->os_projectused_dnode);
1124eda14cbcSMatt Macy 		if (ret)
1125eda14cbcSMatt Macy 			goto error;
1126eda14cbcSMatt Macy 	}
1127eda14cbcSMatt Macy 
1128eda14cbcSMatt Macy 	crypto_mac_final(ctx, raw_local_mac, SHA512_DIGEST_LENGTH);
1129eda14cbcSMatt Macy 
1130da5137abSMartin Matuska 	memcpy(local_mac, raw_local_mac, ZIO_OBJSET_MAC_LEN);
1131eda14cbcSMatt Macy 
1132eda14cbcSMatt Macy 	return (0);
1133eda14cbcSMatt Macy 
1134eda14cbcSMatt Macy error:
1135da5137abSMartin Matuska 	memset(portable_mac, 0, ZIO_OBJSET_MAC_LEN);
1136da5137abSMartin Matuska 	memset(local_mac, 0, ZIO_OBJSET_MAC_LEN);
1137eda14cbcSMatt Macy 	return (ret);
1138eda14cbcSMatt Macy }
1139eda14cbcSMatt Macy 
1140eda14cbcSMatt Macy static void
1141184c1b94SMartin Matuska zio_crypt_destroy_uio(zfs_uio_t *uio)
1142eda14cbcSMatt Macy {
1143184c1b94SMartin Matuska 	if (GET_UIO_STRUCT(uio)->uio_iov)
1144184c1b94SMartin Matuska 		kmem_free(GET_UIO_STRUCT(uio)->uio_iov,
1145184c1b94SMartin Matuska 		    zfs_uio_iovcnt(uio) * sizeof (iovec_t));
1146eda14cbcSMatt Macy }
1147eda14cbcSMatt Macy 
1148eda14cbcSMatt Macy /*
1149eda14cbcSMatt Macy  * This function parses an uncompressed indirect block and returns a checksum
1150eda14cbcSMatt Macy  * of all the portable fields from all of the contained bps. The portable
1151eda14cbcSMatt Macy  * fields are the MAC and all of the fields from blk_prop except for the dedup,
1152eda14cbcSMatt Macy  * checksum, and psize bits. For an explanation of the purpose of this, see
1153eda14cbcSMatt Macy  * the comment block on object set authentication.
1154eda14cbcSMatt Macy  */
1155eda14cbcSMatt Macy static int
1156eda14cbcSMatt Macy zio_crypt_do_indirect_mac_checksum_impl(boolean_t generate, void *buf,
1157eda14cbcSMatt Macy     uint_t datalen, uint64_t version, boolean_t byteswap, uint8_t *cksum)
1158eda14cbcSMatt Macy {
1159eda14cbcSMatt Macy 	blkptr_t *bp;
1160eda14cbcSMatt Macy 	int i, epb = datalen >> SPA_BLKPTRSHIFT;
1161eda14cbcSMatt Macy 	SHA2_CTX ctx;
1162eda14cbcSMatt Macy 	uint8_t digestbuf[SHA512_DIGEST_LENGTH];
1163eda14cbcSMatt Macy 
1164eda14cbcSMatt Macy 	/* checksum all of the MACs from the layer below */
1165eda14cbcSMatt Macy 	SHA2Init(SHA512, &ctx);
1166eda14cbcSMatt Macy 	for (i = 0, bp = buf; i < epb; i++, bp++) {
1167eda14cbcSMatt Macy 		zio_crypt_bp_do_indrect_checksum_updates(&ctx, version,
1168eda14cbcSMatt Macy 		    byteswap, bp);
1169eda14cbcSMatt Macy 	}
1170eda14cbcSMatt Macy 	SHA2Final(digestbuf, &ctx);
1171eda14cbcSMatt Macy 
1172eda14cbcSMatt Macy 	if (generate) {
1173da5137abSMartin Matuska 		memcpy(cksum, digestbuf, ZIO_DATA_MAC_LEN);
1174eda14cbcSMatt Macy 		return (0);
1175eda14cbcSMatt Macy 	}
1176eda14cbcSMatt Macy 
1177da5137abSMartin Matuska 	if (memcmp(digestbuf, cksum, ZIO_DATA_MAC_LEN) != 0) {
1178eda14cbcSMatt Macy #ifdef FCRYPTO_DEBUG
1179eda14cbcSMatt Macy 		printf("%s(%d): Setting ECKSUM\n", __FUNCTION__, __LINE__);
1180eda14cbcSMatt Macy #endif
1181eda14cbcSMatt Macy 		return (SET_ERROR(ECKSUM));
1182eda14cbcSMatt Macy 	}
1183eda14cbcSMatt Macy 	return (0);
1184eda14cbcSMatt Macy }
1185eda14cbcSMatt Macy 
1186eda14cbcSMatt Macy int
1187eda14cbcSMatt Macy zio_crypt_do_indirect_mac_checksum(boolean_t generate, void *buf,
1188eda14cbcSMatt Macy     uint_t datalen, boolean_t byteswap, uint8_t *cksum)
1189eda14cbcSMatt Macy {
1190eda14cbcSMatt Macy 	int ret;
1191eda14cbcSMatt Macy 
1192eda14cbcSMatt Macy 	/*
1193eda14cbcSMatt Macy 	 * Unfortunately, callers of this function will not always have
1194eda14cbcSMatt Macy 	 * easy access to the on-disk format version. This info is
1195eda14cbcSMatt Macy 	 * normally found in the DSL Crypto Key, but the checksum-of-MACs
1196eda14cbcSMatt Macy 	 * is expected to be verifiable even when the key isn't loaded.
1197eda14cbcSMatt Macy 	 * Here, instead of doing a ZAP lookup for the version for each
1198eda14cbcSMatt Macy 	 * zio, we simply try both existing formats.
1199eda14cbcSMatt Macy 	 */
1200eda14cbcSMatt Macy 	ret = zio_crypt_do_indirect_mac_checksum_impl(generate, buf,
1201eda14cbcSMatt Macy 	    datalen, ZIO_CRYPT_KEY_CURRENT_VERSION, byteswap, cksum);
1202eda14cbcSMatt Macy 	if (ret == ECKSUM) {
1203eda14cbcSMatt Macy 		ASSERT(!generate);
1204eda14cbcSMatt Macy 		ret = zio_crypt_do_indirect_mac_checksum_impl(generate,
1205eda14cbcSMatt Macy 		    buf, datalen, 0, byteswap, cksum);
1206eda14cbcSMatt Macy 	}
1207eda14cbcSMatt Macy 
1208eda14cbcSMatt Macy 	return (ret);
1209eda14cbcSMatt Macy }
1210eda14cbcSMatt Macy 
1211eda14cbcSMatt Macy int
1212eda14cbcSMatt Macy zio_crypt_do_indirect_mac_checksum_abd(boolean_t generate, abd_t *abd,
1213eda14cbcSMatt Macy     uint_t datalen, boolean_t byteswap, uint8_t *cksum)
1214eda14cbcSMatt Macy {
1215eda14cbcSMatt Macy 	int ret;
1216eda14cbcSMatt Macy 	void *buf;
1217eda14cbcSMatt Macy 
1218eda14cbcSMatt Macy 	buf = abd_borrow_buf_copy(abd, datalen);
1219eda14cbcSMatt Macy 	ret = zio_crypt_do_indirect_mac_checksum(generate, buf, datalen,
1220eda14cbcSMatt Macy 	    byteswap, cksum);
1221eda14cbcSMatt Macy 	abd_return_buf(abd, buf, datalen);
1222eda14cbcSMatt Macy 
1223eda14cbcSMatt Macy 	return (ret);
1224eda14cbcSMatt Macy }
1225eda14cbcSMatt Macy 
1226eda14cbcSMatt Macy /*
1227eda14cbcSMatt Macy  * Special case handling routine for encrypting / decrypting ZIL blocks.
1228eda14cbcSMatt Macy  * We do not check for the older ZIL chain because the encryption feature
1229eda14cbcSMatt Macy  * was not available before the newer ZIL chain was introduced. The goal
1230eda14cbcSMatt Macy  * here is to encrypt everything except the blkptr_t of a lr_write_t and
1231eda14cbcSMatt Macy  * the zil_chain_t header. Everything that is not encrypted is authenticated.
1232eda14cbcSMatt Macy  */
1233eda14cbcSMatt Macy /*
1234eda14cbcSMatt Macy  * The OpenCrypto used in FreeBSD does not use separate source and
1235eda14cbcSMatt Macy  * destination buffers; instead, the same buffer is used.  Further, to
1236eda14cbcSMatt Macy  * accommodate some of the drivers, the authbuf needs to be logically before
1237eda14cbcSMatt Macy  * the data.  This means that we need to copy the source to the destination,
1238eda14cbcSMatt Macy  * and set up an extra iovec_t at the beginning to handle the authbuf.
1239184c1b94SMartin Matuska  * It also means we'll only return one zfs_uio_t.
1240eda14cbcSMatt Macy  */
1241eda14cbcSMatt Macy 
1242eda14cbcSMatt Macy static int
1243eda14cbcSMatt Macy zio_crypt_init_uios_zil(boolean_t encrypt, uint8_t *plainbuf,
1244184c1b94SMartin Matuska     uint8_t *cipherbuf, uint_t datalen, boolean_t byteswap, zfs_uio_t *puio,
1245184c1b94SMartin Matuska     zfs_uio_t *out_uio, uint_t *enc_len, uint8_t **authbuf, uint_t *auth_len,
1246eda14cbcSMatt Macy     boolean_t *no_crypt)
1247eda14cbcSMatt Macy {
1248e92ffd9bSMartin Matuska 	(void) puio;
1249c40487d4SMatt Macy 	uint8_t *aadbuf = zio_buf_alloc(datalen);
1250eda14cbcSMatt Macy 	uint8_t *src, *dst, *slrp, *dlrp, *blkend, *aadp;
1251c40487d4SMatt Macy 	iovec_t *dst_iovecs;
1252eda14cbcSMatt Macy 	zil_chain_t *zilc;
1253eda14cbcSMatt Macy 	lr_t *lr;
1254525fe93dSMartin Matuska 	uint64_t txtype, lr_len, nused;
1255c40487d4SMatt Macy 	uint_t crypt_len, nr_iovecs, vec;
1256c40487d4SMatt Macy 	uint_t aad_len = 0, total_len = 0;
1257eda14cbcSMatt Macy 
1258eda14cbcSMatt Macy 	if (encrypt) {
1259eda14cbcSMatt Macy 		src = plainbuf;
1260eda14cbcSMatt Macy 		dst = cipherbuf;
1261eda14cbcSMatt Macy 	} else {
1262eda14cbcSMatt Macy 		src = cipherbuf;
1263eda14cbcSMatt Macy 		dst = plainbuf;
1264eda14cbcSMatt Macy 	}
1265da5137abSMartin Matuska 	memcpy(dst, src, datalen);
1266eda14cbcSMatt Macy 
1267c40487d4SMatt Macy 	/* Find the start and end record of the log block. */
1268eda14cbcSMatt Macy 	zilc = (zil_chain_t *)src;
1269eda14cbcSMatt Macy 	slrp = src + sizeof (zil_chain_t);
1270eda14cbcSMatt Macy 	aadp = aadbuf;
1271525fe93dSMartin Matuska 	nused = ((byteswap) ? BSWAP_64(zilc->zc_nused) : zilc->zc_nused);
1272525fe93dSMartin Matuska 	ASSERT3U(nused, >=, sizeof (zil_chain_t));
1273525fe93dSMartin Matuska 	ASSERT3U(nused, <=, datalen);
1274525fe93dSMartin Matuska 	blkend = src + nused;
1275eda14cbcSMatt Macy 
1276c40487d4SMatt Macy 	/*
1277c40487d4SMatt Macy 	 * Calculate the number of encrypted iovecs we will need.
1278c40487d4SMatt Macy 	 */
1279c40487d4SMatt Macy 
1280c40487d4SMatt Macy 	/* We need at least two iovecs -- one for the AAD, one for the MAC. */
1281c40487d4SMatt Macy 	nr_iovecs = 2;
1282c40487d4SMatt Macy 
1283eda14cbcSMatt Macy 	for (; slrp < blkend; slrp += lr_len) {
1284eda14cbcSMatt Macy 		lr = (lr_t *)slrp;
1285eda14cbcSMatt Macy 
1286c40487d4SMatt Macy 		if (byteswap) {
1287eda14cbcSMatt Macy 			txtype = BSWAP_64(lr->lrc_txtype);
1288eda14cbcSMatt Macy 			lr_len = BSWAP_64(lr->lrc_reclen);
1289c40487d4SMatt Macy 		} else {
1290c40487d4SMatt Macy 			txtype = lr->lrc_txtype;
1291c40487d4SMatt Macy 			lr_len = lr->lrc_reclen;
1292eda14cbcSMatt Macy 		}
1293525fe93dSMartin Matuska 		ASSERT3U(lr_len, >=, sizeof (lr_t));
1294525fe93dSMartin Matuska 		ASSERT3U(lr_len, <=, blkend - slrp);
1295eda14cbcSMatt Macy 
1296eda14cbcSMatt Macy 		nr_iovecs++;
1297eda14cbcSMatt Macy 		if (txtype == TX_WRITE && lr_len != sizeof (lr_write_t))
1298eda14cbcSMatt Macy 			nr_iovecs++;
1299eda14cbcSMatt Macy 	}
1300eda14cbcSMatt Macy 
1301c40487d4SMatt Macy 	dst_iovecs = kmem_alloc(nr_iovecs * sizeof (iovec_t), KM_SLEEP);
1302eda14cbcSMatt Macy 
1303eda14cbcSMatt Macy 	/*
1304eda14cbcSMatt Macy 	 * Copy the plain zil header over and authenticate everything except
1305eda14cbcSMatt Macy 	 * the checksum that will store our MAC. If we are writing the data
1306eda14cbcSMatt Macy 	 * the embedded checksum will not have been calculated yet, so we don't
1307eda14cbcSMatt Macy 	 * authenticate that.
1308eda14cbcSMatt Macy 	 */
1309da5137abSMartin Matuska 	memcpy(aadp, src, sizeof (zil_chain_t) - sizeof (zio_eck_t));
1310eda14cbcSMatt Macy 	aadp += sizeof (zil_chain_t) - sizeof (zio_eck_t);
1311eda14cbcSMatt Macy 	aad_len += sizeof (zil_chain_t) - sizeof (zio_eck_t);
1312eda14cbcSMatt Macy 
1313eda14cbcSMatt Macy 	slrp = src + sizeof (zil_chain_t);
1314eda14cbcSMatt Macy 	dlrp = dst + sizeof (zil_chain_t);
1315eda14cbcSMatt Macy 
1316c40487d4SMatt Macy 	/*
1317c40487d4SMatt Macy 	 * Loop over records again, filling in iovecs.
1318c40487d4SMatt Macy 	 */
1319c40487d4SMatt Macy 
1320c40487d4SMatt Macy 	/* The first iovec will contain the authbuf. */
1321c40487d4SMatt Macy 	vec = 1;
1322c40487d4SMatt Macy 
1323eda14cbcSMatt Macy 	for (; slrp < blkend; slrp += lr_len, dlrp += lr_len) {
1324eda14cbcSMatt Macy 		lr = (lr_t *)slrp;
1325eda14cbcSMatt Macy 
1326eda14cbcSMatt Macy 		if (!byteswap) {
1327eda14cbcSMatt Macy 			txtype = lr->lrc_txtype;
1328eda14cbcSMatt Macy 			lr_len = lr->lrc_reclen;
1329eda14cbcSMatt Macy 		} else {
1330eda14cbcSMatt Macy 			txtype = BSWAP_64(lr->lrc_txtype);
1331eda14cbcSMatt Macy 			lr_len = BSWAP_64(lr->lrc_reclen);
1332eda14cbcSMatt Macy 		}
1333eda14cbcSMatt Macy 
1334eda14cbcSMatt Macy 		/* copy the common lr_t */
1335da5137abSMartin Matuska 		memcpy(dlrp, slrp, sizeof (lr_t));
1336da5137abSMartin Matuska 		memcpy(aadp, slrp, sizeof (lr_t));
1337eda14cbcSMatt Macy 		aadp += sizeof (lr_t);
1338eda14cbcSMatt Macy 		aad_len += sizeof (lr_t);
1339eda14cbcSMatt Macy 
1340eda14cbcSMatt Macy 		/*
1341eda14cbcSMatt Macy 		 * If this is a TX_WRITE record we want to encrypt everything
1342eda14cbcSMatt Macy 		 * except the bp if exists. If the bp does exist we want to
1343eda14cbcSMatt Macy 		 * authenticate it.
1344eda14cbcSMatt Macy 		 */
1345eda14cbcSMatt Macy 		if (txtype == TX_WRITE) {
13462276e539SMartin Matuska 			const size_t o = offsetof(lr_write_t, lr_blkptr);
13472276e539SMartin Matuska 			crypt_len = o - sizeof (lr_t);
13482276e539SMartin Matuska 			dst_iovecs[vec].iov_base = (char *)dlrp + sizeof (lr_t);
1349c40487d4SMatt Macy 			dst_iovecs[vec].iov_len = crypt_len;
1350eda14cbcSMatt Macy 
1351eda14cbcSMatt Macy 			/* copy the bp now since it will not be encrypted */
13522276e539SMartin Matuska 			memcpy(dlrp + o, slrp + o, sizeof (blkptr_t));
13532276e539SMartin Matuska 			memcpy(aadp, slrp + o, sizeof (blkptr_t));
1354eda14cbcSMatt Macy 			aadp += sizeof (blkptr_t);
1355eda14cbcSMatt Macy 			aad_len += sizeof (blkptr_t);
1356c40487d4SMatt Macy 			vec++;
1357eda14cbcSMatt Macy 			total_len += crypt_len;
1358eda14cbcSMatt Macy 
1359eda14cbcSMatt Macy 			if (lr_len != sizeof (lr_write_t)) {
1360eda14cbcSMatt Macy 				crypt_len = lr_len - sizeof (lr_write_t);
1361c40487d4SMatt Macy 				dst_iovecs[vec].iov_base = (char *)
1362eda14cbcSMatt Macy 				    dlrp + sizeof (lr_write_t);
1363c40487d4SMatt Macy 				dst_iovecs[vec].iov_len = crypt_len;
1364c40487d4SMatt Macy 				vec++;
1365eda14cbcSMatt Macy 				total_len += crypt_len;
1366eda14cbcSMatt Macy 			}
13672276e539SMartin Matuska 		} else if (txtype == TX_CLONE_RANGE) {
13682276e539SMartin Matuska 			const size_t o = offsetof(lr_clone_range_t, lr_nbps);
13692276e539SMartin Matuska 			crypt_len = o - sizeof (lr_t);
13702276e539SMartin Matuska 			dst_iovecs[vec].iov_base = (char *)dlrp + sizeof (lr_t);
13712276e539SMartin Matuska 			dst_iovecs[vec].iov_len = crypt_len;
13722276e539SMartin Matuska 
13732276e539SMartin Matuska 			/* copy the bps now since they will not be encrypted */
13742276e539SMartin Matuska 			memcpy(dlrp + o, slrp + o, lr_len - o);
13752276e539SMartin Matuska 			memcpy(aadp, slrp + o, lr_len - o);
13762276e539SMartin Matuska 			aadp += lr_len - o;
13772276e539SMartin Matuska 			aad_len += lr_len - o;
13782276e539SMartin Matuska 			vec++;
13792276e539SMartin Matuska 			total_len += crypt_len;
1380eda14cbcSMatt Macy 		} else {
1381eda14cbcSMatt Macy 			crypt_len = lr_len - sizeof (lr_t);
13822276e539SMartin Matuska 			dst_iovecs[vec].iov_base = (char *)dlrp + sizeof (lr_t);
1383c40487d4SMatt Macy 			dst_iovecs[vec].iov_len = crypt_len;
1384c40487d4SMatt Macy 			vec++;
1385eda14cbcSMatt Macy 			total_len += crypt_len;
1386eda14cbcSMatt Macy 		}
1387eda14cbcSMatt Macy 	}
1388eda14cbcSMatt Macy 
1389c40487d4SMatt Macy 	/* The last iovec will contain the MAC. */
1390c40487d4SMatt Macy 	ASSERT3U(vec, ==, nr_iovecs - 1);
1391c40487d4SMatt Macy 
1392c40487d4SMatt Macy 	/* AAD */
1393c40487d4SMatt Macy 	dst_iovecs[0].iov_base = aadbuf;
1394c40487d4SMatt Macy 	dst_iovecs[0].iov_len = aad_len;
1395c40487d4SMatt Macy 	/* MAC */
1396c40487d4SMatt Macy 	dst_iovecs[vec].iov_base = 0;
1397c40487d4SMatt Macy 	dst_iovecs[vec].iov_len = 0;
1398c40487d4SMatt Macy 
1399c40487d4SMatt Macy 	*no_crypt = (vec == 1);
1400eda14cbcSMatt Macy 	*enc_len = total_len;
1401eda14cbcSMatt Macy 	*authbuf = aadbuf;
1402eda14cbcSMatt Macy 	*auth_len = aad_len;
1403184c1b94SMartin Matuska 	GET_UIO_STRUCT(out_uio)->uio_iov = dst_iovecs;
1404184c1b94SMartin Matuska 	zfs_uio_iovcnt(out_uio) = nr_iovecs;
1405eda14cbcSMatt Macy 
1406eda14cbcSMatt Macy 	return (0);
1407eda14cbcSMatt Macy }
1408eda14cbcSMatt Macy 
1409eda14cbcSMatt Macy /*
1410eda14cbcSMatt Macy  * Special case handling routine for encrypting / decrypting dnode blocks.
1411eda14cbcSMatt Macy  */
1412eda14cbcSMatt Macy static int
1413eda14cbcSMatt Macy zio_crypt_init_uios_dnode(boolean_t encrypt, uint64_t version,
1414eda14cbcSMatt Macy     uint8_t *plainbuf, uint8_t *cipherbuf, uint_t datalen, boolean_t byteswap,
1415184c1b94SMartin Matuska     zfs_uio_t *puio, zfs_uio_t *out_uio, uint_t *enc_len, uint8_t **authbuf,
1416eda14cbcSMatt Macy     uint_t *auth_len, boolean_t *no_crypt)
1417eda14cbcSMatt Macy {
1418c40487d4SMatt Macy 	uint8_t *aadbuf = zio_buf_alloc(datalen);
1419eda14cbcSMatt Macy 	uint8_t *src, *dst, *aadp;
1420eda14cbcSMatt Macy 	dnode_phys_t *dnp, *adnp, *sdnp, *ddnp;
1421c40487d4SMatt Macy 	iovec_t *dst_iovecs;
1422c40487d4SMatt Macy 	uint_t nr_iovecs, crypt_len, vec;
1423c40487d4SMatt Macy 	uint_t aad_len = 0, total_len = 0;
1424c40487d4SMatt Macy 	uint_t i, j, max_dnp = datalen >> DNODE_SHIFT;
1425eda14cbcSMatt Macy 
1426eda14cbcSMatt Macy 	if (encrypt) {
1427eda14cbcSMatt Macy 		src = plainbuf;
1428eda14cbcSMatt Macy 		dst = cipherbuf;
1429eda14cbcSMatt Macy 	} else {
1430eda14cbcSMatt Macy 		src = cipherbuf;
1431eda14cbcSMatt Macy 		dst = plainbuf;
1432eda14cbcSMatt Macy 	}
1433da5137abSMartin Matuska 	memcpy(dst, src, datalen);
1434eda14cbcSMatt Macy 
1435eda14cbcSMatt Macy 	sdnp = (dnode_phys_t *)src;
1436eda14cbcSMatt Macy 	ddnp = (dnode_phys_t *)dst;
1437eda14cbcSMatt Macy 	aadp = aadbuf;
1438eda14cbcSMatt Macy 
1439eda14cbcSMatt Macy 	/*
1440eda14cbcSMatt Macy 	 * Count the number of iovecs we will need to do the encryption by
1441eda14cbcSMatt Macy 	 * counting the number of bonus buffers that need to be encrypted.
1442eda14cbcSMatt Macy 	 */
1443c40487d4SMatt Macy 
1444c40487d4SMatt Macy 	/* We need at least two iovecs -- one for the AAD, one for the MAC. */
1445c40487d4SMatt Macy 	nr_iovecs = 2;
1446c40487d4SMatt Macy 
1447eda14cbcSMatt Macy 	for (i = 0; i < max_dnp; i += sdnp[i].dn_extra_slots + 1) {
1448eda14cbcSMatt Macy 		/*
1449eda14cbcSMatt Macy 		 * This block may still be byteswapped. However, all of the
1450eda14cbcSMatt Macy 		 * values we use are either uint8_t's (for which byteswapping
1451eda14cbcSMatt Macy 		 * is a noop) or a * != 0 check, which will work regardless
1452eda14cbcSMatt Macy 		 * of whether or not we byteswap.
1453eda14cbcSMatt Macy 		 */
1454eda14cbcSMatt Macy 		if (sdnp[i].dn_type != DMU_OT_NONE &&
1455eda14cbcSMatt Macy 		    DMU_OT_IS_ENCRYPTED(sdnp[i].dn_bonustype) &&
1456eda14cbcSMatt Macy 		    sdnp[i].dn_bonuslen != 0) {
1457eda14cbcSMatt Macy 			nr_iovecs++;
1458eda14cbcSMatt Macy 		}
1459eda14cbcSMatt Macy 	}
1460eda14cbcSMatt Macy 
1461c40487d4SMatt Macy 	dst_iovecs = kmem_alloc(nr_iovecs * sizeof (iovec_t), KM_SLEEP);
1462eda14cbcSMatt Macy 
1463eda14cbcSMatt Macy 	/*
1464eda14cbcSMatt Macy 	 * Iterate through the dnodes again, this time filling in the uios
1465eda14cbcSMatt Macy 	 * we allocated earlier. We also concatenate any data we want to
1466eda14cbcSMatt Macy 	 * authenticate onto aadbuf.
1467eda14cbcSMatt Macy 	 */
1468c40487d4SMatt Macy 
1469c40487d4SMatt Macy 	/* The first iovec will contain the authbuf. */
1470c40487d4SMatt Macy 	vec = 1;
1471c40487d4SMatt Macy 
1472eda14cbcSMatt Macy 	for (i = 0; i < max_dnp; i += sdnp[i].dn_extra_slots + 1) {
1473eda14cbcSMatt Macy 		dnp = &sdnp[i];
1474eda14cbcSMatt Macy 
1475eda14cbcSMatt Macy 		/* copy over the core fields and blkptrs (kept as plaintext) */
1476da5137abSMartin Matuska 		memcpy(&ddnp[i], dnp,
1477da5137abSMartin Matuska 		    (uint8_t *)DN_BONUS(dnp) - (uint8_t *)dnp);
1478eda14cbcSMatt Macy 
1479eda14cbcSMatt Macy 		if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
1480da5137abSMartin Matuska 			memcpy(DN_SPILL_BLKPTR(&ddnp[i]), DN_SPILL_BLKPTR(dnp),
1481eda14cbcSMatt Macy 			    sizeof (blkptr_t));
1482eda14cbcSMatt Macy 		}
1483eda14cbcSMatt Macy 
1484eda14cbcSMatt Macy 		/*
1485eda14cbcSMatt Macy 		 * Handle authenticated data. We authenticate everything in
1486eda14cbcSMatt Macy 		 * the dnode that can be brought over when we do a raw send.
1487eda14cbcSMatt Macy 		 * This includes all of the core fields as well as the MACs
1488eda14cbcSMatt Macy 		 * stored in the bp checksums and all of the portable bits
1489eda14cbcSMatt Macy 		 * from blk_prop. We include the dnode padding here in case it
1490eda14cbcSMatt Macy 		 * ever gets used in the future. Some dn_flags and dn_used are
1491eda14cbcSMatt Macy 		 * not portable so we mask those out values out of the
1492eda14cbcSMatt Macy 		 * authenticated data.
1493eda14cbcSMatt Macy 		 */
1494eda14cbcSMatt Macy 		crypt_len = offsetof(dnode_phys_t, dn_blkptr);
1495da5137abSMartin Matuska 		memcpy(aadp, dnp, crypt_len);
1496eda14cbcSMatt Macy 		adnp = (dnode_phys_t *)aadp;
1497eda14cbcSMatt Macy 		adnp->dn_flags &= DNODE_CRYPT_PORTABLE_FLAGS_MASK;
1498eda14cbcSMatt Macy 		adnp->dn_used = 0;
1499eda14cbcSMatt Macy 		aadp += crypt_len;
1500eda14cbcSMatt Macy 		aad_len += crypt_len;
1501eda14cbcSMatt Macy 
1502eda14cbcSMatt Macy 		for (j = 0; j < dnp->dn_nblkptr; j++) {
1503eda14cbcSMatt Macy 			zio_crypt_bp_do_aad_updates(&aadp, &aad_len,
1504eda14cbcSMatt Macy 			    version, byteswap, &dnp->dn_blkptr[j]);
1505eda14cbcSMatt Macy 		}
1506eda14cbcSMatt Macy 
1507eda14cbcSMatt Macy 		if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
1508eda14cbcSMatt Macy 			zio_crypt_bp_do_aad_updates(&aadp, &aad_len,
1509eda14cbcSMatt Macy 			    version, byteswap, DN_SPILL_BLKPTR(dnp));
1510eda14cbcSMatt Macy 		}
1511eda14cbcSMatt Macy 
1512eda14cbcSMatt Macy 		/*
1513eda14cbcSMatt Macy 		 * If this bonus buffer needs to be encrypted, we prepare an
1514eda14cbcSMatt Macy 		 * iovec_t. The encryption / decryption functions will fill
1515eda14cbcSMatt Macy 		 * this in for us with the encrypted or decrypted data.
1516eda14cbcSMatt Macy 		 * Otherwise we add the bonus buffer to the authenticated
1517eda14cbcSMatt Macy 		 * data buffer and copy it over to the destination. The
1518eda14cbcSMatt Macy 		 * encrypted iovec extends to DN_MAX_BONUS_LEN(dnp) so that
1519eda14cbcSMatt Macy 		 * we can guarantee alignment with the AES block size
1520eda14cbcSMatt Macy 		 * (128 bits).
1521eda14cbcSMatt Macy 		 */
1522eda14cbcSMatt Macy 		crypt_len = DN_MAX_BONUS_LEN(dnp);
1523eda14cbcSMatt Macy 		if (dnp->dn_type != DMU_OT_NONE &&
1524eda14cbcSMatt Macy 		    DMU_OT_IS_ENCRYPTED(dnp->dn_bonustype) &&
1525eda14cbcSMatt Macy 		    dnp->dn_bonuslen != 0) {
1526c40487d4SMatt Macy 			dst_iovecs[vec].iov_base = DN_BONUS(&ddnp[i]);
1527c40487d4SMatt Macy 			dst_iovecs[vec].iov_len = crypt_len;
1528eda14cbcSMatt Macy 
1529c40487d4SMatt Macy 			vec++;
1530eda14cbcSMatt Macy 			total_len += crypt_len;
1531eda14cbcSMatt Macy 		} else {
1532da5137abSMartin Matuska 			memcpy(DN_BONUS(&ddnp[i]), DN_BONUS(dnp), crypt_len);
1533da5137abSMartin Matuska 			memcpy(aadp, DN_BONUS(dnp), crypt_len);
1534eda14cbcSMatt Macy 			aadp += crypt_len;
1535eda14cbcSMatt Macy 			aad_len += crypt_len;
1536eda14cbcSMatt Macy 		}
1537eda14cbcSMatt Macy 	}
1538eda14cbcSMatt Macy 
1539c40487d4SMatt Macy 	/* The last iovec will contain the MAC. */
1540c40487d4SMatt Macy 	ASSERT3U(vec, ==, nr_iovecs - 1);
1541c40487d4SMatt Macy 
1542c40487d4SMatt Macy 	/* AAD */
1543c40487d4SMatt Macy 	dst_iovecs[0].iov_base = aadbuf;
1544c40487d4SMatt Macy 	dst_iovecs[0].iov_len = aad_len;
1545c40487d4SMatt Macy 	/* MAC */
1546c40487d4SMatt Macy 	dst_iovecs[vec].iov_base = 0;
1547c40487d4SMatt Macy 	dst_iovecs[vec].iov_len = 0;
1548c40487d4SMatt Macy 
1549c40487d4SMatt Macy 	*no_crypt = (vec == 1);
1550eda14cbcSMatt Macy 	*enc_len = total_len;
1551eda14cbcSMatt Macy 	*authbuf = aadbuf;
1552eda14cbcSMatt Macy 	*auth_len = aad_len;
1553184c1b94SMartin Matuska 	GET_UIO_STRUCT(out_uio)->uio_iov = dst_iovecs;
1554184c1b94SMartin Matuska 	zfs_uio_iovcnt(out_uio) = nr_iovecs;
1555eda14cbcSMatt Macy 
1556eda14cbcSMatt Macy 	return (0);
1557eda14cbcSMatt Macy }
1558eda14cbcSMatt Macy 
1559eda14cbcSMatt Macy static int
1560eda14cbcSMatt Macy zio_crypt_init_uios_normal(boolean_t encrypt, uint8_t *plainbuf,
1561184c1b94SMartin Matuska     uint8_t *cipherbuf, uint_t datalen, zfs_uio_t *puio, zfs_uio_t *out_uio,
1562eda14cbcSMatt Macy     uint_t *enc_len)
1563eda14cbcSMatt Macy {
1564e92ffd9bSMartin Matuska 	(void) puio;
1565eda14cbcSMatt Macy 	int ret;
1566eda14cbcSMatt Macy 	uint_t nr_plain = 1, nr_cipher = 2;
1567eda14cbcSMatt Macy 	iovec_t *plain_iovecs = NULL, *cipher_iovecs = NULL;
1568eda14cbcSMatt Macy 	void *src, *dst;
1569eda14cbcSMatt Macy 
157015f0b8c3SMartin Matuska 	cipher_iovecs = kmem_zalloc(nr_cipher * sizeof (iovec_t),
1571eda14cbcSMatt Macy 	    KM_SLEEP);
1572eda14cbcSMatt Macy 	if (!cipher_iovecs) {
1573eda14cbcSMatt Macy 		ret = SET_ERROR(ENOMEM);
1574eda14cbcSMatt Macy 		goto error;
1575eda14cbcSMatt Macy 	}
1576eda14cbcSMatt Macy 
1577eda14cbcSMatt Macy 	if (encrypt) {
1578eda14cbcSMatt Macy 		src = plainbuf;
1579eda14cbcSMatt Macy 		dst = cipherbuf;
1580eda14cbcSMatt Macy 	} else {
1581eda14cbcSMatt Macy 		src = cipherbuf;
1582eda14cbcSMatt Macy 		dst = plainbuf;
1583eda14cbcSMatt Macy 	}
1584da5137abSMartin Matuska 	memcpy(dst, src, datalen);
1585eda14cbcSMatt Macy 	cipher_iovecs[0].iov_base = dst;
1586eda14cbcSMatt Macy 	cipher_iovecs[0].iov_len = datalen;
1587eda14cbcSMatt Macy 
1588eda14cbcSMatt Macy 	*enc_len = datalen;
1589184c1b94SMartin Matuska 	GET_UIO_STRUCT(out_uio)->uio_iov = cipher_iovecs;
1590184c1b94SMartin Matuska 	zfs_uio_iovcnt(out_uio) = nr_cipher;
1591eda14cbcSMatt Macy 
1592eda14cbcSMatt Macy 	return (0);
1593eda14cbcSMatt Macy 
1594eda14cbcSMatt Macy error:
1595eda14cbcSMatt Macy 	if (plain_iovecs != NULL)
1596eda14cbcSMatt Macy 		kmem_free(plain_iovecs, nr_plain * sizeof (iovec_t));
1597eda14cbcSMatt Macy 	if (cipher_iovecs != NULL)
1598eda14cbcSMatt Macy 		kmem_free(cipher_iovecs, nr_cipher * sizeof (iovec_t));
1599eda14cbcSMatt Macy 
1600eda14cbcSMatt Macy 	*enc_len = 0;
1601184c1b94SMartin Matuska 	GET_UIO_STRUCT(out_uio)->uio_iov = NULL;
1602184c1b94SMartin Matuska 	zfs_uio_iovcnt(out_uio) = 0;
1603eda14cbcSMatt Macy 
1604eda14cbcSMatt Macy 	return (ret);
1605eda14cbcSMatt Macy }
1606eda14cbcSMatt Macy 
1607eda14cbcSMatt Macy /*
1608eda14cbcSMatt Macy  * This function builds up the plaintext (puio) and ciphertext (cuio) uios so
1609eda14cbcSMatt Macy  * that they can be used for encryption and decryption by zio_do_crypt_uio().
1610eda14cbcSMatt Macy  * Most blocks will use zio_crypt_init_uios_normal(), with ZIL and dnode blocks
1611eda14cbcSMatt Macy  * requiring special handling to parse out pieces that are to be encrypted. The
1612eda14cbcSMatt Macy  * authbuf is used by these special cases to store additional authenticated
1613eda14cbcSMatt Macy  * data (AAD) for the encryption modes.
1614eda14cbcSMatt Macy  */
1615eda14cbcSMatt Macy static int
1616eda14cbcSMatt Macy zio_crypt_init_uios(boolean_t encrypt, uint64_t version, dmu_object_type_t ot,
1617eda14cbcSMatt Macy     uint8_t *plainbuf, uint8_t *cipherbuf, uint_t datalen, boolean_t byteswap,
1618184c1b94SMartin Matuska     uint8_t *mac, zfs_uio_t *puio, zfs_uio_t *cuio, uint_t *enc_len,
1619184c1b94SMartin Matuska     uint8_t **authbuf, uint_t *auth_len, boolean_t *no_crypt)
1620eda14cbcSMatt Macy {
1621eda14cbcSMatt Macy 	int ret;
1622eda14cbcSMatt Macy 	iovec_t *mac_iov;
1623eda14cbcSMatt Macy 
1624eda14cbcSMatt Macy 	ASSERT(DMU_OT_IS_ENCRYPTED(ot) || ot == DMU_OT_NONE);
1625eda14cbcSMatt Macy 
1626eda14cbcSMatt Macy 	/* route to handler */
1627eda14cbcSMatt Macy 	switch (ot) {
1628eda14cbcSMatt Macy 	case DMU_OT_INTENT_LOG:
1629eda14cbcSMatt Macy 		ret = zio_crypt_init_uios_zil(encrypt, plainbuf, cipherbuf,
1630eda14cbcSMatt Macy 		    datalen, byteswap, puio, cuio, enc_len, authbuf, auth_len,
1631eda14cbcSMatt Macy 		    no_crypt);
1632eda14cbcSMatt Macy 		break;
1633eda14cbcSMatt Macy 	case DMU_OT_DNODE:
1634eda14cbcSMatt Macy 		ret = zio_crypt_init_uios_dnode(encrypt, version, plainbuf,
1635eda14cbcSMatt Macy 		    cipherbuf, datalen, byteswap, puio, cuio, enc_len, authbuf,
1636eda14cbcSMatt Macy 		    auth_len, no_crypt);
1637eda14cbcSMatt Macy 		break;
1638eda14cbcSMatt Macy 	default:
1639eda14cbcSMatt Macy 		ret = zio_crypt_init_uios_normal(encrypt, plainbuf, cipherbuf,
1640eda14cbcSMatt Macy 		    datalen, puio, cuio, enc_len);
1641eda14cbcSMatt Macy 		*authbuf = NULL;
1642eda14cbcSMatt Macy 		*auth_len = 0;
1643eda14cbcSMatt Macy 		*no_crypt = B_FALSE;
1644eda14cbcSMatt Macy 		break;
1645eda14cbcSMatt Macy 	}
1646eda14cbcSMatt Macy 
1647eda14cbcSMatt Macy 	if (ret != 0)
1648eda14cbcSMatt Macy 		goto error;
1649eda14cbcSMatt Macy 
1650eda14cbcSMatt Macy 	/* populate the uios */
1651184c1b94SMartin Matuska 	zfs_uio_segflg(cuio) = UIO_SYSSPACE;
1652eda14cbcSMatt Macy 
1653184c1b94SMartin Matuska 	mac_iov =
1654184c1b94SMartin Matuska 	    ((iovec_t *)&(GET_UIO_STRUCT(cuio)->
1655184c1b94SMartin Matuska 	    uio_iov[zfs_uio_iovcnt(cuio) - 1]));
1656eda14cbcSMatt Macy 	mac_iov->iov_base = (void *)mac;
1657eda14cbcSMatt Macy 	mac_iov->iov_len = ZIO_DATA_MAC_LEN;
1658eda14cbcSMatt Macy 
1659eda14cbcSMatt Macy 	return (0);
1660eda14cbcSMatt Macy 
1661eda14cbcSMatt Macy error:
1662eda14cbcSMatt Macy 	return (ret);
1663eda14cbcSMatt Macy }
1664eda14cbcSMatt Macy 
1665eda14cbcSMatt Macy void *failed_decrypt_buf;
1666eda14cbcSMatt Macy int faile_decrypt_size;
1667eda14cbcSMatt Macy 
1668eda14cbcSMatt Macy /*
1669eda14cbcSMatt Macy  * Primary encryption / decryption entrypoint for zio data.
1670eda14cbcSMatt Macy  */
1671eda14cbcSMatt Macy int
1672eda14cbcSMatt Macy zio_do_crypt_data(boolean_t encrypt, zio_crypt_key_t *key,
1673eda14cbcSMatt Macy     dmu_object_type_t ot, boolean_t byteswap, uint8_t *salt, uint8_t *iv,
1674eda14cbcSMatt Macy     uint8_t *mac, uint_t datalen, uint8_t *plainbuf, uint8_t *cipherbuf,
1675eda14cbcSMatt Macy     boolean_t *no_crypt)
1676eda14cbcSMatt Macy {
1677eda14cbcSMatt Macy 	int ret;
1678eda14cbcSMatt Macy 	boolean_t locked = B_FALSE;
1679eda14cbcSMatt Macy 	uint64_t crypt = key->zk_crypt;
1680eda14cbcSMatt Macy 	uint_t keydata_len = zio_crypt_table[crypt].ci_keylen;
1681eda14cbcSMatt Macy 	uint_t enc_len, auth_len;
1682184c1b94SMartin Matuska 	zfs_uio_t puio, cuio;
1683184c1b94SMartin Matuska 	struct uio puio_s, cuio_s;
1684eda14cbcSMatt Macy 	uint8_t enc_keydata[MASTER_KEY_MAX_LEN];
1685eda14cbcSMatt Macy 	crypto_key_t tmp_ckey, *ckey = NULL;
1686eda14cbcSMatt Macy 	freebsd_crypt_session_t *tmpl = NULL;
1687eda14cbcSMatt Macy 	uint8_t *authbuf = NULL;
1688eda14cbcSMatt Macy 
1689*3ceba58aSDimitry Andric 	memset(&puio_s, 0, sizeof (puio_s));
1690*3ceba58aSDimitry Andric 	memset(&cuio_s, 0, sizeof (cuio_s));
1691184c1b94SMartin Matuska 	zfs_uio_init(&puio, &puio_s);
1692184c1b94SMartin Matuska 	zfs_uio_init(&cuio, &cuio_s);
1693eda14cbcSMatt Macy 
1694eda14cbcSMatt Macy #ifdef FCRYPTO_DEBUG
1695eda14cbcSMatt Macy 	printf("%s(%s, %p, %p, %d, %p, %p, %u, %s, %p, %p, %p)\n",
1696eda14cbcSMatt Macy 	    __FUNCTION__,
1697eda14cbcSMatt Macy 	    encrypt ? "encrypt" : "decrypt",
1698eda14cbcSMatt Macy 	    key, salt, ot, iv, mac, datalen,
1699eda14cbcSMatt Macy 	    byteswap ? "byteswap" : "native_endian", plainbuf,
1700eda14cbcSMatt Macy 	    cipherbuf, no_crypt);
1701eda14cbcSMatt Macy 
1702eda14cbcSMatt Macy 	printf("\tkey = {");
1703eda14cbcSMatt Macy 	for (int i = 0; i < key->zk_current_key.ck_length/8; i++)
1704eda14cbcSMatt Macy 		printf("%02x ", ((uint8_t *)key->zk_current_key.ck_data)[i]);
1705eda14cbcSMatt Macy 	printf("}\n");
1706eda14cbcSMatt Macy #endif
1707eda14cbcSMatt Macy 	/* create uios for encryption */
1708eda14cbcSMatt Macy 	ret = zio_crypt_init_uios(encrypt, key->zk_version, ot, plainbuf,
1709eda14cbcSMatt Macy 	    cipherbuf, datalen, byteswap, mac, &puio, &cuio, &enc_len,
1710eda14cbcSMatt Macy 	    &authbuf, &auth_len, no_crypt);
1711eda14cbcSMatt Macy 	if (ret != 0)
1712eda14cbcSMatt Macy 		return (ret);
1713eda14cbcSMatt Macy 
1714eda14cbcSMatt Macy 	/*
1715eda14cbcSMatt Macy 	 * If the needed key is the current one, just use it. Otherwise we
1716eda14cbcSMatt Macy 	 * need to generate a temporary one from the given salt + master key.
1717eda14cbcSMatt Macy 	 * If we are encrypting, we must return a copy of the current salt
1718eda14cbcSMatt Macy 	 * so that it can be stored in the blkptr_t.
1719eda14cbcSMatt Macy 	 */
1720eda14cbcSMatt Macy 	rw_enter(&key->zk_salt_lock, RW_READER);
1721eda14cbcSMatt Macy 	locked = B_TRUE;
1722eda14cbcSMatt Macy 
1723da5137abSMartin Matuska 	if (memcmp(salt, key->zk_salt, ZIO_DATA_SALT_LEN) == 0) {
1724eda14cbcSMatt Macy 		ckey = &key->zk_current_key;
1725eda14cbcSMatt Macy 		tmpl = &key->zk_session;
1726eda14cbcSMatt Macy 	} else {
1727eda14cbcSMatt Macy 		rw_exit(&key->zk_salt_lock);
1728eda14cbcSMatt Macy 		locked = B_FALSE;
1729eda14cbcSMatt Macy 
1730eda14cbcSMatt Macy 		ret = hkdf_sha512(key->zk_master_keydata, keydata_len, NULL, 0,
1731eda14cbcSMatt Macy 		    salt, ZIO_DATA_SALT_LEN, enc_keydata, keydata_len);
1732eda14cbcSMatt Macy 		if (ret != 0)
1733eda14cbcSMatt Macy 			goto error;
1734eda14cbcSMatt Macy 		tmp_ckey.ck_data = enc_keydata;
1735eda14cbcSMatt Macy 		tmp_ckey.ck_length = CRYPTO_BYTES2BITS(keydata_len);
1736eda14cbcSMatt Macy 
1737eda14cbcSMatt Macy 		ckey = &tmp_ckey;
1738eda14cbcSMatt Macy 		tmpl = NULL;
1739eda14cbcSMatt Macy 	}
1740eda14cbcSMatt Macy 
1741eda14cbcSMatt Macy 	/* perform the encryption / decryption */
1742eda14cbcSMatt Macy 	ret = zio_do_crypt_uio_opencrypto(encrypt, tmpl, key->zk_crypt,
1743eda14cbcSMatt Macy 	    ckey, iv, enc_len, &cuio, auth_len);
1744eda14cbcSMatt Macy 	if (ret != 0)
1745eda14cbcSMatt Macy 		goto error;
1746eda14cbcSMatt Macy 	if (locked) {
1747eda14cbcSMatt Macy 		rw_exit(&key->zk_salt_lock);
1748eda14cbcSMatt Macy 	}
1749eda14cbcSMatt Macy 
1750eda14cbcSMatt Macy 	if (authbuf != NULL)
1751eda14cbcSMatt Macy 		zio_buf_free(authbuf, datalen);
1752eda14cbcSMatt Macy 	if (ckey == &tmp_ckey)
1753da5137abSMartin Matuska 		memset(enc_keydata, 0, keydata_len);
1754eda14cbcSMatt Macy 	zio_crypt_destroy_uio(&puio);
1755eda14cbcSMatt Macy 	zio_crypt_destroy_uio(&cuio);
1756eda14cbcSMatt Macy 
1757eda14cbcSMatt Macy 	return (0);
1758eda14cbcSMatt Macy 
1759eda14cbcSMatt Macy error:
1760eda14cbcSMatt Macy 	if (!encrypt) {
1761eda14cbcSMatt Macy 		if (failed_decrypt_buf != NULL)
1762eda14cbcSMatt Macy 			kmem_free(failed_decrypt_buf, failed_decrypt_size);
1763eda14cbcSMatt Macy 		failed_decrypt_buf = kmem_alloc(datalen, KM_SLEEP);
1764eda14cbcSMatt Macy 		failed_decrypt_size = datalen;
1765da5137abSMartin Matuska 		memcpy(failed_decrypt_buf, cipherbuf, datalen);
1766eda14cbcSMatt Macy 	}
1767eda14cbcSMatt Macy 	if (locked)
1768eda14cbcSMatt Macy 		rw_exit(&key->zk_salt_lock);
1769eda14cbcSMatt Macy 	if (authbuf != NULL)
1770eda14cbcSMatt Macy 		zio_buf_free(authbuf, datalen);
1771eda14cbcSMatt Macy 	if (ckey == &tmp_ckey)
1772da5137abSMartin Matuska 		memset(enc_keydata, 0, keydata_len);
1773eda14cbcSMatt Macy 	zio_crypt_destroy_uio(&puio);
1774eda14cbcSMatt Macy 	zio_crypt_destroy_uio(&cuio);
1775eda14cbcSMatt Macy 	return (SET_ERROR(ret));
1776eda14cbcSMatt Macy }
1777eda14cbcSMatt Macy 
1778eda14cbcSMatt Macy /*
1779eda14cbcSMatt Macy  * Simple wrapper around zio_do_crypt_data() to work with abd's instead of
1780eda14cbcSMatt Macy  * linear buffers.
1781eda14cbcSMatt Macy  */
1782eda14cbcSMatt Macy int
1783eda14cbcSMatt Macy zio_do_crypt_abd(boolean_t encrypt, zio_crypt_key_t *key, dmu_object_type_t ot,
1784eda14cbcSMatt Macy     boolean_t byteswap, uint8_t *salt, uint8_t *iv, uint8_t *mac,
1785eda14cbcSMatt Macy     uint_t datalen, abd_t *pabd, abd_t *cabd, boolean_t *no_crypt)
1786eda14cbcSMatt Macy {
1787eda14cbcSMatt Macy 	int ret;
1788eda14cbcSMatt Macy 	void *ptmp, *ctmp;
1789eda14cbcSMatt Macy 
1790eda14cbcSMatt Macy 	if (encrypt) {
1791eda14cbcSMatt Macy 		ptmp = abd_borrow_buf_copy(pabd, datalen);
1792eda14cbcSMatt Macy 		ctmp = abd_borrow_buf(cabd, datalen);
1793eda14cbcSMatt Macy 	} else {
1794eda14cbcSMatt Macy 		ptmp = abd_borrow_buf(pabd, datalen);
1795eda14cbcSMatt Macy 		ctmp = abd_borrow_buf_copy(cabd, datalen);
1796eda14cbcSMatt Macy 	}
1797eda14cbcSMatt Macy 
1798eda14cbcSMatt Macy 	ret = zio_do_crypt_data(encrypt, key, ot, byteswap, salt, iv, mac,
1799eda14cbcSMatt Macy 	    datalen, ptmp, ctmp, no_crypt);
1800eda14cbcSMatt Macy 	if (ret != 0)
1801eda14cbcSMatt Macy 		goto error;
1802eda14cbcSMatt Macy 
1803eda14cbcSMatt Macy 	if (encrypt) {
1804eda14cbcSMatt Macy 		abd_return_buf(pabd, ptmp, datalen);
1805eda14cbcSMatt Macy 		abd_return_buf_copy(cabd, ctmp, datalen);
1806eda14cbcSMatt Macy 	} else {
1807eda14cbcSMatt Macy 		abd_return_buf_copy(pabd, ptmp, datalen);
1808eda14cbcSMatt Macy 		abd_return_buf(cabd, ctmp, datalen);
1809eda14cbcSMatt Macy 	}
1810eda14cbcSMatt Macy 
1811eda14cbcSMatt Macy 	return (0);
1812eda14cbcSMatt Macy 
1813eda14cbcSMatt Macy error:
1814eda14cbcSMatt Macy 	if (encrypt) {
1815eda14cbcSMatt Macy 		abd_return_buf(pabd, ptmp, datalen);
1816eda14cbcSMatt Macy 		abd_return_buf_copy(cabd, ctmp, datalen);
1817eda14cbcSMatt Macy 	} else {
1818eda14cbcSMatt Macy 		abd_return_buf_copy(pabd, ptmp, datalen);
1819eda14cbcSMatt Macy 		abd_return_buf(cabd, ctmp, datalen);
1820eda14cbcSMatt Macy 	}
1821eda14cbcSMatt Macy 
1822eda14cbcSMatt Macy 	return (SET_ERROR(ret));
1823eda14cbcSMatt Macy }
1824eda14cbcSMatt Macy 
1825eda14cbcSMatt Macy #if defined(_KERNEL) && defined(HAVE_SPL)
1826eda14cbcSMatt Macy module_param(zfs_key_max_salt_uses, ulong, 0644);
1827eda14cbcSMatt Macy MODULE_PARM_DESC(zfs_key_max_salt_uses, "Max number of times a salt value "
1828eda14cbcSMatt Macy 	"can be used for generating encryption keys before it is rotated");
1829eda14cbcSMatt Macy #endif
1830