xref: /freebsd/sys/contrib/openzfs/module/icp/algs/modes/ccm.c (revision 13ec1e3155c7e9bf037b12af186351b7fa9b9450)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/zfs_context.h>
27 #include <modes/modes.h>
28 #include <sys/crypto/common.h>
29 #include <sys/crypto/impl.h>
30 
31 #ifdef HAVE_EFFICIENT_UNALIGNED_ACCESS
32 #include <sys/byteorder.h>
33 #define	UNALIGNED_POINTERS_PERMITTED
34 #endif
35 
36 /*
37  * Encrypt multiple blocks of data in CCM mode.  Decrypt for CCM mode
38  * is done in another function.
39  */
40 int
41 ccm_mode_encrypt_contiguous_blocks(ccm_ctx_t *ctx, char *data, size_t length,
42     crypto_data_t *out, size_t block_size,
43     int (*encrypt_block)(const void *, const uint8_t *, uint8_t *),
44     void (*copy_block)(uint8_t *, uint8_t *),
45     void (*xor_block)(uint8_t *, uint8_t *))
46 {
47 	size_t remainder = length;
48 	size_t need = 0;
49 	uint8_t *datap = (uint8_t *)data;
50 	uint8_t *blockp;
51 	uint8_t *lastp;
52 	void *iov_or_mp;
53 	offset_t offset;
54 	uint8_t *out_data_1;
55 	uint8_t *out_data_2;
56 	size_t out_data_1_len;
57 	uint64_t counter;
58 	uint8_t *mac_buf;
59 
60 	if (length + ctx->ccm_remainder_len < block_size) {
61 		/* accumulate bytes here and return */
62 		bcopy(datap,
63 		    (uint8_t *)ctx->ccm_remainder + ctx->ccm_remainder_len,
64 		    length);
65 		ctx->ccm_remainder_len += length;
66 		ctx->ccm_copy_to = datap;
67 		return (CRYPTO_SUCCESS);
68 	}
69 
70 	lastp = (uint8_t *)ctx->ccm_cb;
71 	crypto_init_ptrs(out, &iov_or_mp, &offset);
72 
73 	mac_buf = (uint8_t *)ctx->ccm_mac_buf;
74 
75 	do {
76 		/* Unprocessed data from last call. */
77 		if (ctx->ccm_remainder_len > 0) {
78 			need = block_size - ctx->ccm_remainder_len;
79 
80 			if (need > remainder)
81 				return (CRYPTO_DATA_LEN_RANGE);
82 
83 			bcopy(datap, &((uint8_t *)ctx->ccm_remainder)
84 			    [ctx->ccm_remainder_len], need);
85 
86 			blockp = (uint8_t *)ctx->ccm_remainder;
87 		} else {
88 			blockp = datap;
89 		}
90 
91 		/*
92 		 * do CBC MAC
93 		 *
94 		 * XOR the previous cipher block current clear block.
95 		 * mac_buf always contain previous cipher block.
96 		 */
97 		xor_block(blockp, mac_buf);
98 		encrypt_block(ctx->ccm_keysched, mac_buf, mac_buf);
99 
100 		/* ccm_cb is the counter block */
101 		encrypt_block(ctx->ccm_keysched, (uint8_t *)ctx->ccm_cb,
102 		    (uint8_t *)ctx->ccm_tmp);
103 
104 		lastp = (uint8_t *)ctx->ccm_tmp;
105 
106 		/*
107 		 * Increment counter. Counter bits are confined
108 		 * to the bottom 64 bits of the counter block.
109 		 */
110 #ifdef _ZFS_LITTLE_ENDIAN
111 		counter = ntohll(ctx->ccm_cb[1] & ctx->ccm_counter_mask);
112 		counter = htonll(counter + 1);
113 #else
114 		counter = ctx->ccm_cb[1] & ctx->ccm_counter_mask;
115 		counter++;
116 #endif	/* _ZFS_LITTLE_ENDIAN */
117 		counter &= ctx->ccm_counter_mask;
118 		ctx->ccm_cb[1] =
119 		    (ctx->ccm_cb[1] & ~(ctx->ccm_counter_mask)) | counter;
120 
121 		/*
122 		 * XOR encrypted counter block with the current clear block.
123 		 */
124 		xor_block(blockp, lastp);
125 
126 		ctx->ccm_processed_data_len += block_size;
127 
128 		crypto_get_ptrs(out, &iov_or_mp, &offset, &out_data_1,
129 		    &out_data_1_len, &out_data_2, block_size);
130 
131 		/* copy block to where it belongs */
132 		if (out_data_1_len == block_size) {
133 			copy_block(lastp, out_data_1);
134 		} else {
135 			bcopy(lastp, out_data_1, out_data_1_len);
136 			if (out_data_2 != NULL) {
137 				bcopy(lastp + out_data_1_len,
138 				    out_data_2,
139 				    block_size - out_data_1_len);
140 			}
141 		}
142 		/* update offset */
143 		out->cd_offset += block_size;
144 
145 		/* Update pointer to next block of data to be processed. */
146 		if (ctx->ccm_remainder_len != 0) {
147 			datap += need;
148 			ctx->ccm_remainder_len = 0;
149 		} else {
150 			datap += block_size;
151 		}
152 
153 		remainder = (size_t)&data[length] - (size_t)datap;
154 
155 		/* Incomplete last block. */
156 		if (remainder > 0 && remainder < block_size) {
157 			bcopy(datap, ctx->ccm_remainder, remainder);
158 			ctx->ccm_remainder_len = remainder;
159 			ctx->ccm_copy_to = datap;
160 			goto out;
161 		}
162 		ctx->ccm_copy_to = NULL;
163 
164 	} while (remainder > 0);
165 
166 out:
167 	return (CRYPTO_SUCCESS);
168 }
169 
170 void
171 calculate_ccm_mac(ccm_ctx_t *ctx, uint8_t *ccm_mac,
172     int (*encrypt_block)(const void *, const uint8_t *, uint8_t *))
173 {
174 	uint64_t counter;
175 	uint8_t *counterp, *mac_buf;
176 	int i;
177 
178 	mac_buf = (uint8_t *)ctx->ccm_mac_buf;
179 
180 	/* first counter block start with index 0 */
181 	counter = 0;
182 	ctx->ccm_cb[1] = (ctx->ccm_cb[1] & ~(ctx->ccm_counter_mask)) | counter;
183 
184 	counterp = (uint8_t *)ctx->ccm_tmp;
185 	encrypt_block(ctx->ccm_keysched, (uint8_t *)ctx->ccm_cb, counterp);
186 
187 	/* calculate XOR of MAC with first counter block */
188 	for (i = 0; i < ctx->ccm_mac_len; i++) {
189 		ccm_mac[i] = mac_buf[i] ^ counterp[i];
190 	}
191 }
192 
193 int
194 ccm_encrypt_final(ccm_ctx_t *ctx, crypto_data_t *out, size_t block_size,
195     int (*encrypt_block)(const void *, const uint8_t *, uint8_t *),
196     void (*xor_block)(uint8_t *, uint8_t *))
197 {
198 	uint8_t *lastp, *mac_buf, *ccm_mac_p, *macp = NULL;
199 	void *iov_or_mp;
200 	offset_t offset;
201 	uint8_t *out_data_1;
202 	uint8_t *out_data_2;
203 	size_t out_data_1_len;
204 	int i;
205 
206 	if (out->cd_length < (ctx->ccm_remainder_len + ctx->ccm_mac_len)) {
207 		return (CRYPTO_DATA_LEN_RANGE);
208 	}
209 
210 	/*
211 	 * When we get here, the number of bytes of payload processed
212 	 * plus whatever data remains, if any,
213 	 * should be the same as the number of bytes that's being
214 	 * passed in the argument during init time.
215 	 */
216 	if ((ctx->ccm_processed_data_len + ctx->ccm_remainder_len)
217 	    != (ctx->ccm_data_len)) {
218 		return (CRYPTO_DATA_LEN_RANGE);
219 	}
220 
221 	mac_buf = (uint8_t *)ctx->ccm_mac_buf;
222 
223 	if (ctx->ccm_remainder_len > 0) {
224 
225 		/* ccm_mac_input_buf is not used for encryption */
226 		macp = (uint8_t *)ctx->ccm_mac_input_buf;
227 		bzero(macp, block_size);
228 
229 		/* copy remainder to temporary buffer */
230 		bcopy(ctx->ccm_remainder, macp, ctx->ccm_remainder_len);
231 
232 		/* calculate the CBC MAC */
233 		xor_block(macp, mac_buf);
234 		encrypt_block(ctx->ccm_keysched, mac_buf, mac_buf);
235 
236 		/* calculate the counter mode */
237 		lastp = (uint8_t *)ctx->ccm_tmp;
238 		encrypt_block(ctx->ccm_keysched, (uint8_t *)ctx->ccm_cb, lastp);
239 
240 		/* XOR with counter block */
241 		for (i = 0; i < ctx->ccm_remainder_len; i++) {
242 			macp[i] ^= lastp[i];
243 		}
244 		ctx->ccm_processed_data_len += ctx->ccm_remainder_len;
245 	}
246 
247 	/* Calculate the CCM MAC */
248 	ccm_mac_p = (uint8_t *)ctx->ccm_tmp;
249 	calculate_ccm_mac(ctx, ccm_mac_p, encrypt_block);
250 
251 	crypto_init_ptrs(out, &iov_or_mp, &offset);
252 	crypto_get_ptrs(out, &iov_or_mp, &offset, &out_data_1,
253 	    &out_data_1_len, &out_data_2,
254 	    ctx->ccm_remainder_len + ctx->ccm_mac_len);
255 
256 	if (ctx->ccm_remainder_len > 0) {
257 
258 		/* copy temporary block to where it belongs */
259 		if (out_data_2 == NULL) {
260 			/* everything will fit in out_data_1 */
261 			bcopy(macp, out_data_1, ctx->ccm_remainder_len);
262 			bcopy(ccm_mac_p, out_data_1 + ctx->ccm_remainder_len,
263 			    ctx->ccm_mac_len);
264 		} else {
265 
266 			if (out_data_1_len < ctx->ccm_remainder_len) {
267 
268 				size_t data_2_len_used;
269 
270 				bcopy(macp, out_data_1, out_data_1_len);
271 
272 				data_2_len_used = ctx->ccm_remainder_len
273 				    - out_data_1_len;
274 
275 				bcopy((uint8_t *)macp + out_data_1_len,
276 				    out_data_2, data_2_len_used);
277 				bcopy(ccm_mac_p, out_data_2 + data_2_len_used,
278 				    ctx->ccm_mac_len);
279 			} else {
280 				bcopy(macp, out_data_1, out_data_1_len);
281 				if (out_data_1_len == ctx->ccm_remainder_len) {
282 					/* mac will be in out_data_2 */
283 					bcopy(ccm_mac_p, out_data_2,
284 					    ctx->ccm_mac_len);
285 				} else {
286 					size_t len_not_used = out_data_1_len -
287 					    ctx->ccm_remainder_len;
288 					/*
289 					 * part of mac in will be in
290 					 * out_data_1, part of the mac will be
291 					 * in out_data_2
292 					 */
293 					bcopy(ccm_mac_p,
294 					    out_data_1 + ctx->ccm_remainder_len,
295 					    len_not_used);
296 					bcopy(ccm_mac_p + len_not_used,
297 					    out_data_2,
298 					    ctx->ccm_mac_len - len_not_used);
299 
300 				}
301 			}
302 		}
303 	} else {
304 		/* copy block to where it belongs */
305 		bcopy(ccm_mac_p, out_data_1, out_data_1_len);
306 		if (out_data_2 != NULL) {
307 			bcopy(ccm_mac_p + out_data_1_len, out_data_2,
308 			    block_size - out_data_1_len);
309 		}
310 	}
311 	out->cd_offset += ctx->ccm_remainder_len + ctx->ccm_mac_len;
312 	ctx->ccm_remainder_len = 0;
313 	return (CRYPTO_SUCCESS);
314 }
315 
316 /*
317  * This will only deal with decrypting the last block of the input that
318  * might not be a multiple of block length.
319  */
320 static void
321 ccm_decrypt_incomplete_block(ccm_ctx_t *ctx,
322     int (*encrypt_block)(const void *, const uint8_t *, uint8_t *))
323 {
324 	uint8_t *datap, *outp, *counterp;
325 	int i;
326 
327 	datap = (uint8_t *)ctx->ccm_remainder;
328 	outp = &((ctx->ccm_pt_buf)[ctx->ccm_processed_data_len]);
329 
330 	counterp = (uint8_t *)ctx->ccm_tmp;
331 	encrypt_block(ctx->ccm_keysched, (uint8_t *)ctx->ccm_cb, counterp);
332 
333 	/* XOR with counter block */
334 	for (i = 0; i < ctx->ccm_remainder_len; i++) {
335 		outp[i] = datap[i] ^ counterp[i];
336 	}
337 }
338 
339 /*
340  * This will decrypt the cipher text.  However, the plaintext won't be
341  * returned to the caller.  It will be returned when decrypt_final() is
342  * called if the MAC matches
343  */
344 int
345 ccm_mode_decrypt_contiguous_blocks(ccm_ctx_t *ctx, char *data, size_t length,
346     crypto_data_t *out, size_t block_size,
347     int (*encrypt_block)(const void *, const uint8_t *, uint8_t *),
348     void (*copy_block)(uint8_t *, uint8_t *),
349     void (*xor_block)(uint8_t *, uint8_t *))
350 {
351 	(void) out;
352 	size_t remainder = length;
353 	size_t need = 0;
354 	uint8_t *datap = (uint8_t *)data;
355 	uint8_t *blockp;
356 	uint8_t *cbp;
357 	uint64_t counter;
358 	size_t pt_len, total_decrypted_len, mac_len, pm_len, pd_len;
359 	uint8_t *resultp;
360 
361 
362 	pm_len = ctx->ccm_processed_mac_len;
363 
364 	if (pm_len > 0) {
365 		uint8_t *tmp;
366 		/*
367 		 * all ciphertext has been processed, just waiting for
368 		 * part of the value of the mac
369 		 */
370 		if ((pm_len + length) > ctx->ccm_mac_len) {
371 			return (CRYPTO_ENCRYPTED_DATA_LEN_RANGE);
372 		}
373 		tmp = (uint8_t *)ctx->ccm_mac_input_buf;
374 
375 		bcopy(datap, tmp + pm_len, length);
376 
377 		ctx->ccm_processed_mac_len += length;
378 		return (CRYPTO_SUCCESS);
379 	}
380 
381 	/*
382 	 * If we decrypt the given data, what total amount of data would
383 	 * have been decrypted?
384 	 */
385 	pd_len = ctx->ccm_processed_data_len;
386 	total_decrypted_len = pd_len + length + ctx->ccm_remainder_len;
387 
388 	if (total_decrypted_len >
389 	    (ctx->ccm_data_len + ctx->ccm_mac_len)) {
390 		return (CRYPTO_ENCRYPTED_DATA_LEN_RANGE);
391 	}
392 
393 	pt_len = ctx->ccm_data_len;
394 
395 	if (total_decrypted_len > pt_len) {
396 		/*
397 		 * part of the input will be the MAC, need to isolate that
398 		 * to be dealt with later.  The left-over data in
399 		 * ccm_remainder_len from last time will not be part of the
400 		 * MAC.  Otherwise, it would have already been taken out
401 		 * when this call is made last time.
402 		 */
403 		size_t pt_part = pt_len - pd_len - ctx->ccm_remainder_len;
404 
405 		mac_len = length - pt_part;
406 
407 		ctx->ccm_processed_mac_len = mac_len;
408 		bcopy(data + pt_part, ctx->ccm_mac_input_buf, mac_len);
409 
410 		if (pt_part + ctx->ccm_remainder_len < block_size) {
411 			/*
412 			 * since this is last of the ciphertext, will
413 			 * just decrypt with it here
414 			 */
415 			bcopy(datap, &((uint8_t *)ctx->ccm_remainder)
416 			    [ctx->ccm_remainder_len], pt_part);
417 			ctx->ccm_remainder_len += pt_part;
418 			ccm_decrypt_incomplete_block(ctx, encrypt_block);
419 			ctx->ccm_processed_data_len += ctx->ccm_remainder_len;
420 			ctx->ccm_remainder_len = 0;
421 			return (CRYPTO_SUCCESS);
422 		} else {
423 			/* let rest of the code handle this */
424 			length = pt_part;
425 		}
426 	} else if (length + ctx->ccm_remainder_len < block_size) {
427 			/* accumulate bytes here and return */
428 		bcopy(datap,
429 		    (uint8_t *)ctx->ccm_remainder + ctx->ccm_remainder_len,
430 		    length);
431 		ctx->ccm_remainder_len += length;
432 		ctx->ccm_copy_to = datap;
433 		return (CRYPTO_SUCCESS);
434 	}
435 
436 	do {
437 		/* Unprocessed data from last call. */
438 		if (ctx->ccm_remainder_len > 0) {
439 			need = block_size - ctx->ccm_remainder_len;
440 
441 			if (need > remainder)
442 				return (CRYPTO_ENCRYPTED_DATA_LEN_RANGE);
443 
444 			bcopy(datap, &((uint8_t *)ctx->ccm_remainder)
445 			    [ctx->ccm_remainder_len], need);
446 
447 			blockp = (uint8_t *)ctx->ccm_remainder;
448 		} else {
449 			blockp = datap;
450 		}
451 
452 		/* Calculate the counter mode, ccm_cb is the counter block */
453 		cbp = (uint8_t *)ctx->ccm_tmp;
454 		encrypt_block(ctx->ccm_keysched, (uint8_t *)ctx->ccm_cb, cbp);
455 
456 		/*
457 		 * Increment counter.
458 		 * Counter bits are confined to the bottom 64 bits
459 		 */
460 #ifdef _ZFS_LITTLE_ENDIAN
461 		counter = ntohll(ctx->ccm_cb[1] & ctx->ccm_counter_mask);
462 		counter = htonll(counter + 1);
463 #else
464 		counter = ctx->ccm_cb[1] & ctx->ccm_counter_mask;
465 		counter++;
466 #endif	/* _ZFS_LITTLE_ENDIAN */
467 		counter &= ctx->ccm_counter_mask;
468 		ctx->ccm_cb[1] =
469 		    (ctx->ccm_cb[1] & ~(ctx->ccm_counter_mask)) | counter;
470 
471 		/* XOR with the ciphertext */
472 		xor_block(blockp, cbp);
473 
474 		/* Copy the plaintext to the "holding buffer" */
475 		resultp = (uint8_t *)ctx->ccm_pt_buf +
476 		    ctx->ccm_processed_data_len;
477 		copy_block(cbp, resultp);
478 
479 		ctx->ccm_processed_data_len += block_size;
480 
481 		ctx->ccm_lastp = blockp;
482 
483 		/* Update pointer to next block of data to be processed. */
484 		if (ctx->ccm_remainder_len != 0) {
485 			datap += need;
486 			ctx->ccm_remainder_len = 0;
487 		} else {
488 			datap += block_size;
489 		}
490 
491 		remainder = (size_t)&data[length] - (size_t)datap;
492 
493 		/* Incomplete last block */
494 		if (remainder > 0 && remainder < block_size) {
495 			bcopy(datap, ctx->ccm_remainder, remainder);
496 			ctx->ccm_remainder_len = remainder;
497 			ctx->ccm_copy_to = datap;
498 			if (ctx->ccm_processed_mac_len > 0) {
499 				/*
500 				 * not expecting anymore ciphertext, just
501 				 * compute plaintext for the remaining input
502 				 */
503 				ccm_decrypt_incomplete_block(ctx,
504 				    encrypt_block);
505 				ctx->ccm_processed_data_len += remainder;
506 				ctx->ccm_remainder_len = 0;
507 			}
508 			goto out;
509 		}
510 		ctx->ccm_copy_to = NULL;
511 
512 	} while (remainder > 0);
513 
514 out:
515 	return (CRYPTO_SUCCESS);
516 }
517 
518 int
519 ccm_decrypt_final(ccm_ctx_t *ctx, crypto_data_t *out, size_t block_size,
520     int (*encrypt_block)(const void *, const uint8_t *, uint8_t *),
521     void (*copy_block)(uint8_t *, uint8_t *),
522     void (*xor_block)(uint8_t *, uint8_t *))
523 {
524 	size_t mac_remain, pt_len;
525 	uint8_t *pt, *mac_buf, *macp, *ccm_mac_p;
526 	int rv;
527 
528 	pt_len = ctx->ccm_data_len;
529 
530 	/* Make sure output buffer can fit all of the plaintext */
531 	if (out->cd_length < pt_len) {
532 		return (CRYPTO_DATA_LEN_RANGE);
533 	}
534 
535 	pt = ctx->ccm_pt_buf;
536 	mac_remain = ctx->ccm_processed_data_len;
537 	mac_buf = (uint8_t *)ctx->ccm_mac_buf;
538 
539 	macp = (uint8_t *)ctx->ccm_tmp;
540 
541 	while (mac_remain > 0) {
542 
543 		if (mac_remain < block_size) {
544 			bzero(macp, block_size);
545 			bcopy(pt, macp, mac_remain);
546 			mac_remain = 0;
547 		} else {
548 			copy_block(pt, macp);
549 			mac_remain -= block_size;
550 			pt += block_size;
551 		}
552 
553 		/* calculate the CBC MAC */
554 		xor_block(macp, mac_buf);
555 		encrypt_block(ctx->ccm_keysched, mac_buf, mac_buf);
556 	}
557 
558 	/* Calculate the CCM MAC */
559 	ccm_mac_p = (uint8_t *)ctx->ccm_tmp;
560 	calculate_ccm_mac((ccm_ctx_t *)ctx, ccm_mac_p, encrypt_block);
561 
562 	/* compare the input CCM MAC value with what we calculated */
563 	if (bcmp(ctx->ccm_mac_input_buf, ccm_mac_p, ctx->ccm_mac_len)) {
564 		/* They don't match */
565 		return (CRYPTO_INVALID_MAC);
566 	} else {
567 		rv = crypto_put_output_data(ctx->ccm_pt_buf, out, pt_len);
568 		if (rv != CRYPTO_SUCCESS)
569 			return (rv);
570 		out->cd_offset += pt_len;
571 	}
572 	return (CRYPTO_SUCCESS);
573 }
574 
575 static int
576 ccm_validate_args(CK_AES_CCM_PARAMS *ccm_param, boolean_t is_encrypt_init)
577 {
578 	size_t macSize, nonceSize;
579 	uint8_t q;
580 	uint64_t maxValue;
581 
582 	/*
583 	 * Check the length of the MAC.  The only valid
584 	 * lengths for the MAC are: 4, 6, 8, 10, 12, 14, 16
585 	 */
586 	macSize = ccm_param->ulMACSize;
587 	if ((macSize < 4) || (macSize > 16) || ((macSize % 2) != 0)) {
588 		return (CRYPTO_MECHANISM_PARAM_INVALID);
589 	}
590 
591 	/* Check the nonce length.  Valid values are 7, 8, 9, 10, 11, 12, 13 */
592 	nonceSize = ccm_param->ulNonceSize;
593 	if ((nonceSize < 7) || (nonceSize > 13)) {
594 		return (CRYPTO_MECHANISM_PARAM_INVALID);
595 	}
596 
597 	/* q is the length of the field storing the length, in bytes */
598 	q = (uint8_t)((15 - nonceSize) & 0xFF);
599 
600 
601 	/*
602 	 * If it is decrypt, need to make sure size of ciphertext is at least
603 	 * bigger than MAC len
604 	 */
605 	if ((!is_encrypt_init) && (ccm_param->ulDataSize < macSize)) {
606 		return (CRYPTO_MECHANISM_PARAM_INVALID);
607 	}
608 
609 	/*
610 	 * Check to make sure the length of the payload is within the
611 	 * range of values allowed by q
612 	 */
613 	if (q < 8) {
614 		maxValue = (1ULL << (q * 8)) - 1;
615 	} else {
616 		maxValue = ULONG_MAX;
617 	}
618 
619 	if (ccm_param->ulDataSize > maxValue) {
620 		return (CRYPTO_MECHANISM_PARAM_INVALID);
621 	}
622 	return (CRYPTO_SUCCESS);
623 }
624 
625 /*
626  * Format the first block used in CBC-MAC (B0) and the initial counter
627  * block based on formatting functions and counter generation functions
628  * specified in RFC 3610 and NIST publication 800-38C, appendix A
629  *
630  * b0 is the first block used in CBC-MAC
631  * cb0 is the first counter block
632  *
633  * It's assumed that the arguments b0 and cb0 are preallocated AES blocks
634  *
635  */
636 static void
637 ccm_format_initial_blocks(uchar_t *nonce, ulong_t nonceSize,
638     ulong_t authDataSize, uint8_t *b0, ccm_ctx_t *aes_ctx)
639 {
640 	uint64_t payloadSize;
641 	uint8_t t, q, have_adata = 0;
642 	size_t limit;
643 	int i, j, k;
644 	uint64_t mask = 0;
645 	uint8_t *cb;
646 
647 	q = (uint8_t)((15 - nonceSize) & 0xFF);
648 	t = (uint8_t)((aes_ctx->ccm_mac_len) & 0xFF);
649 
650 	/* Construct the first octet of b0 */
651 	if (authDataSize > 0) {
652 		have_adata = 1;
653 	}
654 	b0[0] = (have_adata << 6) | (((t - 2)  / 2) << 3) | (q - 1);
655 
656 	/* copy the nonce value into b0 */
657 	bcopy(nonce, &(b0[1]), nonceSize);
658 
659 	/* store the length of the payload into b0 */
660 	bzero(&(b0[1+nonceSize]), q);
661 
662 	payloadSize = aes_ctx->ccm_data_len;
663 	limit = 8 < q ? 8 : q;
664 
665 	for (i = 0, j = 0, k = 15; i < limit; i++, j += 8, k--) {
666 		b0[k] = (uint8_t)((payloadSize >> j) & 0xFF);
667 	}
668 
669 	/* format the counter block */
670 
671 	cb = (uint8_t *)aes_ctx->ccm_cb;
672 
673 	cb[0] = 0x07 & (q-1); /* first byte */
674 
675 	/* copy the nonce value into the counter block */
676 	bcopy(nonce, &(cb[1]), nonceSize);
677 
678 	bzero(&(cb[1+nonceSize]), q);
679 
680 	/* Create the mask for the counter field based on the size of nonce */
681 	q <<= 3;
682 	while (q-- > 0) {
683 		mask |= (1ULL << q);
684 	}
685 
686 #ifdef _ZFS_LITTLE_ENDIAN
687 	mask = htonll(mask);
688 #endif
689 	aes_ctx->ccm_counter_mask = mask;
690 
691 	/*
692 	 * During calculation, we start using counter block 1, we will
693 	 * set it up right here.
694 	 * We can just set the last byte to have the value 1, because
695 	 * even with the biggest nonce of 13, the last byte of the
696 	 * counter block will be used for the counter value.
697 	 */
698 	cb[15] = 0x01;
699 }
700 
701 /*
702  * Encode the length of the associated data as
703  * specified in RFC 3610 and NIST publication 800-38C, appendix A
704  */
705 static void
706 encode_adata_len(ulong_t auth_data_len, uint8_t *encoded, size_t *encoded_len)
707 {
708 #ifdef UNALIGNED_POINTERS_PERMITTED
709 	uint32_t	*lencoded_ptr;
710 #ifdef _LP64
711 	uint64_t	*llencoded_ptr;
712 #endif
713 #endif	/* UNALIGNED_POINTERS_PERMITTED */
714 
715 	if (auth_data_len < ((1ULL<<16) - (1ULL<<8))) {
716 		/* 0 < a < (2^16-2^8) */
717 		*encoded_len = 2;
718 		encoded[0] = (auth_data_len & 0xff00) >> 8;
719 		encoded[1] = auth_data_len & 0xff;
720 
721 	} else if ((auth_data_len >= ((1ULL<<16) - (1ULL<<8))) &&
722 	    (auth_data_len < (1ULL << 31))) {
723 		/* (2^16-2^8) <= a < 2^32 */
724 		*encoded_len = 6;
725 		encoded[0] = 0xff;
726 		encoded[1] = 0xfe;
727 #ifdef UNALIGNED_POINTERS_PERMITTED
728 		lencoded_ptr = (uint32_t *)&encoded[2];
729 		*lencoded_ptr = htonl(auth_data_len);
730 #else
731 		encoded[2] = (auth_data_len & 0xff000000) >> 24;
732 		encoded[3] = (auth_data_len & 0xff0000) >> 16;
733 		encoded[4] = (auth_data_len & 0xff00) >> 8;
734 		encoded[5] = auth_data_len & 0xff;
735 #endif	/* UNALIGNED_POINTERS_PERMITTED */
736 
737 #ifdef _LP64
738 	} else {
739 		/* 2^32 <= a < 2^64 */
740 		*encoded_len = 10;
741 		encoded[0] = 0xff;
742 		encoded[1] = 0xff;
743 #ifdef UNALIGNED_POINTERS_PERMITTED
744 		llencoded_ptr = (uint64_t *)&encoded[2];
745 		*llencoded_ptr = htonl(auth_data_len);
746 #else
747 		encoded[2] = (auth_data_len & 0xff00000000000000) >> 56;
748 		encoded[3] = (auth_data_len & 0xff000000000000) >> 48;
749 		encoded[4] = (auth_data_len & 0xff0000000000) >> 40;
750 		encoded[5] = (auth_data_len & 0xff00000000) >> 32;
751 		encoded[6] = (auth_data_len & 0xff000000) >> 24;
752 		encoded[7] = (auth_data_len & 0xff0000) >> 16;
753 		encoded[8] = (auth_data_len & 0xff00) >> 8;
754 		encoded[9] = auth_data_len & 0xff;
755 #endif	/* UNALIGNED_POINTERS_PERMITTED */
756 #endif	/* _LP64 */
757 	}
758 }
759 
760 static int
761 ccm_init(ccm_ctx_t *ctx, unsigned char *nonce, size_t nonce_len,
762     unsigned char *auth_data, size_t auth_data_len, size_t block_size,
763     int (*encrypt_block)(const void *, const uint8_t *, uint8_t *),
764     void (*xor_block)(uint8_t *, uint8_t *))
765 {
766 	uint8_t *mac_buf, *datap, *ivp, *authp;
767 	size_t remainder, processed;
768 	uint8_t encoded_a[10]; /* max encoded auth data length is 10 octets */
769 	size_t encoded_a_len = 0;
770 
771 	mac_buf = (uint8_t *)&(ctx->ccm_mac_buf);
772 
773 	/*
774 	 * Format the 1st block for CBC-MAC and construct the
775 	 * 1st counter block.
776 	 *
777 	 * aes_ctx->ccm_iv is used for storing the counter block
778 	 * mac_buf will store b0 at this time.
779 	 */
780 	ccm_format_initial_blocks(nonce, nonce_len,
781 	    auth_data_len, mac_buf, ctx);
782 
783 	/* The IV for CBC MAC for AES CCM mode is always zero */
784 	ivp = (uint8_t *)ctx->ccm_tmp;
785 	bzero(ivp, block_size);
786 
787 	xor_block(ivp, mac_buf);
788 
789 	/* encrypt the nonce */
790 	encrypt_block(ctx->ccm_keysched, mac_buf, mac_buf);
791 
792 	/* take care of the associated data, if any */
793 	if (auth_data_len == 0) {
794 		return (CRYPTO_SUCCESS);
795 	}
796 
797 	encode_adata_len(auth_data_len, encoded_a, &encoded_a_len);
798 
799 	remainder = auth_data_len;
800 
801 	/* 1st block: it contains encoded associated data, and some data */
802 	authp = (uint8_t *)ctx->ccm_tmp;
803 	bzero(authp, block_size);
804 	bcopy(encoded_a, authp, encoded_a_len);
805 	processed = block_size - encoded_a_len;
806 	if (processed > auth_data_len) {
807 		/* in case auth_data is very small */
808 		processed = auth_data_len;
809 	}
810 	bcopy(auth_data, authp+encoded_a_len, processed);
811 	/* xor with previous buffer */
812 	xor_block(authp, mac_buf);
813 	encrypt_block(ctx->ccm_keysched, mac_buf, mac_buf);
814 	remainder -= processed;
815 	if (remainder == 0) {
816 		/* a small amount of associated data, it's all done now */
817 		return (CRYPTO_SUCCESS);
818 	}
819 
820 	do {
821 		if (remainder < block_size) {
822 			/*
823 			 * There's not a block full of data, pad rest of
824 			 * buffer with zero
825 			 */
826 			bzero(authp, block_size);
827 			bcopy(&(auth_data[processed]), authp, remainder);
828 			datap = (uint8_t *)authp;
829 			remainder = 0;
830 		} else {
831 			datap = (uint8_t *)(&(auth_data[processed]));
832 			processed += block_size;
833 			remainder -= block_size;
834 		}
835 
836 		xor_block(datap, mac_buf);
837 		encrypt_block(ctx->ccm_keysched, mac_buf, mac_buf);
838 
839 	} while (remainder > 0);
840 
841 	return (CRYPTO_SUCCESS);
842 }
843 
844 /*
845  * The following function should be call at encrypt or decrypt init time
846  * for AES CCM mode.
847  */
848 int
849 ccm_init_ctx(ccm_ctx_t *ccm_ctx, char *param, int kmflag,
850     boolean_t is_encrypt_init, size_t block_size,
851     int (*encrypt_block)(const void *, const uint8_t *, uint8_t *),
852     void (*xor_block)(uint8_t *, uint8_t *))
853 {
854 	int rv;
855 	CK_AES_CCM_PARAMS *ccm_param;
856 
857 	if (param != NULL) {
858 		ccm_param = (CK_AES_CCM_PARAMS *)param;
859 
860 		if ((rv = ccm_validate_args(ccm_param,
861 		    is_encrypt_init)) != 0) {
862 			return (rv);
863 		}
864 
865 		ccm_ctx->ccm_mac_len = ccm_param->ulMACSize;
866 		if (is_encrypt_init) {
867 			ccm_ctx->ccm_data_len = ccm_param->ulDataSize;
868 		} else {
869 			ccm_ctx->ccm_data_len =
870 			    ccm_param->ulDataSize - ccm_ctx->ccm_mac_len;
871 			ccm_ctx->ccm_processed_mac_len = 0;
872 		}
873 		ccm_ctx->ccm_processed_data_len = 0;
874 
875 		ccm_ctx->ccm_flags |= CCM_MODE;
876 	} else {
877 		return (CRYPTO_MECHANISM_PARAM_INVALID);
878 	}
879 
880 	if (ccm_init(ccm_ctx, ccm_param->nonce, ccm_param->ulNonceSize,
881 	    ccm_param->authData, ccm_param->ulAuthDataSize, block_size,
882 	    encrypt_block, xor_block) != 0) {
883 		return (CRYPTO_MECHANISM_PARAM_INVALID);
884 	}
885 	if (!is_encrypt_init) {
886 		/* allocate buffer for storing decrypted plaintext */
887 		ccm_ctx->ccm_pt_buf = vmem_alloc(ccm_ctx->ccm_data_len,
888 		    kmflag);
889 		if (ccm_ctx->ccm_pt_buf == NULL) {
890 			rv = CRYPTO_HOST_MEMORY;
891 		}
892 	}
893 	return (rv);
894 }
895 
896 void *
897 ccm_alloc_ctx(int kmflag)
898 {
899 	ccm_ctx_t *ccm_ctx;
900 
901 	if ((ccm_ctx = kmem_zalloc(sizeof (ccm_ctx_t), kmflag)) == NULL)
902 		return (NULL);
903 
904 	ccm_ctx->ccm_flags = CCM_MODE;
905 	return (ccm_ctx);
906 }
907