xref: /openbsd/sys/crypto/cryptosoft.c (revision fc61954a)
1 /*	$OpenBSD: cryptosoft.c,v 1.81 2016/09/02 09:12:49 tom 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 	caddr_t buf = (caddr_t)crp->crp_buf;
493 	uint32_t *blkp;
494 	int aadlen, blksz, i, ivlen, outtype, len, iskip, oskip;
495 
496 	ivlen = blksz = iskip = oskip = 0;
497 
498 	for (crd = crp->crp_desc; crd; crd = crd->crd_next) {
499 		for (sw = swcr_sessions[crp->crp_sid & 0xffffffff];
500 		     sw && sw->sw_alg != crd->crd_alg;
501 		     sw = sw->sw_next)
502 			;
503 		if (sw == NULL)
504 			return (EINVAL);
505 
506 		switch (sw->sw_alg) {
507 		case CRYPTO_AES_GCM_16:
508 		case CRYPTO_AES_GMAC:
509 		case CRYPTO_CHACHA20_POLY1305:
510 			swe = sw;
511 			crde = crd;
512 			exf = swe->sw_exf;
513 			ivlen = exf->ivsize;
514 			break;
515 		case CRYPTO_AES_128_GMAC:
516 		case CRYPTO_AES_192_GMAC:
517 		case CRYPTO_AES_256_GMAC:
518 		case CRYPTO_CHACHA20_POLY1305_MAC:
519 			swa = sw;
520 			crda = crd;
521 			axf = swa->sw_axf;
522 			if (swa->sw_ictx == 0)
523 				return (EINVAL);
524 			bcopy(swa->sw_ictx, &ctx, axf->ctxsize);
525 			blksz = axf->blocksize;
526 			break;
527 		default:
528 			return (EINVAL);
529 		}
530 	}
531 	if (crde == NULL || crda == NULL)
532 		return (EINVAL);
533 
534 	if (crp->crp_flags & CRYPTO_F_IMBUF) {
535 		outtype = CRYPTO_BUF_MBUF;
536 	} else {
537 		outtype = CRYPTO_BUF_IOV;
538 	}
539 
540 	/* Initialize the IV */
541 	if (crde->crd_flags & CRD_F_ENCRYPT) {
542 		/* IV explicitly provided ? */
543 		if (crde->crd_flags & CRD_F_IV_EXPLICIT)
544 			bcopy(crde->crd_iv, iv, ivlen);
545 		else
546 			arc4random_buf(iv, ivlen);
547 
548 		/* Do we need to write the IV */
549 		if (!(crde->crd_flags & CRD_F_IV_PRESENT))
550 			COPYBACK(outtype, buf, crde->crd_inject, ivlen, iv);
551 
552 	} else {	/* Decryption */
553 			/* IV explicitly provided ? */
554 		if (crde->crd_flags & CRD_F_IV_EXPLICIT)
555 			bcopy(crde->crd_iv, iv, ivlen);
556 		else {
557 			/* Get IV off buf */
558 			COPYDATA(outtype, buf, crde->crd_inject, ivlen, iv);
559 		}
560 	}
561 
562 	/* Supply MAC with IV */
563 	if (axf->Reinit)
564 		axf->Reinit(&ctx, iv, ivlen);
565 
566 	/* Supply MAC with AAD */
567 	aadlen = crda->crd_len;
568 	/*
569 	 * Section 5 of RFC 4106 specifies that AAD construction consists of
570 	 * {SPI, ESN, SN} whereas the real packet contains only {SPI, SN}.
571 	 * Unfortunately it doesn't follow a good example set in the Section
572 	 * 3.3.2.1 of RFC 4303 where upper part of the ESN, located in the
573 	 * external (to the packet) memory buffer, is processed by the hash
574 	 * function in the end thus allowing to retain simple programming
575 	 * interfaces and avoid kludges like the one below.
576 	 */
577 	if (crda->crd_flags & CRD_F_ESN) {
578 		aadlen += 4;
579 		/* SPI */
580 		COPYDATA(outtype, buf, crda->crd_skip, 4, blk);
581 		iskip = 4; /* loop below will start with an offset of 4 */
582 		/* ESN */
583 		bcopy(crda->crd_esn, blk + 4, 4);
584 		oskip = iskip + 4; /* offset output buffer blk by 8 */
585 	}
586 	for (i = iskip; i < crda->crd_len; i += axf->hashsize) {
587 		len = MIN(crda->crd_len - i, axf->hashsize - oskip);
588 		COPYDATA(outtype, buf, crda->crd_skip + i, len, blk + oskip);
589 		bzero(blk + len + oskip, axf->hashsize - len - oskip);
590 		axf->Update(&ctx, blk, axf->hashsize);
591 		oskip = 0; /* reset initial output offset */
592 	}
593 
594 	if (exf->reinit)
595 		exf->reinit(swe->sw_kschedule, iv);
596 
597 	/* Do encryption/decryption with MAC */
598 	for (i = 0; i < crde->crd_len; i += blksz) {
599 		len = MIN(crde->crd_len - i, blksz);
600 		if (len < blksz)
601 			bzero(blk, blksz);
602 		COPYDATA(outtype, buf, crde->crd_skip + i, len, blk);
603 		if (crde->crd_flags & CRD_F_ENCRYPT) {
604 			exf->encrypt(swe->sw_kschedule, blk);
605 			axf->Update(&ctx, blk, len);
606 		} else {
607 			axf->Update(&ctx, blk, len);
608 			exf->decrypt(swe->sw_kschedule, blk);
609 		}
610 		COPYBACK(outtype, buf, crde->crd_skip + i, len, blk);
611 	}
612 
613 	/* Do any required special finalization */
614 	switch (crda->crd_alg) {
615 		case CRYPTO_AES_128_GMAC:
616 		case CRYPTO_AES_192_GMAC:
617 		case CRYPTO_AES_256_GMAC:
618 			/* length block */
619 			bzero(blk, axf->hashsize);
620 			blkp = (uint32_t *)blk + 1;
621 			*blkp = htobe32(aadlen * 8);
622 			blkp = (uint32_t *)blk + 3;
623 			*blkp = htobe32(crde->crd_len * 8);
624 			axf->Update(&ctx, blk, axf->hashsize);
625 			break;
626 		case CRYPTO_CHACHA20_POLY1305_MAC:
627 			/* length block */
628 			bzero(blk, axf->hashsize);
629 			blkp = (uint32_t *)blk;
630 			*blkp = htole32(aadlen);
631 			blkp = (uint32_t *)blk + 2;
632 			*blkp = htole32(crde->crd_len);
633 			axf->Update(&ctx, blk, axf->hashsize);
634 			break;
635 	}
636 
637 	/* Finalize MAC */
638 	axf->Final(aalg, &ctx);
639 
640 	/* Inject the authentication data */
641 	if (outtype == CRYPTO_BUF_MBUF)
642 		COPYBACK(outtype, buf, crda->crd_inject, axf->authsize, aalg);
643 	else
644 		bcopy(aalg, crp->crp_mac, axf->authsize);
645 
646 	return (0);
647 }
648 
649 /*
650  * Apply a compression/decompression algorithm
651  */
652 int
653 swcr_compdec(struct cryptodesc *crd, struct swcr_data *sw,
654     caddr_t buf, int outtype)
655 {
656 	u_int8_t *data, *out;
657 	struct comp_algo *cxf;
658 	int adj;
659 	u_int32_t result;
660 
661 	cxf = sw->sw_cxf;
662 
663 	/* We must handle the whole buffer of data in one time
664 	 * then if there is not all the data in the mbuf, we must
665 	 * copy in a buffer.
666 	 */
667 
668 	data = malloc(crd->crd_len, M_CRYPTO_DATA, M_NOWAIT);
669 	if (data == NULL)
670 		return (EINVAL);
671 	COPYDATA(outtype, buf, crd->crd_skip, crd->crd_len, data);
672 
673 	if (crd->crd_flags & CRD_F_COMP)
674 		result = cxf->compress(data, crd->crd_len, &out);
675 	else
676 		result = cxf->decompress(data, crd->crd_len, &out);
677 
678 	free(data, M_CRYPTO_DATA, crd->crd_len);
679 	if (result == 0)
680 		return EINVAL;
681 
682 	/* Copy back the (de)compressed data. m_copyback is
683 	 * extending the mbuf as necessary.
684 	 */
685 	sw->sw_size = result;
686 	/* Check the compressed size when doing compression */
687 	if (crd->crd_flags & CRD_F_COMP) {
688 		if (result > crd->crd_len) {
689 			/* Compression was useless, we lost time */
690 			free(out, M_CRYPTO_DATA, 0);
691 			return 0;
692 		}
693 	}
694 
695 	COPYBACK(outtype, buf, crd->crd_skip, result, out);
696 	if (result < crd->crd_len) {
697 		adj = result - crd->crd_len;
698 		if (outtype == CRYPTO_BUF_MBUF) {
699 			adj = result - crd->crd_len;
700 			m_adj((struct mbuf *)buf, adj);
701 		} else {
702 			struct uio *uio = (struct uio *)buf;
703 			int ind;
704 
705 			adj = crd->crd_len - result;
706 			ind = uio->uio_iovcnt - 1;
707 
708 			while (adj > 0 && ind >= 0) {
709 				if (adj < uio->uio_iov[ind].iov_len) {
710 					uio->uio_iov[ind].iov_len -= adj;
711 					break;
712 				}
713 
714 				adj -= uio->uio_iov[ind].iov_len;
715 				uio->uio_iov[ind].iov_len = 0;
716 				ind--;
717 				uio->uio_iovcnt--;
718 			}
719 		}
720 	}
721 	free(out, M_CRYPTO_DATA, 0);
722 	return 0;
723 }
724 
725 /*
726  * Generate a new software session.
727  */
728 int
729 swcr_newsession(u_int32_t *sid, struct cryptoini *cri)
730 {
731 	struct swcr_data **swd;
732 	struct auth_hash *axf;
733 	struct enc_xform *txf;
734 	struct comp_algo *cxf;
735 	u_int32_t i;
736 	int k;
737 
738 	if (sid == NULL || cri == NULL)
739 		return EINVAL;
740 
741 	if (swcr_sessions) {
742 		for (i = 1; i < swcr_sesnum; i++)
743 			if (swcr_sessions[i] == NULL)
744 				break;
745 	}
746 
747 	if (swcr_sessions == NULL || i == swcr_sesnum) {
748 		if (swcr_sessions == NULL) {
749 			i = 1; /* We leave swcr_sessions[0] empty */
750 			swcr_sesnum = CRYPTO_SW_SESSIONS;
751 		} else
752 			swcr_sesnum *= 2;
753 
754 		swd = mallocarray(swcr_sesnum, sizeof(struct swcr_data *),
755 		    M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
756 		if (swd == NULL) {
757 			/* Reset session number */
758 			if (swcr_sesnum == CRYPTO_SW_SESSIONS)
759 				swcr_sesnum = 0;
760 			else
761 				swcr_sesnum /= 2;
762 			return ENOBUFS;
763 		}
764 
765 		/* Copy existing sessions */
766 		if (swcr_sessions) {
767 			bcopy(swcr_sessions, swd,
768 			    (swcr_sesnum / 2) * sizeof(struct swcr_data *));
769 			free(swcr_sessions, M_CRYPTO_DATA,
770 			    (swcr_sesnum / 2) * sizeof(struct swcr_data *));
771 		}
772 
773 		swcr_sessions = swd;
774 	}
775 
776 	swd = &swcr_sessions[i];
777 	*sid = i;
778 
779 	while (cri) {
780 		*swd = malloc(sizeof(struct swcr_data), M_CRYPTO_DATA,
781 		    M_NOWAIT | M_ZERO);
782 		if (*swd == NULL) {
783 			swcr_freesession(i);
784 			return ENOBUFS;
785 		}
786 
787 		switch (cri->cri_alg) {
788 		case CRYPTO_3DES_CBC:
789 			txf = &enc_xform_3des;
790 			goto enccommon;
791 		case CRYPTO_BLF_CBC:
792 			txf = &enc_xform_blf;
793 			goto enccommon;
794 		case CRYPTO_CAST_CBC:
795 			txf = &enc_xform_cast5;
796 			goto enccommon;
797 		case CRYPTO_RIJNDAEL128_CBC:
798 			txf = &enc_xform_rijndael128;
799 			goto enccommon;
800 		case CRYPTO_AES_CTR:
801 			txf = &enc_xform_aes_ctr;
802 			goto enccommon;
803 		case CRYPTO_AES_XTS:
804 			txf = &enc_xform_aes_xts;
805 			goto enccommon;
806 		case CRYPTO_AES_GCM_16:
807 			txf = &enc_xform_aes_gcm;
808 			goto enccommon;
809 		case CRYPTO_AES_GMAC:
810 			txf = &enc_xform_aes_gmac;
811 			(*swd)->sw_exf = txf;
812 			break;
813 		case CRYPTO_CHACHA20_POLY1305:
814 			txf = &enc_xform_chacha20_poly1305;
815 			goto enccommon;
816 		case CRYPTO_NULL:
817 			txf = &enc_xform_null;
818 			goto enccommon;
819 		enccommon:
820 			if (txf->ctxsize > 0) {
821 				(*swd)->sw_kschedule = malloc(txf->ctxsize,
822 				    M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
823 				if ((*swd)->sw_kschedule == NULL) {
824 					swcr_freesession(i);
825 					return EINVAL;
826 				}
827 			}
828 			if (txf->setkey((*swd)->sw_kschedule, cri->cri_key,
829 			    cri->cri_klen / 8) < 0) {
830 				swcr_freesession(i);
831 				return EINVAL;
832 			}
833 			(*swd)->sw_exf = txf;
834 			break;
835 
836 		case CRYPTO_MD5_HMAC:
837 			axf = &auth_hash_hmac_md5_96;
838 			goto authcommon;
839 		case CRYPTO_SHA1_HMAC:
840 			axf = &auth_hash_hmac_sha1_96;
841 			goto authcommon;
842 		case CRYPTO_RIPEMD160_HMAC:
843 			axf = &auth_hash_hmac_ripemd_160_96;
844 			goto authcommon;
845 		case CRYPTO_SHA2_256_HMAC:
846 			axf = &auth_hash_hmac_sha2_256_128;
847 			goto authcommon;
848 		case CRYPTO_SHA2_384_HMAC:
849 			axf = &auth_hash_hmac_sha2_384_192;
850 			goto authcommon;
851 		case CRYPTO_SHA2_512_HMAC:
852 			axf = &auth_hash_hmac_sha2_512_256;
853 			goto authcommon;
854 		authcommon:
855 			(*swd)->sw_ictx = malloc(axf->ctxsize, M_CRYPTO_DATA,
856 			    M_NOWAIT);
857 			if ((*swd)->sw_ictx == NULL) {
858 				swcr_freesession(i);
859 				return ENOBUFS;
860 			}
861 
862 			(*swd)->sw_octx = malloc(axf->ctxsize, M_CRYPTO_DATA,
863 			    M_NOWAIT);
864 			if ((*swd)->sw_octx == NULL) {
865 				swcr_freesession(i);
866 				return ENOBUFS;
867 			}
868 
869 			for (k = 0; k < cri->cri_klen / 8; k++)
870 				cri->cri_key[k] ^= HMAC_IPAD_VAL;
871 
872 			axf->Init((*swd)->sw_ictx);
873 			axf->Update((*swd)->sw_ictx, cri->cri_key,
874 			    cri->cri_klen / 8);
875 			axf->Update((*swd)->sw_ictx, hmac_ipad_buffer,
876 			    axf->blocksize - (cri->cri_klen / 8));
877 
878 			for (k = 0; k < cri->cri_klen / 8; k++)
879 				cri->cri_key[k] ^= (HMAC_IPAD_VAL ^ HMAC_OPAD_VAL);
880 
881 			axf->Init((*swd)->sw_octx);
882 			axf->Update((*swd)->sw_octx, cri->cri_key,
883 			    cri->cri_klen / 8);
884 			axf->Update((*swd)->sw_octx, hmac_opad_buffer,
885 			    axf->blocksize - (cri->cri_klen / 8));
886 
887 			for (k = 0; k < cri->cri_klen / 8; k++)
888 				cri->cri_key[k] ^= HMAC_OPAD_VAL;
889 			(*swd)->sw_axf = axf;
890 			break;
891 
892 		case CRYPTO_AES_128_GMAC:
893 			axf = &auth_hash_gmac_aes_128;
894 			goto authenccommon;
895 		case CRYPTO_AES_192_GMAC:
896 			axf = &auth_hash_gmac_aes_192;
897 			goto authenccommon;
898 		case CRYPTO_AES_256_GMAC:
899 			axf = &auth_hash_gmac_aes_256;
900 			goto authenccommon;
901 		case CRYPTO_CHACHA20_POLY1305_MAC:
902 			axf = &auth_hash_chacha20_poly1305;
903 			goto authenccommon;
904 		authenccommon:
905 			(*swd)->sw_ictx = malloc(axf->ctxsize, M_CRYPTO_DATA,
906 			    M_NOWAIT);
907 			if ((*swd)->sw_ictx == NULL) {
908 				swcr_freesession(i);
909 				return ENOBUFS;
910 			}
911 			axf->Init((*swd)->sw_ictx);
912 			axf->Setkey((*swd)->sw_ictx, cri->cri_key,
913 			    cri->cri_klen / 8);
914 			(*swd)->sw_axf = axf;
915 			break;
916 
917 		case CRYPTO_DEFLATE_COMP:
918 			cxf = &comp_algo_deflate;
919 			(*swd)->sw_cxf = cxf;
920 			break;
921 		case CRYPTO_ESN:
922 			/* nothing to do */
923 			break;
924 		default:
925 			swcr_freesession(i);
926 			return EINVAL;
927 		}
928 
929 		(*swd)->sw_alg = cri->cri_alg;
930 		cri = cri->cri_next;
931 		swd = &((*swd)->sw_next);
932 	}
933 	return 0;
934 }
935 
936 /*
937  * Free a session.
938  */
939 int
940 swcr_freesession(u_int64_t tid)
941 {
942 	struct swcr_data *swd;
943 	struct enc_xform *txf;
944 	struct auth_hash *axf;
945 	u_int32_t sid = ((u_int32_t) tid) & 0xffffffff;
946 
947 	if (sid > swcr_sesnum || swcr_sessions == NULL ||
948 	    swcr_sessions[sid] == NULL)
949 		return EINVAL;
950 
951 	/* Silently accept and return */
952 	if (sid == 0)
953 		return 0;
954 
955 	while ((swd = swcr_sessions[sid]) != NULL) {
956 		swcr_sessions[sid] = swd->sw_next;
957 
958 		switch (swd->sw_alg) {
959 		case CRYPTO_3DES_CBC:
960 		case CRYPTO_BLF_CBC:
961 		case CRYPTO_CAST_CBC:
962 		case CRYPTO_RIJNDAEL128_CBC:
963 		case CRYPTO_AES_CTR:
964 		case CRYPTO_AES_XTS:
965 		case CRYPTO_AES_GCM_16:
966 		case CRYPTO_AES_GMAC:
967 		case CRYPTO_CHACHA20_POLY1305:
968 		case CRYPTO_NULL:
969 			txf = swd->sw_exf;
970 
971 			if (swd->sw_kschedule) {
972 				explicit_bzero(swd->sw_kschedule, txf->ctxsize);
973 				free(swd->sw_kschedule, M_CRYPTO_DATA, 0);
974 			}
975 			break;
976 
977 		case CRYPTO_MD5_HMAC:
978 		case CRYPTO_SHA1_HMAC:
979 		case CRYPTO_RIPEMD160_HMAC:
980 		case CRYPTO_SHA2_256_HMAC:
981 		case CRYPTO_SHA2_384_HMAC:
982 		case CRYPTO_SHA2_512_HMAC:
983 			axf = swd->sw_axf;
984 
985 			if (swd->sw_ictx) {
986 				explicit_bzero(swd->sw_ictx, axf->ctxsize);
987 				free(swd->sw_ictx, M_CRYPTO_DATA, 0);
988 			}
989 			if (swd->sw_octx) {
990 				explicit_bzero(swd->sw_octx, axf->ctxsize);
991 				free(swd->sw_octx, M_CRYPTO_DATA, 0);
992 			}
993 			break;
994 
995 		case CRYPTO_AES_128_GMAC:
996 		case CRYPTO_AES_192_GMAC:
997 		case CRYPTO_AES_256_GMAC:
998 		case CRYPTO_CHACHA20_POLY1305_MAC:
999 			axf = swd->sw_axf;
1000 
1001 			if (swd->sw_ictx) {
1002 				explicit_bzero(swd->sw_ictx, axf->ctxsize);
1003 				free(swd->sw_ictx, M_CRYPTO_DATA, 0);
1004 			}
1005 			break;
1006 		}
1007 
1008 		free(swd, M_CRYPTO_DATA, 0);
1009 	}
1010 	return 0;
1011 }
1012 
1013 /*
1014  * Process a software request.
1015  */
1016 int
1017 swcr_process(struct cryptop *crp)
1018 {
1019 	struct cryptodesc *crd;
1020 	struct swcr_data *sw;
1021 	u_int32_t lid;
1022 	int type;
1023 
1024 	/* Sanity check */
1025 	if (crp == NULL)
1026 		return EINVAL;
1027 
1028 	if (crp->crp_desc == NULL || crp->crp_buf == NULL) {
1029 		crp->crp_etype = EINVAL;
1030 		goto done;
1031 	}
1032 
1033 	lid = crp->crp_sid & 0xffffffff;
1034 	if (lid >= swcr_sesnum || lid == 0 || swcr_sessions[lid] == NULL) {
1035 		crp->crp_etype = ENOENT;
1036 		goto done;
1037 	}
1038 
1039 	if (crp->crp_flags & CRYPTO_F_IMBUF)
1040 		type = CRYPTO_BUF_MBUF;
1041 	else
1042 		type = CRYPTO_BUF_IOV;
1043 
1044 	/* Go through crypto descriptors, processing as we go */
1045 	for (crd = crp->crp_desc; crd; crd = crd->crd_next) {
1046 		/*
1047 		 * Find the crypto context.
1048 		 *
1049 		 * XXX Note that the logic here prevents us from having
1050 		 * XXX the same algorithm multiple times in a session
1051 		 * XXX (or rather, we can but it won't give us the right
1052 		 * XXX results). To do that, we'd need some way of differentiating
1053 		 * XXX between the various instances of an algorithm (so we can
1054 		 * XXX locate the correct crypto context).
1055 		 */
1056 		for (sw = swcr_sessions[lid];
1057 		    sw && sw->sw_alg != crd->crd_alg;
1058 		    sw = sw->sw_next)
1059 			;
1060 
1061 		/* No such context ? */
1062 		if (sw == NULL) {
1063 			crp->crp_etype = EINVAL;
1064 			goto done;
1065 		}
1066 
1067 		switch (sw->sw_alg) {
1068 		case CRYPTO_NULL:
1069 			break;
1070 		case CRYPTO_3DES_CBC:
1071 		case CRYPTO_BLF_CBC:
1072 		case CRYPTO_CAST_CBC:
1073 		case CRYPTO_RIJNDAEL128_CBC:
1074 		case CRYPTO_AES_CTR:
1075 		case CRYPTO_AES_XTS:
1076 			if ((crp->crp_etype = swcr_encdec(crd, sw,
1077 			    crp->crp_buf, type)) != 0)
1078 				goto done;
1079 			break;
1080 		case CRYPTO_MD5_HMAC:
1081 		case CRYPTO_SHA1_HMAC:
1082 		case CRYPTO_RIPEMD160_HMAC:
1083 		case CRYPTO_SHA2_256_HMAC:
1084 		case CRYPTO_SHA2_384_HMAC:
1085 		case CRYPTO_SHA2_512_HMAC:
1086 			if ((crp->crp_etype = swcr_authcompute(crp, crd, sw,
1087 			    crp->crp_buf, type)) != 0)
1088 				goto done;
1089 			break;
1090 
1091 		case CRYPTO_AES_GCM_16:
1092 		case CRYPTO_AES_GMAC:
1093 		case CRYPTO_AES_128_GMAC:
1094 		case CRYPTO_AES_192_GMAC:
1095 		case CRYPTO_AES_256_GMAC:
1096 		case CRYPTO_CHACHA20_POLY1305:
1097 		case CRYPTO_CHACHA20_POLY1305_MAC:
1098 			crp->crp_etype = swcr_authenc(crp);
1099 			goto done;
1100 
1101 		case CRYPTO_DEFLATE_COMP:
1102 			if ((crp->crp_etype = swcr_compdec(crd, sw,
1103 			    crp->crp_buf, type)) != 0)
1104 				goto done;
1105 			else
1106 				crp->crp_olen = (int)sw->sw_size;
1107 			break;
1108 
1109 		default:
1110 			/* Unknown/unsupported algorithm */
1111 			crp->crp_etype = EINVAL;
1112 			goto done;
1113 		}
1114 	}
1115 
1116 done:
1117 	crypto_done(crp);
1118 	return 0;
1119 }
1120 
1121 /*
1122  * Initialize the driver, called from the kernel main().
1123  */
1124 void
1125 swcr_init(void)
1126 {
1127 	int algs[CRYPTO_ALGORITHM_MAX + 1];
1128 	int flags = CRYPTOCAP_F_SOFTWARE;
1129 
1130 	swcr_id = crypto_get_driverid(flags);
1131 	if (swcr_id < 0) {
1132 		/* This should never happen */
1133 		panic("Software crypto device cannot initialize!");
1134 	}
1135 
1136 	bzero(algs, sizeof(algs));
1137 
1138 	algs[CRYPTO_3DES_CBC] = CRYPTO_ALG_FLAG_SUPPORTED;
1139 	algs[CRYPTO_BLF_CBC] = CRYPTO_ALG_FLAG_SUPPORTED;
1140 	algs[CRYPTO_CAST_CBC] = CRYPTO_ALG_FLAG_SUPPORTED;
1141 	algs[CRYPTO_MD5_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1142 	algs[CRYPTO_SHA1_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1143 	algs[CRYPTO_RIPEMD160_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1144 	algs[CRYPTO_RIJNDAEL128_CBC] = CRYPTO_ALG_FLAG_SUPPORTED;
1145 	algs[CRYPTO_AES_CTR] = CRYPTO_ALG_FLAG_SUPPORTED;
1146 	algs[CRYPTO_AES_XTS] = CRYPTO_ALG_FLAG_SUPPORTED;
1147 	algs[CRYPTO_AES_GCM_16] = CRYPTO_ALG_FLAG_SUPPORTED;
1148 	algs[CRYPTO_AES_GMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1149 	algs[CRYPTO_DEFLATE_COMP] = CRYPTO_ALG_FLAG_SUPPORTED;
1150 	algs[CRYPTO_NULL] = CRYPTO_ALG_FLAG_SUPPORTED;
1151 	algs[CRYPTO_SHA2_256_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1152 	algs[CRYPTO_SHA2_384_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1153 	algs[CRYPTO_SHA2_512_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1154 	algs[CRYPTO_AES_128_GMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1155 	algs[CRYPTO_AES_192_GMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1156 	algs[CRYPTO_AES_256_GMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1157 	algs[CRYPTO_CHACHA20_POLY1305] = CRYPTO_ALG_FLAG_SUPPORTED;
1158 	algs[CRYPTO_CHACHA20_POLY1305_MAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1159 	algs[CRYPTO_ESN] = CRYPTO_ALG_FLAG_SUPPORTED;
1160 
1161 	crypto_register(swcr_id, algs, swcr_newsession,
1162 	    swcr_freesession, swcr_process);
1163 }
1164