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