xref: /openbsd-src/sys/crypto/cryptosoft.c (revision 0b7734b3d77bb9b21afec6f4621cae6c805dbd45)
1 /*	$OpenBSD: cryptosoft.c,v 1.80 2015/12/10 21:00:51 naddy Exp $	*/
2 
3 /*
4  * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
5  *
6  * This code was written by Angelos D. Keromytis in Athens, Greece, in
7  * February 2000. Network Security Technologies Inc. (NSTI) kindly
8  * supported the development of this code.
9  *
10  * Copyright (c) 2000, 2001 Angelos D. Keromytis
11  *
12  * Permission to use, copy, and modify this software with or without fee
13  * is hereby granted, provided that this entire notice is included in
14  * all source code copies of any software which is or includes a copy or
15  * modification of this software.
16  *
17  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
18  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
19  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
20  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
21  * PURPOSE.
22  */
23 
24 #include <sys/param.h>
25 #include <sys/systm.h>
26 #include <sys/malloc.h>
27 #include <sys/mbuf.h>
28 #include <sys/errno.h>
29 #include <dev/rndvar.h>
30 #include <crypto/md5.h>
31 #include <crypto/sha1.h>
32 #include <crypto/rmd160.h>
33 #include <crypto/cast.h>
34 #include <crypto/cryptodev.h>
35 #include <crypto/cryptosoft.h>
36 #include <crypto/xform.h>
37 
38 const u_int8_t hmac_ipad_buffer[HMAC_MAX_BLOCK_LEN] = {
39 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
40 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
41 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
42 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
43 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
44 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
45 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
46 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
47 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
48 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
49 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
50 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
51 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
52 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
53 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
54 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
55 };
56 
57 const u_int8_t hmac_opad_buffer[HMAC_MAX_BLOCK_LEN] = {
58 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
59 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
60 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
61 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
62 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
63 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
64 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
65 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
66 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
67 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
68 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
69 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
70 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
71 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
72 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
73 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C
74 };
75 
76 
77 struct swcr_data **swcr_sessions = NULL;
78 u_int32_t swcr_sesnum = 0;
79 int32_t swcr_id = -1;
80 
81 #define COPYBACK(x, a, b, c, d) \
82 	do { \
83 		if ((x) == CRYPTO_BUF_MBUF) \
84 			m_copyback((struct mbuf *)a,b,c,d,M_NOWAIT); \
85 		else \
86 			cuio_copyback((struct uio *)a,b,c,d); \
87 	} while (0)
88 #define COPYDATA(x, a, b, c, d) \
89 	do { \
90 		if ((x) == CRYPTO_BUF_MBUF) \
91 			m_copydata((struct mbuf *)a,b,c,d); \
92 		else \
93 			cuio_copydata((struct uio *)a,b,c,d); \
94 	} while (0)
95 
96 /*
97  * Apply a symmetric encryption/decryption algorithm.
98  */
99 int
100 swcr_encdec(struct cryptodesc *crd, struct swcr_data *sw, caddr_t buf,
101     int outtype)
102 {
103 	unsigned char iv[EALG_MAX_BLOCK_LEN], blk[EALG_MAX_BLOCK_LEN], *idat;
104 	unsigned char *ivp, *nivp, iv2[EALG_MAX_BLOCK_LEN];
105 	struct enc_xform *exf;
106 	int i, k, j, blks, ind, count, ivlen;
107 	struct mbuf *m = NULL;
108 	struct uio *uio = NULL;
109 
110 	exf = sw->sw_exf;
111 	blks = exf->blocksize;
112 	ivlen = exf->ivsize;
113 
114 	/* Check for non-padded data */
115 	if (crd->crd_len % blks)
116 		return EINVAL;
117 
118 	if (outtype == CRYPTO_BUF_MBUF)
119 		m = (struct mbuf *) buf;
120 	else
121 		uio = (struct uio *) buf;
122 
123 	/* Initialize the IV */
124 	if (crd->crd_flags & CRD_F_ENCRYPT) {
125 		/* IV explicitly provided ? */
126 		if (crd->crd_flags & CRD_F_IV_EXPLICIT)
127 			bcopy(crd->crd_iv, iv, ivlen);
128 		else
129 			arc4random_buf(iv, ivlen);
130 
131 		/* Do we need to write the IV */
132 		if (!(crd->crd_flags & CRD_F_IV_PRESENT))
133 			COPYBACK(outtype, buf, crd->crd_inject, ivlen, iv);
134 
135 	} else {	/* Decryption */
136 			/* IV explicitly provided ? */
137 		if (crd->crd_flags & CRD_F_IV_EXPLICIT)
138 			bcopy(crd->crd_iv, iv, ivlen);
139 		else {
140 			/* Get IV off buf */
141 			COPYDATA(outtype, buf, crd->crd_inject, ivlen, iv);
142 		}
143 	}
144 
145 	ivp = iv;
146 
147 	/*
148 	 * xforms that provide a reinit method perform all IV
149 	 * handling themselves.
150 	 */
151 	if (exf->reinit)
152 		exf->reinit(sw->sw_kschedule, iv);
153 
154 	if (outtype == CRYPTO_BUF_MBUF) {
155 		/* Find beginning of data */
156 		m = m_getptr(m, crd->crd_skip, &k);
157 		if (m == NULL)
158 			return EINVAL;
159 
160 		i = crd->crd_len;
161 
162 		while (i > 0) {
163 			/*
164 			 * If there's insufficient data at the end of
165 			 * an mbuf, we have to do some copying.
166 			 */
167 			if (m->m_len < k + blks && m->m_len != k) {
168 				m_copydata(m, k, blks, blk);
169 
170 				/* Actual encryption/decryption */
171 				if (exf->reinit) {
172 					if (crd->crd_flags & CRD_F_ENCRYPT) {
173 						exf->encrypt(sw->sw_kschedule,
174 						    blk);
175 					} else {
176 						exf->decrypt(sw->sw_kschedule,
177 						    blk);
178 					}
179 				} else if (crd->crd_flags & CRD_F_ENCRYPT) {
180 					/* XOR with previous block */
181 					for (j = 0; j < blks; j++)
182 						blk[j] ^= ivp[j];
183 
184 					exf->encrypt(sw->sw_kschedule, blk);
185 
186 					/*
187 					 * Keep encrypted block for XOR'ing
188 					 * with next block
189 					 */
190 					bcopy(blk, iv, blks);
191 					ivp = iv;
192 				} else {	/* decrypt */
193 					/*
194 					 * Keep encrypted block for XOR'ing
195 					 * with next block
196 					 */
197 					nivp = (ivp == iv) ? iv2 : iv;
198 					bcopy(blk, nivp, blks);
199 
200 					exf->decrypt(sw->sw_kschedule, blk);
201 
202 					/* XOR with previous block */
203 					for (j = 0; j < blks; j++)
204 						blk[j] ^= ivp[j];
205 					ivp = nivp;
206 				}
207 
208 				/* Copy back decrypted block */
209 				m_copyback(m, k, blks, blk, M_NOWAIT);
210 
211 				/* Advance pointer */
212 				m = m_getptr(m, k + blks, &k);
213 				if (m == NULL)
214 					return EINVAL;
215 
216 				i -= blks;
217 
218 				/* Could be done... */
219 				if (i == 0)
220 					break;
221 			}
222 
223 			/* Skip possibly empty mbufs */
224 			if (k == m->m_len) {
225 				for (m = m->m_next; m && m->m_len == 0;
226 				    m = m->m_next)
227 					;
228 				k = 0;
229 			}
230 
231 			/* Sanity check */
232 			if (m == NULL)
233 				return EINVAL;
234 
235 			/*
236 			 * Warning: idat may point to garbage here, but
237 			 * we only use it in the while() loop, only if
238 			 * there are indeed enough data.
239 			 */
240 			idat = mtod(m, unsigned char *) + k;
241 
242 			while (m->m_len >= k + blks && i > 0) {
243 				if (exf->reinit) {
244 					if (crd->crd_flags & CRD_F_ENCRYPT) {
245 						exf->encrypt(sw->sw_kschedule,
246 						    idat);
247 					} else {
248 						exf->decrypt(sw->sw_kschedule,
249 						    idat);
250 					}
251 				} else if (crd->crd_flags & CRD_F_ENCRYPT) {
252 					/* XOR with previous block/IV */
253 					for (j = 0; j < blks; j++)
254 						idat[j] ^= ivp[j];
255 
256 					exf->encrypt(sw->sw_kschedule, idat);
257 					ivp = idat;
258 				} else {	/* decrypt */
259 					/*
260 					 * Keep encrypted block to be used
261 					 * in next block's processing.
262 					 */
263 					nivp = (ivp == iv) ? iv2 : iv;
264 					bcopy(idat, nivp, blks);
265 
266 					exf->decrypt(sw->sw_kschedule, idat);
267 
268 					/* XOR with previous block/IV */
269 					for (j = 0; j < blks; j++)
270 						idat[j] ^= ivp[j];
271 					ivp = nivp;
272 				}
273 
274 				idat += blks;
275 				k += blks;
276 				i -= blks;
277 			}
278 		}
279 	} else {
280 		/* Find beginning of data */
281 		count = crd->crd_skip;
282 		ind = cuio_getptr(uio, count, &k);
283 		if (ind == -1)
284 			return EINVAL;
285 
286 		i = crd->crd_len;
287 
288 		while (i > 0) {
289 			/*
290 			 * If there's insufficient data at the end,
291 			 * we have to do some copying.
292 			 */
293 			if (uio->uio_iov[ind].iov_len < k + blks &&
294 			    uio->uio_iov[ind].iov_len != k) {
295 				cuio_copydata(uio, count, blks, blk);
296 
297 				/* Actual encryption/decryption */
298 				if (exf->reinit) {
299 					if (crd->crd_flags & CRD_F_ENCRYPT) {
300 						exf->encrypt(sw->sw_kschedule,
301 						    blk);
302 					} else {
303 						exf->decrypt(sw->sw_kschedule,
304 						    blk);
305 					}
306 				} else if (crd->crd_flags & CRD_F_ENCRYPT) {
307 					/* XOR with previous block */
308 					for (j = 0; j < blks; j++)
309 						blk[j] ^= ivp[j];
310 
311 					exf->encrypt(sw->sw_kschedule, blk);
312 
313 					/*
314 					 * Keep encrypted block for XOR'ing
315 					 * with next block
316 					 */
317 					bcopy(blk, iv, blks);
318 					ivp = iv;
319 				} else {	/* decrypt */
320 					/*
321 					 * Keep encrypted block for XOR'ing
322 					 * with next block
323 					 */
324 					nivp = (ivp == iv) ? iv2 : iv;
325 					bcopy(blk, nivp, blks);
326 
327 					exf->decrypt(sw->sw_kschedule, blk);
328 
329 					/* XOR with previous block */
330 					for (j = 0; j < blks; j++)
331 						blk[j] ^= ivp[j];
332 					ivp = nivp;
333 				}
334 
335 				/* Copy back decrypted block */
336 				cuio_copyback(uio, count, blks, blk);
337 
338 				count += blks;
339 
340 				/* Advance pointer */
341 				ind = cuio_getptr(uio, count, &k);
342 				if (ind == -1)
343 					return (EINVAL);
344 
345 				i -= blks;
346 
347 				/* Could be done... */
348 				if (i == 0)
349 					break;
350 			}
351 
352 			/*
353 			 * Warning: idat may point to garbage here, but
354 			 * we only use it in the while() loop, only if
355 			 * there are indeed enough data.
356 			 */
357 			idat = (char *)uio->uio_iov[ind].iov_base + k;
358 
359 			while (uio->uio_iov[ind].iov_len >= k + blks &&
360 			    i > 0) {
361 				if (exf->reinit) {
362 					if (crd->crd_flags & CRD_F_ENCRYPT) {
363 						exf->encrypt(sw->sw_kschedule,
364 						    idat);
365 					} else {
366 						exf->decrypt(sw->sw_kschedule,
367 						    idat);
368 					}
369 				} else if (crd->crd_flags & CRD_F_ENCRYPT) {
370 					/* XOR with previous block/IV */
371 					for (j = 0; j < blks; j++)
372 						idat[j] ^= ivp[j];
373 
374 					exf->encrypt(sw->sw_kschedule, idat);
375 					ivp = idat;
376 				} else {	/* decrypt */
377 					/*
378 					 * Keep encrypted block to be used
379 					 * in next block's processing.
380 					 */
381 					nivp = (ivp == iv) ? iv2 : iv;
382 					bcopy(idat, nivp, blks);
383 
384 					exf->decrypt(sw->sw_kschedule, idat);
385 
386 					/* XOR with previous block/IV */
387 					for (j = 0; j < blks; j++)
388 						idat[j] ^= ivp[j];
389 					ivp = nivp;
390 				}
391 
392 				idat += blks;
393 				count += blks;
394 				k += blks;
395 				i -= blks;
396 			}
397 
398 			/*
399 			 * Advance to the next iov if the end of the current iov
400 			 * is aligned with the end of a cipher block.
401 			 * Note that the code is equivalent to calling:
402 			 *	ind = cuio_getptr(uio, count, &k);
403 			 */
404 			if (i > 0 && k == uio->uio_iov[ind].iov_len) {
405 				k = 0;
406 				ind++;
407 				if (ind >= uio->uio_iovcnt)
408 					return (EINVAL);
409 			}
410 		}
411 	}
412 
413 	return 0; /* Done with encryption/decryption */
414 }
415 
416 /*
417  * Compute keyed-hash authenticator.
418  */
419 int
420 swcr_authcompute(struct cryptop *crp, struct cryptodesc *crd,
421     struct swcr_data *sw, caddr_t buf, int outtype)
422 {
423 	unsigned char aalg[AALG_MAX_RESULT_LEN];
424 	struct auth_hash *axf;
425 	union authctx ctx;
426 	int err;
427 
428 	if (sw->sw_ictx == 0)
429 		return EINVAL;
430 
431 	axf = sw->sw_axf;
432 
433 	bcopy(sw->sw_ictx, &ctx, axf->ctxsize);
434 
435 	if (outtype == CRYPTO_BUF_MBUF)
436 		err = m_apply((struct mbuf *) buf, crd->crd_skip, crd->crd_len,
437 		    (int (*)(caddr_t, caddr_t, unsigned int)) axf->Update,
438 		    (caddr_t) &ctx);
439 	else
440 		err = cuio_apply((struct uio *) buf, crd->crd_skip,
441 		    crd->crd_len,
442 		    (int (*)(caddr_t, caddr_t, unsigned int)) axf->Update,
443 		    (caddr_t) &ctx);
444 
445 	if (err)
446 		return err;
447 
448 	if (crd->crd_flags & CRD_F_ESN)
449 		axf->Update(&ctx, crd->crd_esn, 4);
450 
451 	switch (sw->sw_alg) {
452 	case CRYPTO_MD5_HMAC:
453 	case CRYPTO_SHA1_HMAC:
454 	case CRYPTO_RIPEMD160_HMAC:
455 	case CRYPTO_SHA2_256_HMAC:
456 	case CRYPTO_SHA2_384_HMAC:
457 	case CRYPTO_SHA2_512_HMAC:
458 		if (sw->sw_octx == NULL)
459 			return EINVAL;
460 
461 		axf->Final(aalg, &ctx);
462 		bcopy(sw->sw_octx, &ctx, axf->ctxsize);
463 		axf->Update(&ctx, aalg, axf->hashsize);
464 		axf->Final(aalg, &ctx);
465 		break;
466 	}
467 
468 	/* Inject the authentication data */
469 	if (outtype == CRYPTO_BUF_MBUF)
470 		COPYBACK(outtype, buf, crd->crd_inject, axf->authsize, aalg);
471 	else
472 		bcopy(aalg, crp->crp_mac, axf->authsize);
473 
474 	return 0;
475 }
476 
477 /*
478  * Apply a combined encryption-authentication transformation
479  */
480 int
481 swcr_authenc(struct cryptop *crp)
482 {
483 	uint32_t blkbuf[howmany(EALG_MAX_BLOCK_LEN, sizeof(uint32_t))];
484 	u_char *blk = (u_char *)blkbuf;
485 	u_char aalg[AALG_MAX_RESULT_LEN];
486 	u_char iv[EALG_MAX_BLOCK_LEN];
487 	union authctx ctx;
488 	struct cryptodesc *crd, *crda = NULL, *crde = NULL;
489 	struct swcr_data *sw, *swa, *swe = NULL;
490 	struct auth_hash *axf = NULL;
491 	struct enc_xform *exf = NULL;
492 	struct mbuf *m = NULL;
493 	struct uio *uio = NULL;
494 	caddr_t buf = (caddr_t)crp->crp_buf;
495 	uint32_t *blkp;
496 	int aadlen, blksz, i, ivlen, outtype, len, iskip, oskip;
497 
498 	ivlen = blksz = iskip = oskip = 0;
499 
500 	for (crd = crp->crp_desc; crd; crd = crd->crd_next) {
501 		for (sw = swcr_sessions[crp->crp_sid & 0xffffffff];
502 		     sw && sw->sw_alg != crd->crd_alg;
503 		     sw = sw->sw_next)
504 			;
505 		if (sw == NULL)
506 			return (EINVAL);
507 
508 		switch (sw->sw_alg) {
509 		case CRYPTO_AES_GCM_16:
510 		case CRYPTO_AES_GMAC:
511 		case CRYPTO_CHACHA20_POLY1305:
512 			swe = sw;
513 			crde = crd;
514 			exf = swe->sw_exf;
515 			ivlen = exf->ivsize;
516 			break;
517 		case CRYPTO_AES_128_GMAC:
518 		case CRYPTO_AES_192_GMAC:
519 		case CRYPTO_AES_256_GMAC:
520 		case CRYPTO_CHACHA20_POLY1305_MAC:
521 			swa = sw;
522 			crda = crd;
523 			axf = swa->sw_axf;
524 			if (swa->sw_ictx == 0)
525 				return (EINVAL);
526 			bcopy(swa->sw_ictx, &ctx, axf->ctxsize);
527 			blksz = axf->blocksize;
528 			break;
529 		default:
530 			return (EINVAL);
531 		}
532 	}
533 	if (crde == NULL || crda == NULL)
534 		return (EINVAL);
535 
536 	if (crp->crp_flags & CRYPTO_F_IMBUF) {
537 		outtype = CRYPTO_BUF_MBUF;
538 		m = (struct mbuf *)buf;
539 	} else {
540 		outtype = CRYPTO_BUF_IOV;
541 		uio = (struct uio *)buf;
542 	}
543 
544 	/* Initialize the IV */
545 	if (crde->crd_flags & CRD_F_ENCRYPT) {
546 		/* IV explicitly provided ? */
547 		if (crde->crd_flags & CRD_F_IV_EXPLICIT)
548 			bcopy(crde->crd_iv, iv, ivlen);
549 		else
550 			arc4random_buf(iv, ivlen);
551 
552 		/* Do we need to write the IV */
553 		if (!(crde->crd_flags & CRD_F_IV_PRESENT))
554 			COPYBACK(outtype, buf, crde->crd_inject, ivlen, iv);
555 
556 	} else {	/* Decryption */
557 			/* IV explicitly provided ? */
558 		if (crde->crd_flags & CRD_F_IV_EXPLICIT)
559 			bcopy(crde->crd_iv, iv, ivlen);
560 		else {
561 			/* Get IV off buf */
562 			COPYDATA(outtype, buf, crde->crd_inject, ivlen, iv);
563 		}
564 	}
565 
566 	/* Supply MAC with IV */
567 	if (axf->Reinit)
568 		axf->Reinit(&ctx, iv, ivlen);
569 
570 	/* Supply MAC with AAD */
571 	aadlen = crda->crd_len;
572 	/*
573 	 * Section 5 of RFC 4106 specifies that AAD construction consists of
574 	 * {SPI, ESN, SN} whereas the real packet contains only {SPI, SN}.
575 	 * Unfortunately it doesn't follow a good example set in the Section
576 	 * 3.3.2.1 of RFC 4303 where upper part of the ESN, located in the
577 	 * external (to the packet) memory buffer, is processed by the hash
578 	 * function in the end thus allowing to retain simple programming
579 	 * interfaces and avoid kludges like the one below.
580 	 */
581 	if (crda->crd_flags & CRD_F_ESN) {
582 		aadlen += 4;
583 		/* SPI */
584 		COPYDATA(outtype, buf, crda->crd_skip, 4, blk);
585 		iskip = 4; /* loop below will start with an offset of 4 */
586 		/* ESN */
587 		bcopy(crda->crd_esn, blk + 4, 4);
588 		oskip = iskip + 4; /* offset output buffer blk by 8 */
589 	}
590 	for (i = iskip; i < crda->crd_len; i += axf->hashsize) {
591 		len = MIN(crda->crd_len - i, axf->hashsize - oskip);
592 		COPYDATA(outtype, buf, crda->crd_skip + i, len, blk + oskip);
593 		bzero(blk + len + oskip, axf->hashsize - len - oskip);
594 		axf->Update(&ctx, blk, axf->hashsize);
595 		oskip = 0; /* reset initial output offset */
596 	}
597 
598 	if (exf->reinit)
599 		exf->reinit(swe->sw_kschedule, iv);
600 
601 	/* Do encryption/decryption with MAC */
602 	for (i = 0; i < crde->crd_len; i += blksz) {
603 		len = MIN(crde->crd_len - i, blksz);
604 		if (len < blksz)
605 			bzero(blk, blksz);
606 		COPYDATA(outtype, buf, crde->crd_skip + i, len, blk);
607 		if (crde->crd_flags & CRD_F_ENCRYPT) {
608 			exf->encrypt(swe->sw_kschedule, blk);
609 			axf->Update(&ctx, blk, len);
610 		} else {
611 			axf->Update(&ctx, blk, len);
612 			exf->decrypt(swe->sw_kschedule, blk);
613 		}
614 		COPYBACK(outtype, buf, crde->crd_skip + i, len, blk);
615 	}
616 
617 	/* Do any required special finalization */
618 	switch (crda->crd_alg) {
619 		case CRYPTO_AES_128_GMAC:
620 		case CRYPTO_AES_192_GMAC:
621 		case CRYPTO_AES_256_GMAC:
622 			/* length block */
623 			bzero(blk, axf->hashsize);
624 			blkp = (uint32_t *)blk + 1;
625 			*blkp = htobe32(aadlen * 8);
626 			blkp = (uint32_t *)blk + 3;
627 			*blkp = htobe32(crde->crd_len * 8);
628 			axf->Update(&ctx, blk, axf->hashsize);
629 			break;
630 		case CRYPTO_CHACHA20_POLY1305_MAC:
631 			/* length block */
632 			bzero(blk, axf->hashsize);
633 			blkp = (uint32_t *)blk;
634 			*blkp = htole32(aadlen);
635 			blkp = (uint32_t *)blk + 2;
636 			*blkp = htole32(crde->crd_len);
637 			axf->Update(&ctx, blk, axf->hashsize);
638 			break;
639 	}
640 
641 	/* Finalize MAC */
642 	axf->Final(aalg, &ctx);
643 
644 	/* Inject the authentication data */
645 	if (outtype == CRYPTO_BUF_MBUF)
646 		COPYBACK(outtype, buf, crda->crd_inject, axf->authsize, aalg);
647 	else
648 		bcopy(aalg, crp->crp_mac, axf->authsize);
649 
650 	return (0);
651 }
652 
653 /*
654  * Apply a compression/decompression algorithm
655  */
656 int
657 swcr_compdec(struct cryptodesc *crd, struct swcr_data *sw,
658     caddr_t buf, int outtype)
659 {
660 	u_int8_t *data, *out;
661 	struct comp_algo *cxf;
662 	int adj;
663 	u_int32_t result;
664 
665 	cxf = sw->sw_cxf;
666 
667 	/* We must handle the whole buffer of data in one time
668 	 * then if there is not all the data in the mbuf, we must
669 	 * copy in a buffer.
670 	 */
671 
672 	data = malloc(crd->crd_len, M_CRYPTO_DATA, M_NOWAIT);
673 	if (data == NULL)
674 		return (EINVAL);
675 	COPYDATA(outtype, buf, crd->crd_skip, crd->crd_len, data);
676 
677 	if (crd->crd_flags & CRD_F_COMP)
678 		result = cxf->compress(data, crd->crd_len, &out);
679 	else
680 		result = cxf->decompress(data, crd->crd_len, &out);
681 
682 	free(data, M_CRYPTO_DATA, crd->crd_len);
683 	if (result == 0)
684 		return EINVAL;
685 
686 	/* Copy back the (de)compressed data. m_copyback is
687 	 * extending the mbuf as necessary.
688 	 */
689 	sw->sw_size = result;
690 	/* Check the compressed size when doing compression */
691 	if (crd->crd_flags & CRD_F_COMP) {
692 		if (result > crd->crd_len) {
693 			/* Compression was useless, we lost time */
694 			free(out, M_CRYPTO_DATA, 0);
695 			return 0;
696 		}
697 	}
698 
699 	COPYBACK(outtype, buf, crd->crd_skip, result, out);
700 	if (result < crd->crd_len) {
701 		adj = result - crd->crd_len;
702 		if (outtype == CRYPTO_BUF_MBUF) {
703 			adj = result - crd->crd_len;
704 			m_adj((struct mbuf *)buf, adj);
705 		} else {
706 			struct uio *uio = (struct uio *)buf;
707 			int ind;
708 
709 			adj = crd->crd_len - result;
710 			ind = uio->uio_iovcnt - 1;
711 
712 			while (adj > 0 && ind >= 0) {
713 				if (adj < uio->uio_iov[ind].iov_len) {
714 					uio->uio_iov[ind].iov_len -= adj;
715 					break;
716 				}
717 
718 				adj -= uio->uio_iov[ind].iov_len;
719 				uio->uio_iov[ind].iov_len = 0;
720 				ind--;
721 				uio->uio_iovcnt--;
722 			}
723 		}
724 	}
725 	free(out, M_CRYPTO_DATA, 0);
726 	return 0;
727 }
728 
729 /*
730  * Generate a new software session.
731  */
732 int
733 swcr_newsession(u_int32_t *sid, struct cryptoini *cri)
734 {
735 	struct swcr_data **swd;
736 	struct auth_hash *axf;
737 	struct enc_xform *txf;
738 	struct comp_algo *cxf;
739 	u_int32_t i;
740 	int k;
741 
742 	if (sid == NULL || cri == NULL)
743 		return EINVAL;
744 
745 	if (swcr_sessions) {
746 		for (i = 1; i < swcr_sesnum; i++)
747 			if (swcr_sessions[i] == NULL)
748 				break;
749 	}
750 
751 	if (swcr_sessions == NULL || i == swcr_sesnum) {
752 		if (swcr_sessions == NULL) {
753 			i = 1; /* We leave swcr_sessions[0] empty */
754 			swcr_sesnum = CRYPTO_SW_SESSIONS;
755 		} else
756 			swcr_sesnum *= 2;
757 
758 		swd = mallocarray(swcr_sesnum, sizeof(struct swcr_data *),
759 		    M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
760 		if (swd == NULL) {
761 			/* Reset session number */
762 			if (swcr_sesnum == CRYPTO_SW_SESSIONS)
763 				swcr_sesnum = 0;
764 			else
765 				swcr_sesnum /= 2;
766 			return ENOBUFS;
767 		}
768 
769 		/* Copy existing sessions */
770 		if (swcr_sessions) {
771 			bcopy(swcr_sessions, swd,
772 			    (swcr_sesnum / 2) * sizeof(struct swcr_data *));
773 			free(swcr_sessions, M_CRYPTO_DATA,
774 			    (swcr_sesnum / 2) * sizeof(struct swcr_data *));
775 		}
776 
777 		swcr_sessions = swd;
778 	}
779 
780 	swd = &swcr_sessions[i];
781 	*sid = i;
782 
783 	while (cri) {
784 		*swd = malloc(sizeof(struct swcr_data), M_CRYPTO_DATA,
785 		    M_NOWAIT | M_ZERO);
786 		if (*swd == NULL) {
787 			swcr_freesession(i);
788 			return ENOBUFS;
789 		}
790 
791 		switch (cri->cri_alg) {
792 		case CRYPTO_3DES_CBC:
793 			txf = &enc_xform_3des;
794 			goto enccommon;
795 		case CRYPTO_BLF_CBC:
796 			txf = &enc_xform_blf;
797 			goto enccommon;
798 		case CRYPTO_CAST_CBC:
799 			txf = &enc_xform_cast5;
800 			goto enccommon;
801 		case CRYPTO_RIJNDAEL128_CBC:
802 			txf = &enc_xform_rijndael128;
803 			goto enccommon;
804 		case CRYPTO_AES_CTR:
805 			txf = &enc_xform_aes_ctr;
806 			goto enccommon;
807 		case CRYPTO_AES_XTS:
808 			txf = &enc_xform_aes_xts;
809 			goto enccommon;
810 		case CRYPTO_AES_GCM_16:
811 			txf = &enc_xform_aes_gcm;
812 			goto enccommon;
813 		case CRYPTO_AES_GMAC:
814 			txf = &enc_xform_aes_gmac;
815 			(*swd)->sw_exf = txf;
816 			break;
817 		case CRYPTO_CHACHA20_POLY1305:
818 			txf = &enc_xform_chacha20_poly1305;
819 			goto enccommon;
820 		case CRYPTO_NULL:
821 			txf = &enc_xform_null;
822 			goto enccommon;
823 		enccommon:
824 			if (txf->ctxsize > 0) {
825 				(*swd)->sw_kschedule = malloc(txf->ctxsize,
826 				    M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
827 				if ((*swd)->sw_kschedule == NULL) {
828 					swcr_freesession(i);
829 					return EINVAL;
830 				}
831 			}
832 			if (txf->setkey((*swd)->sw_kschedule, cri->cri_key,
833 			    cri->cri_klen / 8) < 0) {
834 				swcr_freesession(i);
835 				return EINVAL;
836 			}
837 			(*swd)->sw_exf = txf;
838 			break;
839 
840 		case CRYPTO_MD5_HMAC:
841 			axf = &auth_hash_hmac_md5_96;
842 			goto authcommon;
843 		case CRYPTO_SHA1_HMAC:
844 			axf = &auth_hash_hmac_sha1_96;
845 			goto authcommon;
846 		case CRYPTO_RIPEMD160_HMAC:
847 			axf = &auth_hash_hmac_ripemd_160_96;
848 			goto authcommon;
849 		case CRYPTO_SHA2_256_HMAC:
850 			axf = &auth_hash_hmac_sha2_256_128;
851 			goto authcommon;
852 		case CRYPTO_SHA2_384_HMAC:
853 			axf = &auth_hash_hmac_sha2_384_192;
854 			goto authcommon;
855 		case CRYPTO_SHA2_512_HMAC:
856 			axf = &auth_hash_hmac_sha2_512_256;
857 			goto authcommon;
858 		authcommon:
859 			(*swd)->sw_ictx = malloc(axf->ctxsize, M_CRYPTO_DATA,
860 			    M_NOWAIT);
861 			if ((*swd)->sw_ictx == NULL) {
862 				swcr_freesession(i);
863 				return ENOBUFS;
864 			}
865 
866 			(*swd)->sw_octx = malloc(axf->ctxsize, M_CRYPTO_DATA,
867 			    M_NOWAIT);
868 			if ((*swd)->sw_octx == NULL) {
869 				swcr_freesession(i);
870 				return ENOBUFS;
871 			}
872 
873 			for (k = 0; k < cri->cri_klen / 8; k++)
874 				cri->cri_key[k] ^= HMAC_IPAD_VAL;
875 
876 			axf->Init((*swd)->sw_ictx);
877 			axf->Update((*swd)->sw_ictx, cri->cri_key,
878 			    cri->cri_klen / 8);
879 			axf->Update((*swd)->sw_ictx, hmac_ipad_buffer,
880 			    axf->blocksize - (cri->cri_klen / 8));
881 
882 			for (k = 0; k < cri->cri_klen / 8; k++)
883 				cri->cri_key[k] ^= (HMAC_IPAD_VAL ^ HMAC_OPAD_VAL);
884 
885 			axf->Init((*swd)->sw_octx);
886 			axf->Update((*swd)->sw_octx, cri->cri_key,
887 			    cri->cri_klen / 8);
888 			axf->Update((*swd)->sw_octx, hmac_opad_buffer,
889 			    axf->blocksize - (cri->cri_klen / 8));
890 
891 			for (k = 0; k < cri->cri_klen / 8; k++)
892 				cri->cri_key[k] ^= HMAC_OPAD_VAL;
893 			(*swd)->sw_axf = axf;
894 			break;
895 
896 		case CRYPTO_AES_128_GMAC:
897 			axf = &auth_hash_gmac_aes_128;
898 			goto authenccommon;
899 		case CRYPTO_AES_192_GMAC:
900 			axf = &auth_hash_gmac_aes_192;
901 			goto authenccommon;
902 		case CRYPTO_AES_256_GMAC:
903 			axf = &auth_hash_gmac_aes_256;
904 			goto authenccommon;
905 		case CRYPTO_CHACHA20_POLY1305_MAC:
906 			axf = &auth_hash_chacha20_poly1305;
907 			goto authenccommon;
908 		authenccommon:
909 			(*swd)->sw_ictx = malloc(axf->ctxsize, M_CRYPTO_DATA,
910 			    M_NOWAIT);
911 			if ((*swd)->sw_ictx == NULL) {
912 				swcr_freesession(i);
913 				return ENOBUFS;
914 			}
915 			axf->Init((*swd)->sw_ictx);
916 			axf->Setkey((*swd)->sw_ictx, cri->cri_key,
917 			    cri->cri_klen / 8);
918 			(*swd)->sw_axf = axf;
919 			break;
920 
921 		case CRYPTO_DEFLATE_COMP:
922 			cxf = &comp_algo_deflate;
923 			(*swd)->sw_cxf = cxf;
924 			break;
925 		case CRYPTO_ESN:
926 			/* nothing to do */
927 			break;
928 		default:
929 			swcr_freesession(i);
930 			return EINVAL;
931 		}
932 
933 		(*swd)->sw_alg = cri->cri_alg;
934 		cri = cri->cri_next;
935 		swd = &((*swd)->sw_next);
936 	}
937 	return 0;
938 }
939 
940 /*
941  * Free a session.
942  */
943 int
944 swcr_freesession(u_int64_t tid)
945 {
946 	struct swcr_data *swd;
947 	struct enc_xform *txf;
948 	struct auth_hash *axf;
949 	u_int32_t sid = ((u_int32_t) tid) & 0xffffffff;
950 
951 	if (sid > swcr_sesnum || swcr_sessions == NULL ||
952 	    swcr_sessions[sid] == NULL)
953 		return EINVAL;
954 
955 	/* Silently accept and return */
956 	if (sid == 0)
957 		return 0;
958 
959 	while ((swd = swcr_sessions[sid]) != NULL) {
960 		swcr_sessions[sid] = swd->sw_next;
961 
962 		switch (swd->sw_alg) {
963 		case CRYPTO_3DES_CBC:
964 		case CRYPTO_BLF_CBC:
965 		case CRYPTO_CAST_CBC:
966 		case CRYPTO_RIJNDAEL128_CBC:
967 		case CRYPTO_AES_CTR:
968 		case CRYPTO_AES_XTS:
969 		case CRYPTO_AES_GCM_16:
970 		case CRYPTO_AES_GMAC:
971 		case CRYPTO_CHACHA20_POLY1305:
972 		case CRYPTO_NULL:
973 			txf = swd->sw_exf;
974 
975 			if (swd->sw_kschedule) {
976 				explicit_bzero(swd->sw_kschedule, txf->ctxsize);
977 				free(swd->sw_kschedule, M_CRYPTO_DATA, 0);
978 			}
979 			break;
980 
981 		case CRYPTO_MD5_HMAC:
982 		case CRYPTO_SHA1_HMAC:
983 		case CRYPTO_RIPEMD160_HMAC:
984 		case CRYPTO_SHA2_256_HMAC:
985 		case CRYPTO_SHA2_384_HMAC:
986 		case CRYPTO_SHA2_512_HMAC:
987 			axf = swd->sw_axf;
988 
989 			if (swd->sw_ictx) {
990 				explicit_bzero(swd->sw_ictx, axf->ctxsize);
991 				free(swd->sw_ictx, M_CRYPTO_DATA, 0);
992 			}
993 			if (swd->sw_octx) {
994 				explicit_bzero(swd->sw_octx, axf->ctxsize);
995 				free(swd->sw_octx, M_CRYPTO_DATA, 0);
996 			}
997 			break;
998 
999 		case CRYPTO_AES_128_GMAC:
1000 		case CRYPTO_AES_192_GMAC:
1001 		case CRYPTO_AES_256_GMAC:
1002 		case CRYPTO_CHACHA20_POLY1305_MAC:
1003 			axf = swd->sw_axf;
1004 
1005 			if (swd->sw_ictx) {
1006 				explicit_bzero(swd->sw_ictx, axf->ctxsize);
1007 				free(swd->sw_ictx, M_CRYPTO_DATA, 0);
1008 			}
1009 			break;
1010 		}
1011 
1012 		free(swd, M_CRYPTO_DATA, 0);
1013 	}
1014 	return 0;
1015 }
1016 
1017 /*
1018  * Process a software request.
1019  */
1020 int
1021 swcr_process(struct cryptop *crp)
1022 {
1023 	struct cryptodesc *crd;
1024 	struct swcr_data *sw;
1025 	u_int32_t lid;
1026 	int type;
1027 
1028 	/* Sanity check */
1029 	if (crp == NULL)
1030 		return EINVAL;
1031 
1032 	if (crp->crp_desc == NULL || crp->crp_buf == NULL) {
1033 		crp->crp_etype = EINVAL;
1034 		goto done;
1035 	}
1036 
1037 	lid = crp->crp_sid & 0xffffffff;
1038 	if (lid >= swcr_sesnum || lid == 0 || swcr_sessions[lid] == NULL) {
1039 		crp->crp_etype = ENOENT;
1040 		goto done;
1041 	}
1042 
1043 	if (crp->crp_flags & CRYPTO_F_IMBUF)
1044 		type = CRYPTO_BUF_MBUF;
1045 	else
1046 		type = CRYPTO_BUF_IOV;
1047 
1048 	/* Go through crypto descriptors, processing as we go */
1049 	for (crd = crp->crp_desc; crd; crd = crd->crd_next) {
1050 		/*
1051 		 * Find the crypto context.
1052 		 *
1053 		 * XXX Note that the logic here prevents us from having
1054 		 * XXX the same algorithm multiple times in a session
1055 		 * XXX (or rather, we can but it won't give us the right
1056 		 * XXX results). To do that, we'd need some way of differentiating
1057 		 * XXX between the various instances of an algorithm (so we can
1058 		 * XXX locate the correct crypto context).
1059 		 */
1060 		for (sw = swcr_sessions[lid];
1061 		    sw && sw->sw_alg != crd->crd_alg;
1062 		    sw = sw->sw_next)
1063 			;
1064 
1065 		/* No such context ? */
1066 		if (sw == NULL) {
1067 			crp->crp_etype = EINVAL;
1068 			goto done;
1069 		}
1070 
1071 		switch (sw->sw_alg) {
1072 		case CRYPTO_NULL:
1073 			break;
1074 		case CRYPTO_3DES_CBC:
1075 		case CRYPTO_BLF_CBC:
1076 		case CRYPTO_CAST_CBC:
1077 		case CRYPTO_RIJNDAEL128_CBC:
1078 		case CRYPTO_AES_CTR:
1079 		case CRYPTO_AES_XTS:
1080 			if ((crp->crp_etype = swcr_encdec(crd, sw,
1081 			    crp->crp_buf, type)) != 0)
1082 				goto done;
1083 			break;
1084 		case CRYPTO_MD5_HMAC:
1085 		case CRYPTO_SHA1_HMAC:
1086 		case CRYPTO_RIPEMD160_HMAC:
1087 		case CRYPTO_SHA2_256_HMAC:
1088 		case CRYPTO_SHA2_384_HMAC:
1089 		case CRYPTO_SHA2_512_HMAC:
1090 			if ((crp->crp_etype = swcr_authcompute(crp, crd, sw,
1091 			    crp->crp_buf, type)) != 0)
1092 				goto done;
1093 			break;
1094 
1095 		case CRYPTO_AES_GCM_16:
1096 		case CRYPTO_AES_GMAC:
1097 		case CRYPTO_AES_128_GMAC:
1098 		case CRYPTO_AES_192_GMAC:
1099 		case CRYPTO_AES_256_GMAC:
1100 		case CRYPTO_CHACHA20_POLY1305:
1101 		case CRYPTO_CHACHA20_POLY1305_MAC:
1102 			crp->crp_etype = swcr_authenc(crp);
1103 			goto done;
1104 
1105 		case CRYPTO_DEFLATE_COMP:
1106 			if ((crp->crp_etype = swcr_compdec(crd, sw,
1107 			    crp->crp_buf, type)) != 0)
1108 				goto done;
1109 			else
1110 				crp->crp_olen = (int)sw->sw_size;
1111 			break;
1112 
1113 		default:
1114 			/* Unknown/unsupported algorithm */
1115 			crp->crp_etype = EINVAL;
1116 			goto done;
1117 		}
1118 	}
1119 
1120 done:
1121 	crypto_done(crp);
1122 	return 0;
1123 }
1124 
1125 /*
1126  * Initialize the driver, called from the kernel main().
1127  */
1128 void
1129 swcr_init(void)
1130 {
1131 	int algs[CRYPTO_ALGORITHM_MAX + 1];
1132 	int flags = CRYPTOCAP_F_SOFTWARE;
1133 
1134 	swcr_id = crypto_get_driverid(flags);
1135 	if (swcr_id < 0) {
1136 		/* This should never happen */
1137 		panic("Software crypto device cannot initialize!");
1138 	}
1139 
1140 	bzero(algs, sizeof(algs));
1141 
1142 	algs[CRYPTO_3DES_CBC] = CRYPTO_ALG_FLAG_SUPPORTED;
1143 	algs[CRYPTO_BLF_CBC] = CRYPTO_ALG_FLAG_SUPPORTED;
1144 	algs[CRYPTO_CAST_CBC] = CRYPTO_ALG_FLAG_SUPPORTED;
1145 	algs[CRYPTO_MD5_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1146 	algs[CRYPTO_SHA1_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1147 	algs[CRYPTO_RIPEMD160_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1148 	algs[CRYPTO_RIJNDAEL128_CBC] = CRYPTO_ALG_FLAG_SUPPORTED;
1149 	algs[CRYPTO_AES_CTR] = CRYPTO_ALG_FLAG_SUPPORTED;
1150 	algs[CRYPTO_AES_XTS] = CRYPTO_ALG_FLAG_SUPPORTED;
1151 	algs[CRYPTO_AES_GCM_16] = CRYPTO_ALG_FLAG_SUPPORTED;
1152 	algs[CRYPTO_AES_GMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1153 	algs[CRYPTO_DEFLATE_COMP] = CRYPTO_ALG_FLAG_SUPPORTED;
1154 	algs[CRYPTO_NULL] = CRYPTO_ALG_FLAG_SUPPORTED;
1155 	algs[CRYPTO_SHA2_256_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1156 	algs[CRYPTO_SHA2_384_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1157 	algs[CRYPTO_SHA2_512_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1158 	algs[CRYPTO_AES_128_GMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1159 	algs[CRYPTO_AES_192_GMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1160 	algs[CRYPTO_AES_256_GMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1161 	algs[CRYPTO_CHACHA20_POLY1305] = CRYPTO_ALG_FLAG_SUPPORTED;
1162 	algs[CRYPTO_CHACHA20_POLY1305_MAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1163 	algs[CRYPTO_ESN] = CRYPTO_ALG_FLAG_SUPPORTED;
1164 
1165 	crypto_register(swcr_id, algs, swcr_newsession,
1166 	    swcr_freesession, swcr_process);
1167 }
1168