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