xref: /freebsd/sys/opencrypto/cryptodev.c (revision a18eacbefdfa1085ca3db829e86ece78cd416493)
1 /*	$OpenBSD: cryptodev.c,v 1.52 2002/06/19 07:22:46 deraadt Exp $	*/
2 
3 /*-
4  * Copyright (c) 2001 Theo de Raadt
5  * Copyright (c) 2002-2006 Sam Leffler, Errno Consulting
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *   notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *   notice, this list of conditions and the following disclaimer in the
15  *   documentation and/or other materials provided with the distribution.
16  * 3. The name of the author may not be used to endorse or promote products
17  *   derived from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * Effort sponsored in part by the Defense Advanced Research Projects
31  * Agency (DARPA) and Air Force Research Laboratory, Air Force
32  * Materiel Command, USAF, under agreement number F30602-01-2-0537.
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "opt_compat.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/malloc.h>
43 #include <sys/mbuf.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/sysctl.h>
47 #include <sys/file.h>
48 #include <sys/filedesc.h>
49 #include <sys/errno.h>
50 #include <sys/uio.h>
51 #include <sys/random.h>
52 #include <sys/conf.h>
53 #include <sys/kernel.h>
54 #include <sys/module.h>
55 #include <sys/fcntl.h>
56 #include <sys/bus.h>
57 
58 #include <opencrypto/cryptodev.h>
59 #include <opencrypto/xform.h>
60 
61 #ifdef COMPAT_FREEBSD32
62 #include <sys/mount.h>
63 #include <compat/freebsd32/freebsd32.h>
64 
65 struct session_op32 {
66 	u_int32_t	cipher;
67 	u_int32_t	mac;
68 	u_int32_t	keylen;
69 	u_int32_t	key;
70 	int		mackeylen;
71 	u_int32_t	mackey;
72 	u_int32_t	ses;
73 };
74 
75 struct session2_op32 {
76 	u_int32_t	cipher;
77 	u_int32_t	mac;
78 	u_int32_t	keylen;
79 	u_int32_t	key;
80 	int		mackeylen;
81 	u_int32_t	mackey;
82 	u_int32_t	ses;
83 	int		crid;
84 	int		pad[4];
85 };
86 
87 struct crypt_op32 {
88 	u_int32_t	ses;
89 	u_int16_t	op;
90 	u_int16_t	flags;
91 	u_int		len;
92 	u_int32_t	src, dst;
93 	u_int32_t	mac;
94 	u_int32_t	iv;
95 };
96 
97 struct crparam32 {
98 	u_int32_t	crp_p;
99 	u_int		crp_nbits;
100 };
101 
102 struct crypt_kop32 {
103 	u_int		crk_op;
104 	u_int		crk_status;
105 	u_short		crk_iparams;
106 	u_short		crk_oparams;
107 	u_int		crk_crid;
108 	struct crparam32	crk_param[CRK_MAXPARAM];
109 };
110 
111 struct cryptotstat32 {
112 	struct timespec32	acc;
113 	struct timespec32	min;
114 	struct timespec32	max;
115 	u_int32_t	count;
116 };
117 
118 struct cryptostats32 {
119 	u_int32_t	cs_ops;
120 	u_int32_t	cs_errs;
121 	u_int32_t	cs_kops;
122 	u_int32_t	cs_kerrs;
123 	u_int32_t	cs_intrs;
124 	u_int32_t	cs_rets;
125 	u_int32_t	cs_blocks;
126 	u_int32_t	cs_kblocks;
127 	struct cryptotstat32 cs_invoke;
128 	struct cryptotstat32 cs_done;
129 	struct cryptotstat32 cs_cb;
130 	struct cryptotstat32 cs_finis;
131 };
132 
133 #define	CIOCGSESSION32	_IOWR('c', 101, struct session_op32)
134 #define	CIOCCRYPT32	_IOWR('c', 103, struct crypt_op32)
135 #define	CIOCKEY32	_IOWR('c', 104, struct crypt_kop32)
136 #define	CIOCGSESSION232	_IOWR('c', 106, struct session2_op32)
137 #define	CIOCKEY232	_IOWR('c', 107, struct crypt_kop32)
138 
139 static void
140 session_op_from_32(const struct session_op32 *from, struct session_op *to)
141 {
142 
143 	CP(*from, *to, cipher);
144 	CP(*from, *to, mac);
145 	CP(*from, *to, keylen);
146 	PTRIN_CP(*from, *to, key);
147 	CP(*from, *to, mackeylen);
148 	PTRIN_CP(*from, *to, mackey);
149 	CP(*from, *to, ses);
150 }
151 
152 static void
153 session2_op_from_32(const struct session2_op32 *from, struct session2_op *to)
154 {
155 
156 	session_op_from_32((const struct session_op32 *)from,
157 	    (struct session_op *)to);
158 	CP(*from, *to, crid);
159 }
160 
161 static void
162 session_op_to_32(const struct session_op *from, struct session_op32 *to)
163 {
164 
165 	CP(*from, *to, cipher);
166 	CP(*from, *to, mac);
167 	CP(*from, *to, keylen);
168 	PTROUT_CP(*from, *to, key);
169 	CP(*from, *to, mackeylen);
170 	PTROUT_CP(*from, *to, mackey);
171 	CP(*from, *to, ses);
172 }
173 
174 static void
175 session2_op_to_32(const struct session2_op *from, struct session2_op32 *to)
176 {
177 
178 	session_op_to_32((const struct session_op *)from,
179 	    (struct session_op32 *)to);
180 	CP(*from, *to, crid);
181 }
182 
183 static void
184 crypt_op_from_32(const struct crypt_op32 *from, struct crypt_op *to)
185 {
186 
187 	CP(*from, *to, ses);
188 	CP(*from, *to, op);
189 	CP(*from, *to, flags);
190 	CP(*from, *to, len);
191 	PTRIN_CP(*from, *to, src);
192 	PTRIN_CP(*from, *to, dst);
193 	PTRIN_CP(*from, *to, mac);
194 	PTRIN_CP(*from, *to, iv);
195 }
196 
197 static void
198 crypt_op_to_32(const struct crypt_op *from, struct crypt_op32 *to)
199 {
200 
201 	CP(*from, *to, ses);
202 	CP(*from, *to, op);
203 	CP(*from, *to, flags);
204 	CP(*from, *to, len);
205 	PTROUT_CP(*from, *to, src);
206 	PTROUT_CP(*from, *to, dst);
207 	PTROUT_CP(*from, *to, mac);
208 	PTROUT_CP(*from, *to, iv);
209 }
210 
211 static void
212 crparam_from_32(const struct crparam32 *from, struct crparam *to)
213 {
214 
215 	PTRIN_CP(*from, *to, crp_p);
216 	CP(*from, *to, crp_nbits);
217 }
218 
219 static void
220 crparam_to_32(const struct crparam *from, struct crparam32 *to)
221 {
222 
223 	PTROUT_CP(*from, *to, crp_p);
224 	CP(*from, *to, crp_nbits);
225 }
226 
227 static void
228 crypt_kop_from_32(const struct crypt_kop32 *from, struct crypt_kop *to)
229 {
230 	int i;
231 
232 	CP(*from, *to, crk_op);
233 	CP(*from, *to, crk_status);
234 	CP(*from, *to, crk_iparams);
235 	CP(*from, *to, crk_oparams);
236 	CP(*from, *to, crk_crid);
237 	for (i = 0; i < CRK_MAXPARAM; i++)
238 		crparam_from_32(&from->crk_param[i], &to->crk_param[i]);
239 }
240 
241 static void
242 crypt_kop_to_32(const struct crypt_kop *from, struct crypt_kop32 *to)
243 {
244 	int i;
245 
246 	CP(*from, *to, crk_op);
247 	CP(*from, *to, crk_status);
248 	CP(*from, *to, crk_iparams);
249 	CP(*from, *to, crk_oparams);
250 	CP(*from, *to, crk_crid);
251 	for (i = 0; i < CRK_MAXPARAM; i++)
252 		crparam_to_32(&from->crk_param[i], &to->crk_param[i]);
253 }
254 #endif
255 
256 struct csession {
257 	TAILQ_ENTRY(csession) next;
258 	u_int64_t	sid;
259 	u_int32_t	ses;
260 	struct mtx	lock;		/* for op submission */
261 
262 	u_int32_t	cipher;
263 	struct enc_xform *txform;
264 	u_int32_t	mac;
265 	struct auth_hash *thash;
266 
267 	caddr_t		key;
268 	int		keylen;
269 	u_char		tmp_iv[EALG_MAX_BLOCK_LEN];
270 
271 	caddr_t		mackey;
272 	int		mackeylen;
273 
274 	struct iovec	iovec;
275 	struct uio	uio;
276 	int		error;
277 };
278 
279 struct fcrypt {
280 	TAILQ_HEAD(csessionlist, csession) csessions;
281 	int		sesn;
282 };
283 
284 static	int cryptof_rw(struct file *fp, struct uio *uio,
285 		    struct ucred *cred, int flags, struct thread *);
286 static	int cryptof_truncate(struct file *, off_t, struct ucred *,
287 		    struct thread *);
288 static	int cryptof_ioctl(struct file *, u_long, void *,
289 		    struct ucred *, struct thread *);
290 static	int cryptof_poll(struct file *, int, struct ucred *, struct thread *);
291 static	int cryptof_kqfilter(struct file *, struct knote *);
292 static	int cryptof_stat(struct file *, struct stat *,
293 		    struct ucred *, struct thread *);
294 static	int cryptof_close(struct file *, struct thread *);
295 
296 static struct fileops cryptofops = {
297     .fo_read = cryptof_rw,
298     .fo_write = cryptof_rw,
299     .fo_truncate = cryptof_truncate,
300     .fo_ioctl = cryptof_ioctl,
301     .fo_poll = cryptof_poll,
302     .fo_kqfilter = cryptof_kqfilter,
303     .fo_stat = cryptof_stat,
304     .fo_close = cryptof_close,
305     .fo_chmod = invfo_chmod,
306     .fo_chown = invfo_chown,
307     .fo_sendfile = invfo_sendfile,
308 };
309 
310 static struct csession *csefind(struct fcrypt *, u_int);
311 static int csedelete(struct fcrypt *, struct csession *);
312 static struct csession *cseadd(struct fcrypt *, struct csession *);
313 static struct csession *csecreate(struct fcrypt *, u_int64_t, caddr_t,
314     u_int64_t, caddr_t, u_int64_t, u_int32_t, u_int32_t, struct enc_xform *,
315     struct auth_hash *);
316 static int csefree(struct csession *);
317 
318 static	int cryptodev_op(struct csession *, struct crypt_op *,
319 			struct ucred *, struct thread *td);
320 static	int cryptodev_key(struct crypt_kop *);
321 static	int cryptodev_find(struct crypt_find_op *);
322 
323 static int
324 cryptof_rw(
325 	struct file *fp,
326 	struct uio *uio,
327 	struct ucred *active_cred,
328 	int flags,
329 	struct thread *td)
330 {
331 
332 	return (EIO);
333 }
334 
335 static int
336 cryptof_truncate(
337 	struct file *fp,
338 	off_t length,
339 	struct ucred *active_cred,
340 	struct thread *td)
341 {
342 
343 	return (EINVAL);
344 }
345 
346 /*
347  * Check a crypto identifier to see if it requested
348  * a software device/driver.  This can be done either
349  * by device name/class or through search constraints.
350  */
351 static int
352 checkforsoftware(int crid)
353 {
354 	if (crid & CRYPTOCAP_F_SOFTWARE)
355 		return EINVAL;		/* XXX */
356 	if ((crid & CRYPTOCAP_F_HARDWARE) == 0 &&
357 	    (crypto_getcaps(crid) & CRYPTOCAP_F_HARDWARE) == 0)
358 		return EINVAL;		/* XXX */
359 	return 0;
360 }
361 
362 /* ARGSUSED */
363 static int
364 cryptof_ioctl(
365 	struct file *fp,
366 	u_long cmd,
367 	void *data,
368 	struct ucred *active_cred,
369 	struct thread *td)
370 {
371 #define	SES2(p)	((struct session2_op *)p)
372 	struct cryptoini cria, crie;
373 	struct fcrypt *fcr = fp->f_data;
374 	struct csession *cse;
375 	struct session_op *sop;
376 	struct crypt_op *cop;
377 	struct enc_xform *txform = NULL;
378 	struct auth_hash *thash = NULL;
379 	struct crypt_kop *kop;
380 	u_int64_t sid;
381 	u_int32_t ses;
382 	int error = 0, crid;
383 #ifdef COMPAT_FREEBSD32
384 	struct session2_op sopc;
385 	struct crypt_op copc;
386 	struct crypt_kop kopc;
387 #endif
388 
389 	switch (cmd) {
390 	case CIOCGSESSION:
391 	case CIOCGSESSION2:
392 #ifdef COMPAT_FREEBSD32
393 	case CIOCGSESSION32:
394 	case CIOCGSESSION232:
395 		if (cmd == CIOCGSESSION32) {
396 			session_op_from_32(data, (struct session_op *)&sopc);
397 			sop = (struct session_op *)&sopc;
398 		} else if (cmd == CIOCGSESSION232) {
399 			session2_op_from_32(data, &sopc);
400 			sop = (struct session_op *)&sopc;
401 		} else
402 #endif
403 			sop = (struct session_op *)data;
404 		switch (sop->cipher) {
405 		case 0:
406 			break;
407 		case CRYPTO_DES_CBC:
408 			txform = &enc_xform_des;
409 			break;
410 		case CRYPTO_3DES_CBC:
411 			txform = &enc_xform_3des;
412 			break;
413 		case CRYPTO_BLF_CBC:
414 			txform = &enc_xform_blf;
415 			break;
416 		case CRYPTO_CAST_CBC:
417 			txform = &enc_xform_cast5;
418 			break;
419 		case CRYPTO_SKIPJACK_CBC:
420 			txform = &enc_xform_skipjack;
421 			break;
422 		case CRYPTO_AES_CBC:
423 			txform = &enc_xform_rijndael128;
424 			break;
425 		case CRYPTO_AES_XTS:
426 			txform = &enc_xform_aes_xts;
427 			break;
428 		case CRYPTO_NULL_CBC:
429 			txform = &enc_xform_null;
430 			break;
431 		case CRYPTO_ARC4:
432 			txform = &enc_xform_arc4;
433 			break;
434  		case CRYPTO_CAMELLIA_CBC:
435  			txform = &enc_xform_camellia;
436  			break;
437 		default:
438 			return (EINVAL);
439 		}
440 
441 		switch (sop->mac) {
442 		case 0:
443 			break;
444 		case CRYPTO_MD5_HMAC:
445 			thash = &auth_hash_hmac_md5;
446 			break;
447 		case CRYPTO_SHA1_HMAC:
448 			thash = &auth_hash_hmac_sha1;
449 			break;
450 		case CRYPTO_SHA2_256_HMAC:
451 			thash = &auth_hash_hmac_sha2_256;
452 			break;
453 		case CRYPTO_SHA2_384_HMAC:
454 			thash = &auth_hash_hmac_sha2_384;
455 			break;
456 		case CRYPTO_SHA2_512_HMAC:
457 			thash = &auth_hash_hmac_sha2_512;
458 			break;
459 		case CRYPTO_RIPEMD160_HMAC:
460 			thash = &auth_hash_hmac_ripemd_160;
461 			break;
462 #ifdef notdef
463 		case CRYPTO_MD5:
464 			thash = &auth_hash_md5;
465 			break;
466 		case CRYPTO_SHA1:
467 			thash = &auth_hash_sha1;
468 			break;
469 #endif
470 		case CRYPTO_NULL_HMAC:
471 			thash = &auth_hash_null;
472 			break;
473 		default:
474 			return (EINVAL);
475 		}
476 
477 		bzero(&crie, sizeof(crie));
478 		bzero(&cria, sizeof(cria));
479 
480 		if (txform) {
481 			crie.cri_alg = txform->type;
482 			crie.cri_klen = sop->keylen * 8;
483 			if (sop->keylen > txform->maxkey ||
484 			    sop->keylen < txform->minkey) {
485 				error = EINVAL;
486 				goto bail;
487 			}
488 
489 			crie.cri_key = malloc(crie.cri_klen / 8,
490 			    M_XDATA, M_WAITOK);
491 			if ((error = copyin(sop->key, crie.cri_key,
492 			    crie.cri_klen / 8)))
493 				goto bail;
494 			if (thash)
495 				crie.cri_next = &cria;
496 		}
497 
498 		if (thash) {
499 			cria.cri_alg = thash->type;
500 			cria.cri_klen = sop->mackeylen * 8;
501 			if (sop->mackeylen != thash->keysize) {
502 				error = EINVAL;
503 				goto bail;
504 			}
505 
506 			if (cria.cri_klen) {
507 				cria.cri_key = malloc(cria.cri_klen / 8,
508 				    M_XDATA, M_WAITOK);
509 				if ((error = copyin(sop->mackey, cria.cri_key,
510 				    cria.cri_klen / 8)))
511 					goto bail;
512 			}
513 		}
514 
515 		/* NB: CIOCGSESSION2 has the crid */
516 		if (cmd == CIOCGSESSION2
517 #ifdef COMPAT_FREEBSD32
518 		    || cmd == CIOCGSESSION232
519 #endif
520 			) {
521 			crid = SES2(sop)->crid;
522 			error = checkforsoftware(crid);
523 			if (error)
524 				goto bail;
525 		} else
526 			crid = CRYPTOCAP_F_HARDWARE;
527 		error = crypto_newsession(&sid, (txform ? &crie : &cria), crid);
528 		if (error)
529 			goto bail;
530 
531 		cse = csecreate(fcr, sid, crie.cri_key, crie.cri_klen,
532 		    cria.cri_key, cria.cri_klen, sop->cipher, sop->mac, txform,
533 		    thash);
534 
535 		if (cse == NULL) {
536 			crypto_freesession(sid);
537 			error = EINVAL;
538 			goto bail;
539 		}
540 		sop->ses = cse->ses;
541 		if (cmd == CIOCGSESSION2
542 #ifdef COMPAT_FREEBSD32
543 		    || cmd == CIOCGSESSION232
544 #endif
545 		    ) {
546 			/* return hardware/driver id */
547 			SES2(sop)->crid = CRYPTO_SESID2HID(cse->sid);
548 		}
549 bail:
550 		if (error) {
551 			if (crie.cri_key)
552 				free(crie.cri_key, M_XDATA);
553 			if (cria.cri_key)
554 				free(cria.cri_key, M_XDATA);
555 		}
556 #ifdef COMPAT_FREEBSD32
557 		else {
558 			if (cmd == CIOCGSESSION32)
559 				session_op_to_32(sop, data);
560 			else if (cmd == CIOCGSESSION232)
561 				session2_op_to_32((struct session2_op *)sop,
562 				    data);
563 		}
564 #endif
565 		break;
566 	case CIOCFSESSION:
567 		ses = *(u_int32_t *)data;
568 		cse = csefind(fcr, ses);
569 		if (cse == NULL)
570 			return (EINVAL);
571 		csedelete(fcr, cse);
572 		error = csefree(cse);
573 		break;
574 	case CIOCCRYPT:
575 #ifdef COMPAT_FREEBSD32
576 	case CIOCCRYPT32:
577 		if (cmd == CIOCCRYPT32) {
578 			cop = &copc;
579 			crypt_op_from_32(data, cop);
580 		} else
581 #endif
582 			cop = (struct crypt_op *)data;
583 		cse = csefind(fcr, cop->ses);
584 		if (cse == NULL)
585 			return (EINVAL);
586 		error = cryptodev_op(cse, cop, active_cred, td);
587 #ifdef COMPAT_FREEBSD32
588 		if (error == 0 && cmd == CIOCCRYPT32)
589 			crypt_op_to_32(cop, data);
590 #endif
591 		break;
592 	case CIOCKEY:
593 	case CIOCKEY2:
594 #ifdef COMPAT_FREEBSD32
595 	case CIOCKEY32:
596 	case CIOCKEY232:
597 #endif
598 		if (!crypto_userasymcrypto)
599 			return (EPERM);		/* XXX compat? */
600 #ifdef COMPAT_FREEBSD32
601 		if (cmd == CIOCKEY32 || cmd == CIOCKEY232) {
602 			kop = &kopc;
603 			crypt_kop_from_32(data, kop);
604 		} else
605 #endif
606 			kop = (struct crypt_kop *)data;
607 		if (cmd == CIOCKEY
608 #ifdef COMPAT_FREEBSD32
609 		    || cmd == CIOCKEY32
610 #endif
611 		    ) {
612 			/* NB: crypto core enforces s/w driver use */
613 			kop->crk_crid =
614 			    CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE;
615 		}
616 		mtx_lock(&Giant);
617 		error = cryptodev_key(kop);
618 		mtx_unlock(&Giant);
619 #ifdef COMPAT_FREEBSD32
620 		if (cmd == CIOCKEY32 || cmd == CIOCKEY232)
621 			crypt_kop_to_32(kop, data);
622 #endif
623 		break;
624 	case CIOCASYMFEAT:
625 		if (!crypto_userasymcrypto) {
626 			/*
627 			 * NB: if user asym crypto operations are
628 			 * not permitted return "no algorithms"
629 			 * so well-behaved applications will just
630 			 * fallback to doing them in software.
631 			 */
632 			*(int *)data = 0;
633 		} else
634 			error = crypto_getfeat((int *)data);
635 		break;
636 	case CIOCFINDDEV:
637 		error = cryptodev_find((struct crypt_find_op *)data);
638 		break;
639 	default:
640 		error = EINVAL;
641 		break;
642 	}
643 	return (error);
644 #undef SES2
645 }
646 
647 static int cryptodev_cb(void *);
648 
649 
650 static int
651 cryptodev_op(
652 	struct csession *cse,
653 	struct crypt_op *cop,
654 	struct ucred *active_cred,
655 	struct thread *td)
656 {
657 	struct cryptop *crp = NULL;
658 	struct cryptodesc *crde = NULL, *crda = NULL;
659 	int error;
660 
661 	if (cop->len > 256*1024-4)
662 		return (E2BIG);
663 
664 	if (cse->txform) {
665 		if (cop->len == 0 || (cop->len % cse->txform->blocksize) != 0)
666 			return (EINVAL);
667 	}
668 
669 	cse->uio.uio_iov = &cse->iovec;
670 	cse->uio.uio_iovcnt = 1;
671 	cse->uio.uio_offset = 0;
672 	cse->uio.uio_resid = cop->len;
673 	cse->uio.uio_segflg = UIO_SYSSPACE;
674 	cse->uio.uio_rw = UIO_WRITE;
675 	cse->uio.uio_td = td;
676 	cse->uio.uio_iov[0].iov_len = cop->len;
677 	if (cse->thash) {
678 		cse->uio.uio_iov[0].iov_len += cse->thash->hashsize;
679 		cse->uio.uio_resid += cse->thash->hashsize;
680 	}
681 	cse->uio.uio_iov[0].iov_base = malloc(cse->uio.uio_iov[0].iov_len,
682 	    M_XDATA, M_WAITOK);
683 
684 	crp = crypto_getreq((cse->txform != NULL) + (cse->thash != NULL));
685 	if (crp == NULL) {
686 		error = ENOMEM;
687 		goto bail;
688 	}
689 
690 	if (cse->thash) {
691 		crda = crp->crp_desc;
692 		if (cse->txform)
693 			crde = crda->crd_next;
694 	} else {
695 		if (cse->txform)
696 			crde = crp->crp_desc;
697 		else {
698 			error = EINVAL;
699 			goto bail;
700 		}
701 	}
702 
703 	if ((error = copyin(cop->src, cse->uio.uio_iov[0].iov_base, cop->len)))
704 		goto bail;
705 
706 	if (crda) {
707 		crda->crd_skip = 0;
708 		crda->crd_len = cop->len;
709 		crda->crd_inject = cop->len;
710 
711 		crda->crd_alg = cse->mac;
712 		crda->crd_key = cse->mackey;
713 		crda->crd_klen = cse->mackeylen * 8;
714 	}
715 
716 	if (crde) {
717 		if (cop->op == COP_ENCRYPT)
718 			crde->crd_flags |= CRD_F_ENCRYPT;
719 		else
720 			crde->crd_flags &= ~CRD_F_ENCRYPT;
721 		crde->crd_len = cop->len;
722 		crde->crd_inject = 0;
723 
724 		crde->crd_alg = cse->cipher;
725 		crde->crd_key = cse->key;
726 		crde->crd_klen = cse->keylen * 8;
727 	}
728 
729 	crp->crp_ilen = cop->len;
730 	crp->crp_flags = CRYPTO_F_IOV | CRYPTO_F_CBIMM
731 		       | (cop->flags & COP_F_BATCH);
732 	crp->crp_buf = (caddr_t)&cse->uio;
733 	crp->crp_callback = (int (*) (struct cryptop *)) cryptodev_cb;
734 	crp->crp_sid = cse->sid;
735 	crp->crp_opaque = (void *)cse;
736 
737 	if (cop->iv) {
738 		if (crde == NULL) {
739 			error = EINVAL;
740 			goto bail;
741 		}
742 		if (cse->cipher == CRYPTO_ARC4) { /* XXX use flag? */
743 			error = EINVAL;
744 			goto bail;
745 		}
746 		if ((error = copyin(cop->iv, cse->tmp_iv, cse->txform->blocksize)))
747 			goto bail;
748 		bcopy(cse->tmp_iv, crde->crd_iv, cse->txform->blocksize);
749 		crde->crd_flags |= CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
750 		crde->crd_skip = 0;
751 	} else if (cse->cipher == CRYPTO_ARC4) { /* XXX use flag? */
752 		crde->crd_skip = 0;
753 	} else if (crde) {
754 		crde->crd_flags |= CRD_F_IV_PRESENT;
755 		crde->crd_skip = cse->txform->blocksize;
756 		crde->crd_len -= cse->txform->blocksize;
757 	}
758 
759 	if (cop->mac && crda == NULL) {
760 		error = EINVAL;
761 		goto bail;
762 	}
763 
764 again:
765 	/*
766 	 * Let the dispatch run unlocked, then, interlock against the
767 	 * callback before checking if the operation completed and going
768 	 * to sleep.  This insures drivers don't inherit our lock which
769 	 * results in a lock order reversal between crypto_dispatch forced
770 	 * entry and the crypto_done callback into us.
771 	 */
772 	error = crypto_dispatch(crp);
773 	mtx_lock(&cse->lock);
774 	if (error == 0 && (crp->crp_flags & CRYPTO_F_DONE) == 0)
775 		error = msleep(crp, &cse->lock, PWAIT, "crydev", 0);
776 	mtx_unlock(&cse->lock);
777 
778 	if (error != 0)
779 		goto bail;
780 
781 	if (crp->crp_etype == EAGAIN) {
782 		crp->crp_etype = 0;
783 		crp->crp_flags &= ~CRYPTO_F_DONE;
784 		goto again;
785 	}
786 
787 	if (crp->crp_etype != 0) {
788 		error = crp->crp_etype;
789 		goto bail;
790 	}
791 
792 	if (cse->error) {
793 		error = cse->error;
794 		goto bail;
795 	}
796 
797 	if (cop->dst &&
798 	    (error = copyout(cse->uio.uio_iov[0].iov_base, cop->dst, cop->len)))
799 		goto bail;
800 
801 	if (cop->mac &&
802 	    (error = copyout((caddr_t)cse->uio.uio_iov[0].iov_base + cop->len,
803 	    cop->mac, cse->thash->hashsize)))
804 		goto bail;
805 
806 bail:
807 	if (crp)
808 		crypto_freereq(crp);
809 	if (cse->uio.uio_iov[0].iov_base)
810 		free(cse->uio.uio_iov[0].iov_base, M_XDATA);
811 
812 	return (error);
813 }
814 
815 static int
816 cryptodev_cb(void *op)
817 {
818 	struct cryptop *crp = (struct cryptop *) op;
819 	struct csession *cse = (struct csession *)crp->crp_opaque;
820 
821 	mtx_lock(&cse->lock);
822 	cse->error = crp->crp_etype;
823 	wakeup_one(crp);
824 	mtx_unlock(&cse->lock);
825 	return (0);
826 }
827 
828 static int
829 cryptodevkey_cb(void *op)
830 {
831 	struct cryptkop *krp = (struct cryptkop *) op;
832 
833 	wakeup_one(krp);
834 	return (0);
835 }
836 
837 static int
838 cryptodev_key(struct crypt_kop *kop)
839 {
840 	struct cryptkop *krp = NULL;
841 	int error = EINVAL;
842 	int in, out, size, i;
843 
844 	if (kop->crk_iparams + kop->crk_oparams > CRK_MAXPARAM) {
845 		return (EFBIG);
846 	}
847 
848 	in = kop->crk_iparams;
849 	out = kop->crk_oparams;
850 	switch (kop->crk_op) {
851 	case CRK_MOD_EXP:
852 		if (in == 3 && out == 1)
853 			break;
854 		return (EINVAL);
855 	case CRK_MOD_EXP_CRT:
856 		if (in == 6 && out == 1)
857 			break;
858 		return (EINVAL);
859 	case CRK_DSA_SIGN:
860 		if (in == 5 && out == 2)
861 			break;
862 		return (EINVAL);
863 	case CRK_DSA_VERIFY:
864 		if (in == 7 && out == 0)
865 			break;
866 		return (EINVAL);
867 	case CRK_DH_COMPUTE_KEY:
868 		if (in == 3 && out == 1)
869 			break;
870 		return (EINVAL);
871 	default:
872 		return (EINVAL);
873 	}
874 
875 	krp = (struct cryptkop *)malloc(sizeof *krp, M_XDATA, M_WAITOK|M_ZERO);
876 	if (!krp)
877 		return (ENOMEM);
878 	krp->krp_op = kop->crk_op;
879 	krp->krp_status = kop->crk_status;
880 	krp->krp_iparams = kop->crk_iparams;
881 	krp->krp_oparams = kop->crk_oparams;
882 	krp->krp_crid = kop->crk_crid;
883 	krp->krp_status = 0;
884 	krp->krp_callback = (int (*) (struct cryptkop *)) cryptodevkey_cb;
885 
886 	for (i = 0; i < CRK_MAXPARAM; i++) {
887 		if (kop->crk_param[i].crp_nbits > 65536)
888 			/* Limit is the same as in OpenBSD */
889 			goto fail;
890 		krp->krp_param[i].crp_nbits = kop->crk_param[i].crp_nbits;
891 	}
892 	for (i = 0; i < krp->krp_iparams + krp->krp_oparams; i++) {
893 		size = (krp->krp_param[i].crp_nbits + 7) / 8;
894 		if (size == 0)
895 			continue;
896 		krp->krp_param[i].crp_p = malloc(size, M_XDATA, M_WAITOK);
897 		if (i >= krp->krp_iparams)
898 			continue;
899 		error = copyin(kop->crk_param[i].crp_p, krp->krp_param[i].crp_p, size);
900 		if (error)
901 			goto fail;
902 	}
903 
904 	error = crypto_kdispatch(krp);
905 	if (error)
906 		goto fail;
907 	error = tsleep(krp, PSOCK, "crydev", 0);
908 	if (error) {
909 		/* XXX can this happen?  if so, how do we recover? */
910 		goto fail;
911 	}
912 
913 	kop->crk_crid = krp->krp_crid;		/* device that did the work */
914 	if (krp->krp_status != 0) {
915 		error = krp->krp_status;
916 		goto fail;
917 	}
918 
919 	for (i = krp->krp_iparams; i < krp->krp_iparams + krp->krp_oparams; i++) {
920 		size = (krp->krp_param[i].crp_nbits + 7) / 8;
921 		if (size == 0)
922 			continue;
923 		error = copyout(krp->krp_param[i].crp_p, kop->crk_param[i].crp_p, size);
924 		if (error)
925 			goto fail;
926 	}
927 
928 fail:
929 	if (krp) {
930 		kop->crk_status = krp->krp_status;
931 		for (i = 0; i < CRK_MAXPARAM; i++) {
932 			if (krp->krp_param[i].crp_p)
933 				free(krp->krp_param[i].crp_p, M_XDATA);
934 		}
935 		free(krp, M_XDATA);
936 	}
937 	return (error);
938 }
939 
940 static int
941 cryptodev_find(struct crypt_find_op *find)
942 {
943 	device_t dev;
944 
945 	if (find->crid != -1) {
946 		dev = crypto_find_device_byhid(find->crid);
947 		if (dev == NULL)
948 			return (ENOENT);
949 		strlcpy(find->name, device_get_nameunit(dev),
950 		    sizeof(find->name));
951 	} else {
952 		find->crid = crypto_find_driver(find->name);
953 		if (find->crid == -1)
954 			return (ENOENT);
955 	}
956 	return (0);
957 }
958 
959 /* ARGSUSED */
960 static int
961 cryptof_poll(
962 	struct file *fp,
963 	int events,
964 	struct ucred *active_cred,
965 	struct thread *td)
966 {
967 
968 	return (0);
969 }
970 
971 /* ARGSUSED */
972 static int
973 cryptof_kqfilter(struct file *fp, struct knote *kn)
974 {
975 
976 	return (0);
977 }
978 
979 /* ARGSUSED */
980 static int
981 cryptof_stat(
982 	struct file *fp,
983 	struct stat *sb,
984 	struct ucred *active_cred,
985 	struct thread *td)
986 {
987 
988 	return (EOPNOTSUPP);
989 }
990 
991 /* ARGSUSED */
992 static int
993 cryptof_close(struct file *fp, struct thread *td)
994 {
995 	struct fcrypt *fcr = fp->f_data;
996 	struct csession *cse;
997 
998 	while ((cse = TAILQ_FIRST(&fcr->csessions))) {
999 		TAILQ_REMOVE(&fcr->csessions, cse, next);
1000 		(void)csefree(cse);
1001 	}
1002 	free(fcr, M_XDATA);
1003 	fp->f_data = NULL;
1004 	return 0;
1005 }
1006 
1007 static struct csession *
1008 csefind(struct fcrypt *fcr, u_int ses)
1009 {
1010 	struct csession *cse;
1011 
1012 	TAILQ_FOREACH(cse, &fcr->csessions, next)
1013 		if (cse->ses == ses)
1014 			return (cse);
1015 	return (NULL);
1016 }
1017 
1018 static int
1019 csedelete(struct fcrypt *fcr, struct csession *cse_del)
1020 {
1021 	struct csession *cse;
1022 
1023 	TAILQ_FOREACH(cse, &fcr->csessions, next) {
1024 		if (cse == cse_del) {
1025 			TAILQ_REMOVE(&fcr->csessions, cse, next);
1026 			return (1);
1027 		}
1028 	}
1029 	return (0);
1030 }
1031 
1032 static struct csession *
1033 cseadd(struct fcrypt *fcr, struct csession *cse)
1034 {
1035 	TAILQ_INSERT_TAIL(&fcr->csessions, cse, next);
1036 	cse->ses = fcr->sesn++;
1037 	return (cse);
1038 }
1039 
1040 struct csession *
1041 csecreate(struct fcrypt *fcr, u_int64_t sid, caddr_t key, u_int64_t keylen,
1042     caddr_t mackey, u_int64_t mackeylen, u_int32_t cipher, u_int32_t mac,
1043     struct enc_xform *txform, struct auth_hash *thash)
1044 {
1045 	struct csession *cse;
1046 
1047 #ifdef INVARIANTS
1048 	/* NB: required when mtx_init is built with INVARIANTS */
1049 	cse = malloc(sizeof(struct csession), M_XDATA, M_NOWAIT | M_ZERO);
1050 #else
1051 	cse = malloc(sizeof(struct csession), M_XDATA, M_NOWAIT);
1052 #endif
1053 	if (cse == NULL)
1054 		return NULL;
1055 	mtx_init(&cse->lock, "cryptodev", "crypto session lock", MTX_DEF);
1056 	cse->key = key;
1057 	cse->keylen = keylen/8;
1058 	cse->mackey = mackey;
1059 	cse->mackeylen = mackeylen/8;
1060 	cse->sid = sid;
1061 	cse->cipher = cipher;
1062 	cse->mac = mac;
1063 	cse->txform = txform;
1064 	cse->thash = thash;
1065 	cseadd(fcr, cse);
1066 	return (cse);
1067 }
1068 
1069 static int
1070 csefree(struct csession *cse)
1071 {
1072 	int error;
1073 
1074 	error = crypto_freesession(cse->sid);
1075 	mtx_destroy(&cse->lock);
1076 	if (cse->key)
1077 		free(cse->key, M_XDATA);
1078 	if (cse->mackey)
1079 		free(cse->mackey, M_XDATA);
1080 	free(cse, M_XDATA);
1081 	return (error);
1082 }
1083 
1084 static int
1085 cryptoopen(struct cdev *dev, int oflags, int devtype, struct thread *td)
1086 {
1087 	return (0);
1088 }
1089 
1090 static int
1091 cryptoread(struct cdev *dev, struct uio *uio, int ioflag)
1092 {
1093 	return (EIO);
1094 }
1095 
1096 static int
1097 cryptowrite(struct cdev *dev, struct uio *uio, int ioflag)
1098 {
1099 	return (EIO);
1100 }
1101 
1102 static int
1103 cryptoioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
1104 {
1105 	struct file *f;
1106 	struct fcrypt *fcr;
1107 	int fd, error;
1108 
1109 	switch (cmd) {
1110 	case CRIOGET:
1111 		fcr = malloc(sizeof(struct fcrypt), M_XDATA, M_WAITOK);
1112 		TAILQ_INIT(&fcr->csessions);
1113 		fcr->sesn = 0;
1114 
1115 		error = falloc(td, &f, &fd, 0);
1116 
1117 		if (error) {
1118 			free(fcr, M_XDATA);
1119 			return (error);
1120 		}
1121 		/* falloc automatically provides an extra reference to 'f'. */
1122 		finit(f, FREAD | FWRITE, DTYPE_CRYPTO, fcr, &cryptofops);
1123 		*(u_int32_t *)data = fd;
1124 		fdrop(f, td);
1125 		break;
1126 	case CRIOFINDDEV:
1127 		error = cryptodev_find((struct crypt_find_op *)data);
1128 		break;
1129 	case CRIOASYMFEAT:
1130 		error = crypto_getfeat((int *)data);
1131 		break;
1132 	default:
1133 		error = EINVAL;
1134 		break;
1135 	}
1136 	return (error);
1137 }
1138 
1139 static struct cdevsw crypto_cdevsw = {
1140 	.d_version =	D_VERSION,
1141 	.d_flags =	D_NEEDGIANT,
1142 	.d_open =	cryptoopen,
1143 	.d_read =	cryptoread,
1144 	.d_write =	cryptowrite,
1145 	.d_ioctl =	cryptoioctl,
1146 	.d_name =	"crypto",
1147 };
1148 static struct cdev *crypto_dev;
1149 
1150 /*
1151  * Initialization code, both for static and dynamic loading.
1152  */
1153 static int
1154 cryptodev_modevent(module_t mod, int type, void *unused)
1155 {
1156 	switch (type) {
1157 	case MOD_LOAD:
1158 		if (bootverbose)
1159 			printf("crypto: <crypto device>\n");
1160 		crypto_dev = make_dev(&crypto_cdevsw, 0,
1161 				      UID_ROOT, GID_WHEEL, 0666,
1162 				      "crypto");
1163 		return 0;
1164 	case MOD_UNLOAD:
1165 		/*XXX disallow if active sessions */
1166 		destroy_dev(crypto_dev);
1167 		return 0;
1168 	}
1169 	return EINVAL;
1170 }
1171 
1172 static moduledata_t cryptodev_mod = {
1173 	"cryptodev",
1174 	cryptodev_modevent,
1175 	0
1176 };
1177 MODULE_VERSION(cryptodev, 1);
1178 DECLARE_MODULE(cryptodev, cryptodev_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
1179 MODULE_DEPEND(cryptodev, crypto, 1, 1, 1);
1180 MODULE_DEPEND(cryptodev, zlib, 1, 1, 1);
1181