xref: /freebsd/sys/opencrypto/cryptodev.c (revision 0f2bd1e89db1a2f09268edea21e0ead329e092df)
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 };
306 
307 static struct csession *csefind(struct fcrypt *, u_int);
308 static int csedelete(struct fcrypt *, struct csession *);
309 static struct csession *cseadd(struct fcrypt *, struct csession *);
310 static struct csession *csecreate(struct fcrypt *, u_int64_t, caddr_t,
311     u_int64_t, caddr_t, u_int64_t, u_int32_t, u_int32_t, struct enc_xform *,
312     struct auth_hash *);
313 static int csefree(struct csession *);
314 
315 static	int cryptodev_op(struct csession *, struct crypt_op *,
316 			struct ucred *, struct thread *td);
317 static	int cryptodev_key(struct crypt_kop *);
318 static	int cryptodev_find(struct crypt_find_op *);
319 
320 static int
321 cryptof_rw(
322 	struct file *fp,
323 	struct uio *uio,
324 	struct ucred *active_cred,
325 	int flags,
326 	struct thread *td)
327 {
328 
329 	return (EIO);
330 }
331 
332 static int
333 cryptof_truncate(
334 	struct file *fp,
335 	off_t length,
336 	struct ucred *active_cred,
337 	struct thread *td)
338 {
339 
340 	return (EINVAL);
341 }
342 
343 /*
344  * Check a crypto identifier to see if it requested
345  * a software device/driver.  This can be done either
346  * by device name/class or through search constraints.
347  */
348 static int
349 checkforsoftware(int crid)
350 {
351 	if (crid & CRYPTOCAP_F_SOFTWARE)
352 		return EINVAL;		/* XXX */
353 	if ((crid & CRYPTOCAP_F_HARDWARE) == 0 &&
354 	    (crypto_getcaps(crid) & CRYPTOCAP_F_HARDWARE) == 0)
355 		return EINVAL;		/* XXX */
356 	return 0;
357 }
358 
359 /* ARGSUSED */
360 static int
361 cryptof_ioctl(
362 	struct file *fp,
363 	u_long cmd,
364 	void *data,
365 	struct ucred *active_cred,
366 	struct thread *td)
367 {
368 #define	SES2(p)	((struct session2_op *)p)
369 	struct cryptoini cria, crie;
370 	struct fcrypt *fcr = fp->f_data;
371 	struct csession *cse;
372 	struct session_op *sop;
373 	struct crypt_op *cop;
374 	struct enc_xform *txform = NULL;
375 	struct auth_hash *thash = NULL;
376 	struct crypt_kop *kop;
377 	u_int64_t sid;
378 	u_int32_t ses;
379 	int error = 0, crid;
380 #ifdef COMPAT_FREEBSD32
381 	struct session2_op sopc;
382 	struct crypt_op copc;
383 	struct crypt_kop kopc;
384 #endif
385 
386 	switch (cmd) {
387 	case CIOCGSESSION:
388 	case CIOCGSESSION2:
389 #ifdef COMPAT_FREEBSD32
390 	case CIOCGSESSION32:
391 	case CIOCGSESSION232:
392 		if (cmd == CIOCGSESSION32) {
393 			session_op_from_32(data, (struct session_op *)&sopc);
394 			sop = (struct session_op *)&sopc;
395 		} else if (cmd == CIOCGSESSION232) {
396 			session2_op_from_32(data, &sopc);
397 			sop = (struct session_op *)&sopc;
398 		} else
399 #endif
400 			sop = (struct session_op *)data;
401 		switch (sop->cipher) {
402 		case 0:
403 			break;
404 		case CRYPTO_DES_CBC:
405 			txform = &enc_xform_des;
406 			break;
407 		case CRYPTO_3DES_CBC:
408 			txform = &enc_xform_3des;
409 			break;
410 		case CRYPTO_BLF_CBC:
411 			txform = &enc_xform_blf;
412 			break;
413 		case CRYPTO_CAST_CBC:
414 			txform = &enc_xform_cast5;
415 			break;
416 		case CRYPTO_SKIPJACK_CBC:
417 			txform = &enc_xform_skipjack;
418 			break;
419 		case CRYPTO_AES_CBC:
420 			txform = &enc_xform_rijndael128;
421 			break;
422 		case CRYPTO_NULL_CBC:
423 			txform = &enc_xform_null;
424 			break;
425 		case CRYPTO_ARC4:
426 			txform = &enc_xform_arc4;
427 			break;
428  		case CRYPTO_CAMELLIA_CBC:
429  			txform = &enc_xform_camellia;
430  			break;
431 		default:
432 			return (EINVAL);
433 		}
434 
435 		switch (sop->mac) {
436 		case 0:
437 			break;
438 		case CRYPTO_MD5_HMAC:
439 			thash = &auth_hash_hmac_md5;
440 			break;
441 		case CRYPTO_SHA1_HMAC:
442 			thash = &auth_hash_hmac_sha1;
443 			break;
444 		case CRYPTO_SHA2_256_HMAC:
445 			thash = &auth_hash_hmac_sha2_256;
446 			break;
447 		case CRYPTO_SHA2_384_HMAC:
448 			thash = &auth_hash_hmac_sha2_384;
449 			break;
450 		case CRYPTO_SHA2_512_HMAC:
451 			thash = &auth_hash_hmac_sha2_512;
452 			break;
453 		case CRYPTO_RIPEMD160_HMAC:
454 			thash = &auth_hash_hmac_ripemd_160;
455 			break;
456 #ifdef notdef
457 		case CRYPTO_MD5:
458 			thash = &auth_hash_md5;
459 			break;
460 		case CRYPTO_SHA1:
461 			thash = &auth_hash_sha1;
462 			break;
463 #endif
464 		case CRYPTO_NULL_HMAC:
465 			thash = &auth_hash_null;
466 			break;
467 		default:
468 			return (EINVAL);
469 		}
470 
471 		bzero(&crie, sizeof(crie));
472 		bzero(&cria, sizeof(cria));
473 
474 		if (txform) {
475 			crie.cri_alg = txform->type;
476 			crie.cri_klen = sop->keylen * 8;
477 			if (sop->keylen > txform->maxkey ||
478 			    sop->keylen < txform->minkey) {
479 				error = EINVAL;
480 				goto bail;
481 			}
482 
483 			crie.cri_key = malloc(crie.cri_klen / 8,
484 			    M_XDATA, M_WAITOK);
485 			if ((error = copyin(sop->key, crie.cri_key,
486 			    crie.cri_klen / 8)))
487 				goto bail;
488 			if (thash)
489 				crie.cri_next = &cria;
490 		}
491 
492 		if (thash) {
493 			cria.cri_alg = thash->type;
494 			cria.cri_klen = sop->mackeylen * 8;
495 			if (sop->mackeylen != thash->keysize) {
496 				error = EINVAL;
497 				goto bail;
498 			}
499 
500 			if (cria.cri_klen) {
501 				cria.cri_key = malloc(cria.cri_klen / 8,
502 				    M_XDATA, M_WAITOK);
503 				if ((error = copyin(sop->mackey, cria.cri_key,
504 				    cria.cri_klen / 8)))
505 					goto bail;
506 			}
507 		}
508 
509 		/* NB: CIOCGSESSION2 has the crid */
510 		if (cmd == CIOCGSESSION2
511 #ifdef COMPAT_FREEBSD32
512 		    || cmd == CIOCGSESSION232
513 #endif
514 			) {
515 			crid = SES2(sop)->crid;
516 			error = checkforsoftware(crid);
517 			if (error)
518 				goto bail;
519 		} else
520 			crid = CRYPTOCAP_F_HARDWARE;
521 		error = crypto_newsession(&sid, (txform ? &crie : &cria), crid);
522 		if (error)
523 			goto bail;
524 
525 		cse = csecreate(fcr, sid, crie.cri_key, crie.cri_klen,
526 		    cria.cri_key, cria.cri_klen, sop->cipher, sop->mac, txform,
527 		    thash);
528 
529 		if (cse == NULL) {
530 			crypto_freesession(sid);
531 			error = EINVAL;
532 			goto bail;
533 		}
534 		sop->ses = cse->ses;
535 		if (cmd == CIOCGSESSION2
536 #ifdef COMPAT_FREEBSD32
537 		    || cmd == CIOCGSESSION232
538 #endif
539 		    ) {
540 			/* return hardware/driver id */
541 			SES2(sop)->crid = CRYPTO_SESID2HID(cse->sid);
542 		}
543 bail:
544 		if (error) {
545 			if (crie.cri_key)
546 				free(crie.cri_key, M_XDATA);
547 			if (cria.cri_key)
548 				free(cria.cri_key, M_XDATA);
549 		}
550 #ifdef COMPAT_FREEBSD32
551 		else {
552 			if (cmd == CIOCGSESSION32)
553 				session_op_to_32(sop, data);
554 			else if (cmd == CIOCGSESSION232)
555 				session2_op_to_32((struct session2_op *)sop,
556 				    data);
557 		}
558 #endif
559 		break;
560 	case CIOCFSESSION:
561 		ses = *(u_int32_t *)data;
562 		cse = csefind(fcr, ses);
563 		if (cse == NULL)
564 			return (EINVAL);
565 		csedelete(fcr, cse);
566 		error = csefree(cse);
567 		break;
568 	case CIOCCRYPT:
569 #ifdef COMPAT_FREEBSD32
570 	case CIOCCRYPT32:
571 		if (cmd == CIOCCRYPT32) {
572 			cop = &copc;
573 			crypt_op_from_32(data, cop);
574 		} else
575 #endif
576 			cop = (struct crypt_op *)data;
577 		cse = csefind(fcr, cop->ses);
578 		if (cse == NULL)
579 			return (EINVAL);
580 		error = cryptodev_op(cse, cop, active_cred, td);
581 #ifdef COMPAT_FREEBSD32
582 		if (error == 0 && cmd == CIOCCRYPT32)
583 			crypt_op_to_32(cop, data);
584 #endif
585 		break;
586 	case CIOCKEY:
587 	case CIOCKEY2:
588 #ifdef COMPAT_FREEBSD32
589 	case CIOCKEY32:
590 	case CIOCKEY232:
591 #endif
592 		if (!crypto_userasymcrypto)
593 			return (EPERM);		/* XXX compat? */
594 #ifdef COMPAT_FREEBSD32
595 		if (cmd == CIOCKEY32 || cmd == CIOCKEY232) {
596 			kop = &kopc;
597 			crypt_kop_from_32(data, kop);
598 		} else
599 #endif
600 			kop = (struct crypt_kop *)data;
601 		if (cmd == CIOCKEY
602 #ifdef COMPAT_FREEBSD32
603 		    || cmd == CIOCKEY32
604 #endif
605 		    ) {
606 			/* NB: crypto core enforces s/w driver use */
607 			kop->crk_crid =
608 			    CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE;
609 		}
610 		mtx_lock(&Giant);
611 		error = cryptodev_key(kop);
612 		mtx_unlock(&Giant);
613 #ifdef COMPAT_FREEBSD32
614 		if (cmd == CIOCKEY32 || cmd == CIOCKEY232)
615 			crypt_kop_to_32(kop, data);
616 #endif
617 		break;
618 	case CIOCASYMFEAT:
619 		if (!crypto_userasymcrypto) {
620 			/*
621 			 * NB: if user asym crypto operations are
622 			 * not permitted return "no algorithms"
623 			 * so well-behaved applications will just
624 			 * fallback to doing them in software.
625 			 */
626 			*(int *)data = 0;
627 		} else
628 			error = crypto_getfeat((int *)data);
629 		break;
630 	case CIOCFINDDEV:
631 		error = cryptodev_find((struct crypt_find_op *)data);
632 		break;
633 	default:
634 		error = EINVAL;
635 		break;
636 	}
637 	return (error);
638 #undef SES2
639 }
640 
641 static int cryptodev_cb(void *);
642 
643 
644 static int
645 cryptodev_op(
646 	struct csession *cse,
647 	struct crypt_op *cop,
648 	struct ucred *active_cred,
649 	struct thread *td)
650 {
651 	struct cryptop *crp = NULL;
652 	struct cryptodesc *crde = NULL, *crda = NULL;
653 	int error;
654 
655 	if (cop->len > 256*1024-4)
656 		return (E2BIG);
657 
658 	if (cse->txform) {
659 		if (cop->len == 0 || (cop->len % cse->txform->blocksize) != 0)
660 			return (EINVAL);
661 	}
662 
663 	cse->uio.uio_iov = &cse->iovec;
664 	cse->uio.uio_iovcnt = 1;
665 	cse->uio.uio_offset = 0;
666 	cse->uio.uio_resid = cop->len;
667 	cse->uio.uio_segflg = UIO_SYSSPACE;
668 	cse->uio.uio_rw = UIO_WRITE;
669 	cse->uio.uio_td = td;
670 	cse->uio.uio_iov[0].iov_len = cop->len;
671 	if (cse->thash) {
672 		cse->uio.uio_iov[0].iov_len += cse->thash->hashsize;
673 		cse->uio.uio_resid += cse->thash->hashsize;
674 	}
675 	cse->uio.uio_iov[0].iov_base = malloc(cse->uio.uio_iov[0].iov_len,
676 	    M_XDATA, M_WAITOK);
677 
678 	crp = crypto_getreq((cse->txform != NULL) + (cse->thash != NULL));
679 	if (crp == NULL) {
680 		error = ENOMEM;
681 		goto bail;
682 	}
683 
684 	if (cse->thash) {
685 		crda = crp->crp_desc;
686 		if (cse->txform)
687 			crde = crda->crd_next;
688 	} else {
689 		if (cse->txform)
690 			crde = crp->crp_desc;
691 		else {
692 			error = EINVAL;
693 			goto bail;
694 		}
695 	}
696 
697 	if ((error = copyin(cop->src, cse->uio.uio_iov[0].iov_base, cop->len)))
698 		goto bail;
699 
700 	if (crda) {
701 		crda->crd_skip = 0;
702 		crda->crd_len = cop->len;
703 		crda->crd_inject = cop->len;
704 
705 		crda->crd_alg = cse->mac;
706 		crda->crd_key = cse->mackey;
707 		crda->crd_klen = cse->mackeylen * 8;
708 	}
709 
710 	if (crde) {
711 		if (cop->op == COP_ENCRYPT)
712 			crde->crd_flags |= CRD_F_ENCRYPT;
713 		else
714 			crde->crd_flags &= ~CRD_F_ENCRYPT;
715 		crde->crd_len = cop->len;
716 		crde->crd_inject = 0;
717 
718 		crde->crd_alg = cse->cipher;
719 		crde->crd_key = cse->key;
720 		crde->crd_klen = cse->keylen * 8;
721 	}
722 
723 	crp->crp_ilen = cop->len;
724 	crp->crp_flags = CRYPTO_F_IOV | CRYPTO_F_CBIMM
725 		       | (cop->flags & COP_F_BATCH);
726 	crp->crp_buf = (caddr_t)&cse->uio;
727 	crp->crp_callback = (int (*) (struct cryptop *)) cryptodev_cb;
728 	crp->crp_sid = cse->sid;
729 	crp->crp_opaque = (void *)cse;
730 
731 	if (cop->iv) {
732 		if (crde == NULL) {
733 			error = EINVAL;
734 			goto bail;
735 		}
736 		if (cse->cipher == CRYPTO_ARC4) { /* XXX use flag? */
737 			error = EINVAL;
738 			goto bail;
739 		}
740 		if ((error = copyin(cop->iv, cse->tmp_iv, cse->txform->blocksize)))
741 			goto bail;
742 		bcopy(cse->tmp_iv, crde->crd_iv, cse->txform->blocksize);
743 		crde->crd_flags |= CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
744 		crde->crd_skip = 0;
745 	} else if (cse->cipher == CRYPTO_ARC4) { /* XXX use flag? */
746 		crde->crd_skip = 0;
747 	} else if (crde) {
748 		crde->crd_flags |= CRD_F_IV_PRESENT;
749 		crde->crd_skip = cse->txform->blocksize;
750 		crde->crd_len -= cse->txform->blocksize;
751 	}
752 
753 	if (cop->mac && crda == NULL) {
754 		error = EINVAL;
755 		goto bail;
756 	}
757 
758 again:
759 	/*
760 	 * Let the dispatch run unlocked, then, interlock against the
761 	 * callback before checking if the operation completed and going
762 	 * to sleep.  This insures drivers don't inherit our lock which
763 	 * results in a lock order reversal between crypto_dispatch forced
764 	 * entry and the crypto_done callback into us.
765 	 */
766 	error = crypto_dispatch(crp);
767 	mtx_lock(&cse->lock);
768 	if (error == 0 && (crp->crp_flags & CRYPTO_F_DONE) == 0)
769 		error = msleep(crp, &cse->lock, PWAIT, "crydev", 0);
770 	mtx_unlock(&cse->lock);
771 
772 	if (error != 0)
773 		goto bail;
774 
775 	if (crp->crp_etype == EAGAIN) {
776 		crp->crp_etype = 0;
777 		crp->crp_flags &= ~CRYPTO_F_DONE;
778 		goto again;
779 	}
780 
781 	if (crp->crp_etype != 0) {
782 		error = crp->crp_etype;
783 		goto bail;
784 	}
785 
786 	if (cse->error) {
787 		error = cse->error;
788 		goto bail;
789 	}
790 
791 	if (cop->dst &&
792 	    (error = copyout(cse->uio.uio_iov[0].iov_base, cop->dst, cop->len)))
793 		goto bail;
794 
795 	if (cop->mac &&
796 	    (error = copyout((caddr_t)cse->uio.uio_iov[0].iov_base + cop->len,
797 	    cop->mac, cse->thash->hashsize)))
798 		goto bail;
799 
800 bail:
801 	if (crp)
802 		crypto_freereq(crp);
803 	if (cse->uio.uio_iov[0].iov_base)
804 		free(cse->uio.uio_iov[0].iov_base, M_XDATA);
805 
806 	return (error);
807 }
808 
809 static int
810 cryptodev_cb(void *op)
811 {
812 	struct cryptop *crp = (struct cryptop *) op;
813 	struct csession *cse = (struct csession *)crp->crp_opaque;
814 
815 	mtx_lock(&cse->lock);
816 	cse->error = crp->crp_etype;
817 	wakeup_one(crp);
818 	mtx_unlock(&cse->lock);
819 	return (0);
820 }
821 
822 static int
823 cryptodevkey_cb(void *op)
824 {
825 	struct cryptkop *krp = (struct cryptkop *) op;
826 
827 	wakeup_one(krp);
828 	return (0);
829 }
830 
831 static int
832 cryptodev_key(struct crypt_kop *kop)
833 {
834 	struct cryptkop *krp = NULL;
835 	int error = EINVAL;
836 	int in, out, size, i;
837 
838 	if (kop->crk_iparams + kop->crk_oparams > CRK_MAXPARAM) {
839 		return (EFBIG);
840 	}
841 
842 	in = kop->crk_iparams;
843 	out = kop->crk_oparams;
844 	switch (kop->crk_op) {
845 	case CRK_MOD_EXP:
846 		if (in == 3 && out == 1)
847 			break;
848 		return (EINVAL);
849 	case CRK_MOD_EXP_CRT:
850 		if (in == 6 && out == 1)
851 			break;
852 		return (EINVAL);
853 	case CRK_DSA_SIGN:
854 		if (in == 5 && out == 2)
855 			break;
856 		return (EINVAL);
857 	case CRK_DSA_VERIFY:
858 		if (in == 7 && out == 0)
859 			break;
860 		return (EINVAL);
861 	case CRK_DH_COMPUTE_KEY:
862 		if (in == 3 && out == 1)
863 			break;
864 		return (EINVAL);
865 	default:
866 		return (EINVAL);
867 	}
868 
869 	krp = (struct cryptkop *)malloc(sizeof *krp, M_XDATA, M_WAITOK|M_ZERO);
870 	if (!krp)
871 		return (ENOMEM);
872 	krp->krp_op = kop->crk_op;
873 	krp->krp_status = kop->crk_status;
874 	krp->krp_iparams = kop->crk_iparams;
875 	krp->krp_oparams = kop->crk_oparams;
876 	krp->krp_crid = kop->crk_crid;
877 	krp->krp_status = 0;
878 	krp->krp_callback = (int (*) (struct cryptkop *)) cryptodevkey_cb;
879 
880 	for (i = 0; i < CRK_MAXPARAM; i++) {
881 		if (kop->crk_param[i].crp_nbits > 65536)
882 			/* Limit is the same as in OpenBSD */
883 			goto fail;
884 		krp->krp_param[i].crp_nbits = kop->crk_param[i].crp_nbits;
885 	}
886 	for (i = 0; i < krp->krp_iparams + krp->krp_oparams; i++) {
887 		size = (krp->krp_param[i].crp_nbits + 7) / 8;
888 		if (size == 0)
889 			continue;
890 		krp->krp_param[i].crp_p = malloc(size, M_XDATA, M_WAITOK);
891 		if (i >= krp->krp_iparams)
892 			continue;
893 		error = copyin(kop->crk_param[i].crp_p, krp->krp_param[i].crp_p, size);
894 		if (error)
895 			goto fail;
896 	}
897 
898 	error = crypto_kdispatch(krp);
899 	if (error)
900 		goto fail;
901 	error = tsleep(krp, PSOCK, "crydev", 0);
902 	if (error) {
903 		/* XXX can this happen?  if so, how do we recover? */
904 		goto fail;
905 	}
906 
907 	kop->crk_crid = krp->krp_crid;		/* device that did the work */
908 	if (krp->krp_status != 0) {
909 		error = krp->krp_status;
910 		goto fail;
911 	}
912 
913 	for (i = krp->krp_iparams; i < krp->krp_iparams + krp->krp_oparams; i++) {
914 		size = (krp->krp_param[i].crp_nbits + 7) / 8;
915 		if (size == 0)
916 			continue;
917 		error = copyout(krp->krp_param[i].crp_p, kop->crk_param[i].crp_p, size);
918 		if (error)
919 			goto fail;
920 	}
921 
922 fail:
923 	if (krp) {
924 		kop->crk_status = krp->krp_status;
925 		for (i = 0; i < CRK_MAXPARAM; i++) {
926 			if (krp->krp_param[i].crp_p)
927 				free(krp->krp_param[i].crp_p, M_XDATA);
928 		}
929 		free(krp, M_XDATA);
930 	}
931 	return (error);
932 }
933 
934 static int
935 cryptodev_find(struct crypt_find_op *find)
936 {
937 	device_t dev;
938 
939 	if (find->crid != -1) {
940 		dev = crypto_find_device_byhid(find->crid);
941 		if (dev == NULL)
942 			return (ENOENT);
943 		strlcpy(find->name, device_get_nameunit(dev),
944 		    sizeof(find->name));
945 	} else {
946 		find->crid = crypto_find_driver(find->name);
947 		if (find->crid == -1)
948 			return (ENOENT);
949 	}
950 	return (0);
951 }
952 
953 /* ARGSUSED */
954 static int
955 cryptof_poll(
956 	struct file *fp,
957 	int events,
958 	struct ucred *active_cred,
959 	struct thread *td)
960 {
961 
962 	return (0);
963 }
964 
965 /* ARGSUSED */
966 static int
967 cryptof_kqfilter(struct file *fp, struct knote *kn)
968 {
969 
970 	return (0);
971 }
972 
973 /* ARGSUSED */
974 static int
975 cryptof_stat(
976 	struct file *fp,
977 	struct stat *sb,
978 	struct ucred *active_cred,
979 	struct thread *td)
980 {
981 
982 	return (EOPNOTSUPP);
983 }
984 
985 /* ARGSUSED */
986 static int
987 cryptof_close(struct file *fp, struct thread *td)
988 {
989 	struct fcrypt *fcr = fp->f_data;
990 	struct csession *cse;
991 
992 	while ((cse = TAILQ_FIRST(&fcr->csessions))) {
993 		TAILQ_REMOVE(&fcr->csessions, cse, next);
994 		(void)csefree(cse);
995 	}
996 	free(fcr, M_XDATA);
997 	fp->f_data = NULL;
998 	return 0;
999 }
1000 
1001 static struct csession *
1002 csefind(struct fcrypt *fcr, u_int ses)
1003 {
1004 	struct csession *cse;
1005 
1006 	TAILQ_FOREACH(cse, &fcr->csessions, next)
1007 		if (cse->ses == ses)
1008 			return (cse);
1009 	return (NULL);
1010 }
1011 
1012 static int
1013 csedelete(struct fcrypt *fcr, struct csession *cse_del)
1014 {
1015 	struct csession *cse;
1016 
1017 	TAILQ_FOREACH(cse, &fcr->csessions, next) {
1018 		if (cse == cse_del) {
1019 			TAILQ_REMOVE(&fcr->csessions, cse, next);
1020 			return (1);
1021 		}
1022 	}
1023 	return (0);
1024 }
1025 
1026 static struct csession *
1027 cseadd(struct fcrypt *fcr, struct csession *cse)
1028 {
1029 	TAILQ_INSERT_TAIL(&fcr->csessions, cse, next);
1030 	cse->ses = fcr->sesn++;
1031 	return (cse);
1032 }
1033 
1034 struct csession *
1035 csecreate(struct fcrypt *fcr, u_int64_t sid, caddr_t key, u_int64_t keylen,
1036     caddr_t mackey, u_int64_t mackeylen, u_int32_t cipher, u_int32_t mac,
1037     struct enc_xform *txform, struct auth_hash *thash)
1038 {
1039 	struct csession *cse;
1040 
1041 #ifdef INVARIANTS
1042 	/* NB: required when mtx_init is built with INVARIANTS */
1043 	cse = malloc(sizeof(struct csession), M_XDATA, M_NOWAIT | M_ZERO);
1044 #else
1045 	cse = malloc(sizeof(struct csession), M_XDATA, M_NOWAIT);
1046 #endif
1047 	if (cse == NULL)
1048 		return NULL;
1049 	mtx_init(&cse->lock, "cryptodev", "crypto session lock", MTX_DEF);
1050 	cse->key = key;
1051 	cse->keylen = keylen/8;
1052 	cse->mackey = mackey;
1053 	cse->mackeylen = mackeylen/8;
1054 	cse->sid = sid;
1055 	cse->cipher = cipher;
1056 	cse->mac = mac;
1057 	cse->txform = txform;
1058 	cse->thash = thash;
1059 	cseadd(fcr, cse);
1060 	return (cse);
1061 }
1062 
1063 static int
1064 csefree(struct csession *cse)
1065 {
1066 	int error;
1067 
1068 	error = crypto_freesession(cse->sid);
1069 	mtx_destroy(&cse->lock);
1070 	if (cse->key)
1071 		free(cse->key, M_XDATA);
1072 	if (cse->mackey)
1073 		free(cse->mackey, M_XDATA);
1074 	free(cse, M_XDATA);
1075 	return (error);
1076 }
1077 
1078 static int
1079 cryptoopen(struct cdev *dev, int oflags, int devtype, struct thread *td)
1080 {
1081 	return (0);
1082 }
1083 
1084 static int
1085 cryptoread(struct cdev *dev, struct uio *uio, int ioflag)
1086 {
1087 	return (EIO);
1088 }
1089 
1090 static int
1091 cryptowrite(struct cdev *dev, struct uio *uio, int ioflag)
1092 {
1093 	return (EIO);
1094 }
1095 
1096 static int
1097 cryptoioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
1098 {
1099 	struct file *f;
1100 	struct fcrypt *fcr;
1101 	int fd, error;
1102 
1103 	switch (cmd) {
1104 	case CRIOGET:
1105 		fcr = malloc(sizeof(struct fcrypt), M_XDATA, M_WAITOK);
1106 		TAILQ_INIT(&fcr->csessions);
1107 		fcr->sesn = 0;
1108 
1109 		error = falloc(td, &f, &fd);
1110 
1111 		if (error) {
1112 			free(fcr, M_XDATA);
1113 			return (error);
1114 		}
1115 		/* falloc automatically provides an extra reference to 'f'. */
1116 		finit(f, FREAD | FWRITE, DTYPE_CRYPTO, fcr, &cryptofops);
1117 		*(u_int32_t *)data = fd;
1118 		fdrop(f, td);
1119 		break;
1120 	case CRIOFINDDEV:
1121 		error = cryptodev_find((struct crypt_find_op *)data);
1122 		break;
1123 	case CRIOASYMFEAT:
1124 		error = crypto_getfeat((int *)data);
1125 		break;
1126 	default:
1127 		error = EINVAL;
1128 		break;
1129 	}
1130 	return (error);
1131 }
1132 
1133 static struct cdevsw crypto_cdevsw = {
1134 	.d_version =	D_VERSION,
1135 	.d_flags =	D_NEEDGIANT,
1136 	.d_open =	cryptoopen,
1137 	.d_read =	cryptoread,
1138 	.d_write =	cryptowrite,
1139 	.d_ioctl =	cryptoioctl,
1140 	.d_name =	"crypto",
1141 };
1142 static struct cdev *crypto_dev;
1143 
1144 /*
1145  * Initialization code, both for static and dynamic loading.
1146  */
1147 static int
1148 cryptodev_modevent(module_t mod, int type, void *unused)
1149 {
1150 	switch (type) {
1151 	case MOD_LOAD:
1152 		if (bootverbose)
1153 			printf("crypto: <crypto device>\n");
1154 		crypto_dev = make_dev(&crypto_cdevsw, 0,
1155 				      UID_ROOT, GID_WHEEL, 0666,
1156 				      "crypto");
1157 		return 0;
1158 	case MOD_UNLOAD:
1159 		/*XXX disallow if active sessions */
1160 		destroy_dev(crypto_dev);
1161 		return 0;
1162 	}
1163 	return EINVAL;
1164 }
1165 
1166 static moduledata_t cryptodev_mod = {
1167 	"cryptodev",
1168 	cryptodev_modevent,
1169 	0
1170 };
1171 MODULE_VERSION(cryptodev, 1);
1172 DECLARE_MODULE(cryptodev, cryptodev_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
1173 MODULE_DEPEND(cryptodev, crypto, 1, 1, 1);
1174 MODULE_DEPEND(cryptodev, zlib, 1, 1, 1);
1175