xref: /openbsd-src/sys/crypto/cryptosoft.c (revision fcde59b201a29a2b4570b00b71e7aa25d61cb5c1)
1 /*	$OpenBSD: cryptosoft.c,v 1.86 2020/05/29 01:22:53 deraadt 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 <crypto/md5.h>
30 #include <crypto/sha1.h>
31 #include <crypto/rmd160.h>
32 #include <crypto/cast.h>
33 #include <crypto/cryptodev.h>
34 #include <crypto/cryptosoft.h>
35 #include <crypto/xform.h>
36 
37 const u_int8_t hmac_ipad_buffer[HMAC_MAX_BLOCK_LEN] = {
38 	0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
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 };
55 
56 const u_int8_t hmac_opad_buffer[HMAC_MAX_BLOCK_LEN] = {
57 	0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
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 };
74 
75 
76 struct swcr_data **swcr_sessions = NULL;
77 u_int32_t swcr_sesnum = 0;
78 int32_t swcr_id = -1;
79 
80 #define COPYBACK(x, a, b, c, d) \
81 	do { \
82 		if ((x) == CRYPTO_BUF_MBUF) \
83 			m_copyback((struct mbuf *)a,b,c,d,M_NOWAIT); \
84 		else \
85 			cuio_copyback((struct uio *)a,b,c,d); \
86 	} while (0)
87 #define COPYDATA(x, a, b, c, d) \
88 	do { \
89 		if ((x) == CRYPTO_BUF_MBUF) \
90 			m_copydata((struct mbuf *)a,b,c,d); \
91 		else \
92 			cuio_copydata((struct uio *)a,b,c,d); \
93 	} while (0)
94 
95 /*
96  * Apply a symmetric encryption/decryption algorithm.
97  */
98 int
99 swcr_encdec(struct cryptodesc *crd, struct swcr_data *sw, caddr_t buf,
100     int outtype)
101 {
102 	unsigned char iv[EALG_MAX_BLOCK_LEN], blk[EALG_MAX_BLOCK_LEN], *idat;
103 	unsigned char *ivp, *nivp, iv2[EALG_MAX_BLOCK_LEN];
104 	struct enc_xform *exf;
105 	int i, k, j, blks, ind, count, ivlen;
106 	struct mbuf *m = NULL;
107 	struct uio *uio = NULL;
108 
109 	exf = sw->sw_exf;
110 	blks = exf->blocksize;
111 	ivlen = exf->ivsize;
112 
113 	/* Check for non-padded data */
114 	if (crd->crd_len % blks)
115 		return EINVAL;
116 
117 	if (outtype == CRYPTO_BUF_MBUF)
118 		m = (struct mbuf *) buf;
119 	else
120 		uio = (struct uio *) buf;
121 
122 	/* Initialize the IV */
123 	if (crd->crd_flags & CRD_F_ENCRYPT) {
124 		/* IV explicitly provided ? */
125 		if (crd->crd_flags & CRD_F_IV_EXPLICIT)
126 			bcopy(crd->crd_iv, iv, ivlen);
127 		else
128 			arc4random_buf(iv, ivlen);
129 
130 		/* Do we need to write the IV */
131 		if (!(crd->crd_flags & CRD_F_IV_PRESENT))
132 			COPYBACK(outtype, buf, crd->crd_inject, ivlen, iv);
133 
134 	} else {	/* Decryption */
135 			/* IV explicitly provided ? */
136 		if (crd->crd_flags & CRD_F_IV_EXPLICIT)
137 			bcopy(crd->crd_iv, iv, ivlen);
138 		else {
139 			/* Get IV off buf */
140 			COPYDATA(outtype, buf, crd->crd_inject, ivlen, iv);
141 		}
142 	}
143 
144 	ivp = iv;
145 
146 	/*
147 	 * xforms that provide a reinit method perform all IV
148 	 * handling themselves.
149 	 */
150 	if (exf->reinit)
151 		exf->reinit(sw->sw_kschedule, iv);
152 
153 	if (outtype == CRYPTO_BUF_MBUF) {
154 		/* Find beginning of data */
155 		m = m_getptr(m, crd->crd_skip, &k);
156 		if (m == NULL)
157 			return EINVAL;
158 
159 		i = crd->crd_len;
160 
161 		while (i > 0) {
162 			/*
163 			 * If there's insufficient data at the end of
164 			 * an mbuf, we have to do some copying.
165 			 */
166 			if (m->m_len < k + blks && m->m_len != k) {
167 				m_copydata(m, k, blks, blk);
168 
169 				/* Actual encryption/decryption */
170 				if (exf->reinit) {
171 					if (crd->crd_flags & CRD_F_ENCRYPT) {
172 						exf->encrypt(sw->sw_kschedule,
173 						    blk);
174 					} else {
175 						exf->decrypt(sw->sw_kschedule,
176 						    blk);
177 					}
178 				} else if (crd->crd_flags & CRD_F_ENCRYPT) {
179 					/* XOR with previous block */
180 					for (j = 0; j < blks; j++)
181 						blk[j] ^= ivp[j];
182 
183 					exf->encrypt(sw->sw_kschedule, blk);
184 
185 					/*
186 					 * Keep encrypted block for XOR'ing
187 					 * with next block
188 					 */
189 					bcopy(blk, iv, blks);
190 					ivp = iv;
191 				} else {	/* decrypt */
192 					/*
193 					 * Keep encrypted block for XOR'ing
194 					 * with next block
195 					 */
196 					nivp = (ivp == iv) ? iv2 : iv;
197 					bcopy(blk, nivp, blks);
198 
199 					exf->decrypt(sw->sw_kschedule, blk);
200 
201 					/* XOR with previous block */
202 					for (j = 0; j < blks; j++)
203 						blk[j] ^= ivp[j];
204 					ivp = nivp;
205 				}
206 
207 				/* Copy back decrypted block */
208 				m_copyback(m, k, blks, blk, M_NOWAIT);
209 
210 				/* Advance pointer */
211 				m = m_getptr(m, k + blks, &k);
212 				if (m == NULL)
213 					return EINVAL;
214 
215 				i -= blks;
216 
217 				/* Could be done... */
218 				if (i == 0)
219 					break;
220 			}
221 
222 			/* Skip possibly empty mbufs */
223 			if (k == m->m_len) {
224 				for (m = m->m_next; m && m->m_len == 0;
225 				    m = m->m_next)
226 					;
227 				k = 0;
228 			}
229 
230 			/* Sanity check */
231 			if (m == NULL)
232 				return EINVAL;
233 
234 			/*
235 			 * Warning: idat may point to garbage here, but
236 			 * we only use it in the while() loop, only if
237 			 * there are indeed enough data.
238 			 */
239 			idat = mtod(m, unsigned char *) + k;
240 
241 			while (m->m_len >= k + blks && i > 0) {
242 				if (exf->reinit) {
243 					if (crd->crd_flags & CRD_F_ENCRYPT) {
244 						exf->encrypt(sw->sw_kschedule,
245 						    idat);
246 					} else {
247 						exf->decrypt(sw->sw_kschedule,
248 						    idat);
249 					}
250 				} else if (crd->crd_flags & CRD_F_ENCRYPT) {
251 					/* XOR with previous block/IV */
252 					for (j = 0; j < blks; j++)
253 						idat[j] ^= ivp[j];
254 
255 					exf->encrypt(sw->sw_kschedule, idat);
256 					ivp = idat;
257 				} else {	/* decrypt */
258 					/*
259 					 * Keep encrypted block to be used
260 					 * in next block's processing.
261 					 */
262 					nivp = (ivp == iv) ? iv2 : iv;
263 					bcopy(idat, nivp, blks);
264 
265 					exf->decrypt(sw->sw_kschedule, idat);
266 
267 					/* XOR with previous block/IV */
268 					for (j = 0; j < blks; j++)
269 						idat[j] ^= ivp[j];
270 					ivp = nivp;
271 				}
272 
273 				idat += blks;
274 				k += blks;
275 				i -= blks;
276 			}
277 		}
278 	} else {
279 		/* Find beginning of data */
280 		count = crd->crd_skip;
281 		ind = cuio_getptr(uio, count, &k);
282 		if (ind == -1)
283 			return EINVAL;
284 
285 		i = crd->crd_len;
286 
287 		while (i > 0) {
288 			/*
289 			 * If there's insufficient data at the end,
290 			 * we have to do some copying.
291 			 */
292 			if (uio->uio_iov[ind].iov_len < k + blks &&
293 			    uio->uio_iov[ind].iov_len != k) {
294 				cuio_copydata(uio, count, blks, blk);
295 
296 				/* Actual encryption/decryption */
297 				if (exf->reinit) {
298 					if (crd->crd_flags & CRD_F_ENCRYPT) {
299 						exf->encrypt(sw->sw_kschedule,
300 						    blk);
301 					} else {
302 						exf->decrypt(sw->sw_kschedule,
303 						    blk);
304 					}
305 				} else if (crd->crd_flags & CRD_F_ENCRYPT) {
306 					/* XOR with previous block */
307 					for (j = 0; j < blks; j++)
308 						blk[j] ^= ivp[j];
309 
310 					exf->encrypt(sw->sw_kschedule, blk);
311 
312 					/*
313 					 * Keep encrypted block for XOR'ing
314 					 * with next block
315 					 */
316 					bcopy(blk, iv, blks);
317 					ivp = iv;
318 				} else {	/* decrypt */
319 					/*
320 					 * Keep encrypted block for XOR'ing
321 					 * with next block
322 					 */
323 					nivp = (ivp == iv) ? iv2 : iv;
324 					bcopy(blk, nivp, blks);
325 
326 					exf->decrypt(sw->sw_kschedule, blk);
327 
328 					/* XOR with previous block */
329 					for (j = 0; j < blks; j++)
330 						blk[j] ^= ivp[j];
331 					ivp = nivp;
332 				}
333 
334 				/* Copy back decrypted block */
335 				cuio_copyback(uio, count, blks, blk);
336 
337 				count += blks;
338 
339 				/* Advance pointer */
340 				ind = cuio_getptr(uio, count, &k);
341 				if (ind == -1)
342 					return (EINVAL);
343 
344 				i -= blks;
345 
346 				/* Could be done... */
347 				if (i == 0)
348 					break;
349 			}
350 
351 			/*
352 			 * Warning: idat may point to garbage here, but
353 			 * we only use it in the while() loop, only if
354 			 * there are indeed enough data.
355 			 */
356 			idat = (char *)uio->uio_iov[ind].iov_base + k;
357 
358 			while (uio->uio_iov[ind].iov_len >= k + blks &&
359 			    i > 0) {
360 				if (exf->reinit) {
361 					if (crd->crd_flags & CRD_F_ENCRYPT) {
362 						exf->encrypt(sw->sw_kschedule,
363 						    idat);
364 					} else {
365 						exf->decrypt(sw->sw_kschedule,
366 						    idat);
367 					}
368 				} else if (crd->crd_flags & CRD_F_ENCRYPT) {
369 					/* XOR with previous block/IV */
370 					for (j = 0; j < blks; j++)
371 						idat[j] ^= ivp[j];
372 
373 					exf->encrypt(sw->sw_kschedule, idat);
374 					ivp = idat;
375 				} else {	/* decrypt */
376 					/*
377 					 * Keep encrypted block to be used
378 					 * in next block's processing.
379 					 */
380 					nivp = (ivp == iv) ? iv2 : iv;
381 					bcopy(idat, nivp, blks);
382 
383 					exf->decrypt(sw->sw_kschedule, idat);
384 
385 					/* XOR with previous block/IV */
386 					for (j = 0; j < blks; j++)
387 						idat[j] ^= ivp[j];
388 					ivp = nivp;
389 				}
390 
391 				idat += blks;
392 				count += blks;
393 				k += blks;
394 				i -= blks;
395 			}
396 
397 			/*
398 			 * Advance to the next iov if the end of the current iov
399 			 * is aligned with the end of a cipher block.
400 			 * Note that the code is equivalent to calling:
401 			 *	ind = cuio_getptr(uio, count, &k);
402 			 */
403 			if (i > 0 && k == uio->uio_iov[ind].iov_len) {
404 				k = 0;
405 				ind++;
406 				if (ind >= uio->uio_iovcnt)
407 					return (EINVAL);
408 			}
409 		}
410 	}
411 
412 	return 0; /* Done with encryption/decryption */
413 }
414 
415 /*
416  * Compute keyed-hash authenticator.
417  */
418 int
419 swcr_authcompute(struct cryptop *crp, struct cryptodesc *crd,
420     struct swcr_data *sw, caddr_t buf, int outtype)
421 {
422 	unsigned char aalg[AALG_MAX_RESULT_LEN];
423 	struct auth_hash *axf;
424 	union authctx ctx;
425 	int err;
426 
427 	if (sw->sw_ictx == 0)
428 		return EINVAL;
429 
430 	axf = sw->sw_axf;
431 
432 	bcopy(sw->sw_ictx, &ctx, axf->ctxsize);
433 
434 	if (outtype == CRYPTO_BUF_MBUF)
435 		err = m_apply((struct mbuf *) buf, crd->crd_skip, crd->crd_len,
436 		    (int (*)(caddr_t, caddr_t, unsigned int)) axf->Update,
437 		    (caddr_t) &ctx);
438 	else
439 		err = cuio_apply((struct uio *) buf, crd->crd_skip,
440 		    crd->crd_len,
441 		    (int (*)(caddr_t, caddr_t, unsigned int)) axf->Update,
442 		    (caddr_t) &ctx);
443 
444 	if (err)
445 		return err;
446 
447 	if (crd->crd_flags & CRD_F_ESN)
448 		axf->Update(&ctx, crd->crd_esn, 4);
449 
450 	switch (sw->sw_alg) {
451 	case CRYPTO_MD5_HMAC:
452 	case CRYPTO_SHA1_HMAC:
453 	case CRYPTO_RIPEMD160_HMAC:
454 	case CRYPTO_SHA2_256_HMAC:
455 	case CRYPTO_SHA2_384_HMAC:
456 	case CRYPTO_SHA2_512_HMAC:
457 		if (sw->sw_octx == NULL)
458 			return EINVAL;
459 
460 		axf->Final(aalg, &ctx);
461 		bcopy(sw->sw_octx, &ctx, axf->ctxsize);
462 		axf->Update(&ctx, aalg, axf->hashsize);
463 		axf->Final(aalg, &ctx);
464 		break;
465 	}
466 
467 	/* Inject the authentication data */
468 	if (outtype == CRYPTO_BUF_MBUF)
469 		COPYBACK(outtype, buf, crd->crd_inject, axf->authsize, aalg);
470 	else
471 		bcopy(aalg, crp->crp_mac, axf->authsize);
472 
473 	return 0;
474 }
475 
476 /*
477  * Apply a combined encryption-authentication transformation
478  */
479 int
480 swcr_authenc(struct cryptop *crp)
481 {
482 	uint32_t blkbuf[howmany(EALG_MAX_BLOCK_LEN, sizeof(uint32_t))];
483 	u_char *blk = (u_char *)blkbuf;
484 	u_char aalg[AALG_MAX_RESULT_LEN];
485 	u_char iv[EALG_MAX_BLOCK_LEN];
486 	union authctx ctx;
487 	struct cryptodesc *crd, *crda = NULL, *crde = NULL;
488 	struct swcr_data *sw, *swa, *swe = NULL;
489 	struct auth_hash *axf = NULL;
490 	struct enc_xform *exf = NULL;
491 	caddr_t buf = (caddr_t)crp->crp_buf;
492 	uint32_t *blkp;
493 	int aadlen, blksz, i, ivlen, outtype, len, iskip, oskip;
494 
495 	ivlen = blksz = iskip = oskip = 0;
496 
497 	for (i = 0; i < crp->crp_ndesc; i++) {
498 		crd = &crp->crp_desc[i];
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, result);
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, result);
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_AES_CBC:
798 			txf = &enc_xform_aes;
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_AES_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,
974 				    txf->ctxsize);
975 			}
976 			break;
977 
978 		case CRYPTO_MD5_HMAC:
979 		case CRYPTO_SHA1_HMAC:
980 		case CRYPTO_RIPEMD160_HMAC:
981 		case CRYPTO_SHA2_256_HMAC:
982 		case CRYPTO_SHA2_384_HMAC:
983 		case CRYPTO_SHA2_512_HMAC:
984 			axf = swd->sw_axf;
985 
986 			if (swd->sw_ictx) {
987 				explicit_bzero(swd->sw_ictx, axf->ctxsize);
988 				free(swd->sw_ictx, M_CRYPTO_DATA, axf->ctxsize);
989 			}
990 			if (swd->sw_octx) {
991 				explicit_bzero(swd->sw_octx, axf->ctxsize);
992 				free(swd->sw_octx, M_CRYPTO_DATA, axf->ctxsize);
993 			}
994 			break;
995 
996 		case CRYPTO_AES_128_GMAC:
997 		case CRYPTO_AES_192_GMAC:
998 		case CRYPTO_AES_256_GMAC:
999 		case CRYPTO_CHACHA20_POLY1305_MAC:
1000 			axf = swd->sw_axf;
1001 
1002 			if (swd->sw_ictx) {
1003 				explicit_bzero(swd->sw_ictx, axf->ctxsize);
1004 				free(swd->sw_ictx, M_CRYPTO_DATA, axf->ctxsize);
1005 			}
1006 			break;
1007 		}
1008 
1009 		free(swd, M_CRYPTO_DATA, sizeof(*swd));
1010 	}
1011 	return 0;
1012 }
1013 
1014 /*
1015  * Process a software request.
1016  */
1017 int
1018 swcr_process(struct cryptop *crp)
1019 {
1020 	struct cryptodesc *crd;
1021 	struct swcr_data *sw;
1022 	u_int32_t lid;
1023 	int type;
1024 	int i;
1025 
1026 	/* Sanity check */
1027 	if (crp == NULL)
1028 		return EINVAL;
1029 
1030 	if (crp->crp_ndesc < 1 || crp->crp_buf == NULL) {
1031 		crp->crp_etype = EINVAL;
1032 		goto done;
1033 	}
1034 
1035 	lid = crp->crp_sid & 0xffffffff;
1036 	if (lid >= swcr_sesnum || lid == 0 || swcr_sessions[lid] == NULL) {
1037 		crp->crp_etype = ENOENT;
1038 		goto done;
1039 	}
1040 
1041 	if (crp->crp_flags & CRYPTO_F_IMBUF)
1042 		type = CRYPTO_BUF_MBUF;
1043 	else
1044 		type = CRYPTO_BUF_IOV;
1045 
1046 	/* Go through crypto descriptors, processing as we go */
1047 	for (i = 0; i < crp->crp_ndesc; i++) {
1048 		crd = &crp->crp_desc[i];
1049 		/*
1050 		 * Find the crypto context.
1051 		 *
1052 		 * XXX Note that the logic here prevents us from having
1053 		 * XXX the same algorithm multiple times in a session
1054 		 * XXX (or rather, we can but it won't give us the right
1055 		 * XXX results). To do that, we'd need some way of differentiating
1056 		 * XXX between the various instances of an algorithm (so we can
1057 		 * XXX locate the correct crypto context).
1058 		 */
1059 		for (sw = swcr_sessions[lid];
1060 		    sw && sw->sw_alg != crd->crd_alg;
1061 		    sw = sw->sw_next)
1062 			;
1063 
1064 		/* No such context ? */
1065 		if (sw == NULL) {
1066 			crp->crp_etype = EINVAL;
1067 			goto done;
1068 		}
1069 
1070 		switch (sw->sw_alg) {
1071 		case CRYPTO_NULL:
1072 			break;
1073 		case CRYPTO_3DES_CBC:
1074 		case CRYPTO_BLF_CBC:
1075 		case CRYPTO_CAST_CBC:
1076 		case CRYPTO_RIJNDAEL128_CBC:
1077 		case CRYPTO_AES_CTR:
1078 		case CRYPTO_AES_XTS:
1079 			if ((crp->crp_etype = swcr_encdec(crd, sw,
1080 			    crp->crp_buf, type)) != 0)
1081 				goto done;
1082 			break;
1083 		case CRYPTO_MD5_HMAC:
1084 		case CRYPTO_SHA1_HMAC:
1085 		case CRYPTO_RIPEMD160_HMAC:
1086 		case CRYPTO_SHA2_256_HMAC:
1087 		case CRYPTO_SHA2_384_HMAC:
1088 		case CRYPTO_SHA2_512_HMAC:
1089 			if ((crp->crp_etype = swcr_authcompute(crp, crd, sw,
1090 			    crp->crp_buf, type)) != 0)
1091 				goto done;
1092 			break;
1093 
1094 		case CRYPTO_AES_GCM_16:
1095 		case CRYPTO_AES_GMAC:
1096 		case CRYPTO_AES_128_GMAC:
1097 		case CRYPTO_AES_192_GMAC:
1098 		case CRYPTO_AES_256_GMAC:
1099 		case CRYPTO_CHACHA20_POLY1305:
1100 		case CRYPTO_CHACHA20_POLY1305_MAC:
1101 			crp->crp_etype = swcr_authenc(crp);
1102 			goto done;
1103 
1104 		case CRYPTO_DEFLATE_COMP:
1105 			if ((crp->crp_etype = swcr_compdec(crd, sw,
1106 			    crp->crp_buf, type)) != 0)
1107 				goto done;
1108 			else
1109 				crp->crp_olen = (int)sw->sw_size;
1110 			break;
1111 
1112 		default:
1113 			/* Unknown/unsupported algorithm */
1114 			crp->crp_etype = EINVAL;
1115 			goto done;
1116 		}
1117 	}
1118 
1119 done:
1120 	crypto_done(crp);
1121 	return 0;
1122 }
1123 
1124 /*
1125  * Initialize the driver, called from the kernel main().
1126  */
1127 void
1128 swcr_init(void)
1129 {
1130 	int algs[CRYPTO_ALGORITHM_MAX + 1];
1131 	int flags = CRYPTOCAP_F_SOFTWARE;
1132 
1133 	swcr_id = crypto_get_driverid(flags);
1134 	if (swcr_id < 0) {
1135 		/* This should never happen */
1136 		panic("Software crypto device cannot initialize!");
1137 	}
1138 
1139 	bzero(algs, sizeof(algs));
1140 
1141 	algs[CRYPTO_3DES_CBC] = CRYPTO_ALG_FLAG_SUPPORTED;
1142 	algs[CRYPTO_BLF_CBC] = CRYPTO_ALG_FLAG_SUPPORTED;
1143 	algs[CRYPTO_CAST_CBC] = CRYPTO_ALG_FLAG_SUPPORTED;
1144 	algs[CRYPTO_MD5_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1145 	algs[CRYPTO_SHA1_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1146 	algs[CRYPTO_RIPEMD160_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1147 	algs[CRYPTO_AES_CBC] = CRYPTO_ALG_FLAG_SUPPORTED;
1148 	algs[CRYPTO_AES_CTR] = CRYPTO_ALG_FLAG_SUPPORTED;
1149 	algs[CRYPTO_AES_XTS] = CRYPTO_ALG_FLAG_SUPPORTED;
1150 	algs[CRYPTO_AES_GCM_16] = CRYPTO_ALG_FLAG_SUPPORTED;
1151 	algs[CRYPTO_AES_GMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1152 	algs[CRYPTO_DEFLATE_COMP] = CRYPTO_ALG_FLAG_SUPPORTED;
1153 	algs[CRYPTO_NULL] = CRYPTO_ALG_FLAG_SUPPORTED;
1154 	algs[CRYPTO_SHA2_256_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1155 	algs[CRYPTO_SHA2_384_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1156 	algs[CRYPTO_SHA2_512_HMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1157 	algs[CRYPTO_AES_128_GMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1158 	algs[CRYPTO_AES_192_GMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1159 	algs[CRYPTO_AES_256_GMAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1160 	algs[CRYPTO_CHACHA20_POLY1305] = CRYPTO_ALG_FLAG_SUPPORTED;
1161 	algs[CRYPTO_CHACHA20_POLY1305_MAC] = CRYPTO_ALG_FLAG_SUPPORTED;
1162 	algs[CRYPTO_ESN] = CRYPTO_ALG_FLAG_SUPPORTED;
1163 
1164 	crypto_register(swcr_id, algs, swcr_newsession,
1165 	    swcr_freesession, swcr_process);
1166 }
1167