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