Import OpenSSL-0.9.8m.
[dragonfly.git] / crypto / openssl / crypto / engine / eng_cryptodev.c
1 /*
2  * Copyright (c) 2002 Bob Beck <beck@openbsd.org>
3  * Copyright (c) 2002 Theo de Raadt
4  * Copyright (c) 2002 Markus Friedl
5  * All rights reserved.
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  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
20  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  *
27  */
28
29 #include <openssl/objects.h>
30 #include <openssl/engine.h>
31 #include <openssl/evp.h>
32 #include <openssl/bn.h>
33 #include <openssl/dsa.h>
34 #include <openssl/rsa.h>
35 #include <openssl/dh.h>
36 #include <openssl/err.h>
37
38 #if (defined(__unix__) || defined(unix)) && !defined(USG) && \
39         (defined(OpenBSD) || defined(__FreeBSD__))
40 #include <sys/param.h>
41 # if (OpenBSD >= 200112) || ((__FreeBSD_version >= 470101 && __FreeBSD_version < 500000) || __FreeBSD_version >= 500041)
42 #  define HAVE_CRYPTODEV
43 # endif
44 # if (OpenBSD >= 200110)
45 #  define HAVE_SYSLOG_R
46 # endif
47 #endif
48
49 #ifndef HAVE_CRYPTODEV
50
51 void
52 ENGINE_load_cryptodev(void)
53 {
54         /* This is a NOP on platforms without /dev/crypto */
55         return;
56 }
57
58 #else 
59  
60 #include <sys/types.h>
61 #include <crypto/cryptodev.h>
62 #include <sys/ioctl.h>
63 #include <errno.h>
64 #include <stdio.h>
65 #include <unistd.h>
66 #include <fcntl.h>
67 #include <stdarg.h>
68 #include <syslog.h>
69 #include <errno.h>
70 #include <string.h>
71
72 struct dev_crypto_state {
73         struct session_op d_sess;
74         int d_fd;
75 };
76
77 static u_int32_t cryptodev_asymfeat = 0;
78
79 static int get_asym_dev_crypto(void);
80 static int open_dev_crypto(void);
81 static int get_dev_crypto(void);
82 static int cryptodev_max_iv(int cipher);
83 static int cryptodev_key_length_valid(int cipher, int len);
84 static int cipher_nid_to_cryptodev(int nid);
85 static int get_cryptodev_ciphers(const int **cnids);
86 /*static int get_cryptodev_digests(const int **cnids);*/
87 static int cryptodev_usable_ciphers(const int **nids);
88 static int cryptodev_usable_digests(const int **nids);
89 static int cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
90     const unsigned char *in, unsigned int inl);
91 static int cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
92     const unsigned char *iv, int enc);
93 static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx);
94 static int cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
95     const int **nids, int nid);
96 static int cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest,
97     const int **nids, int nid);
98 static int bn2crparam(const BIGNUM *a, struct crparam *crp);
99 static int crparam2bn(struct crparam *crp, BIGNUM *a);
100 static void zapparams(struct crypt_kop *kop);
101 static int cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r,
102     int slen, BIGNUM *s);
103
104 static int cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a,
105     const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
106 static int cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I,
107     RSA *rsa, BN_CTX *ctx);
108 static int cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx);
109 static int cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a,
110     const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
111 static int cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g,
112     BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2, BIGNUM *p,
113     BN_CTX *ctx, BN_MONT_CTX *mont);
114 static DSA_SIG *cryptodev_dsa_do_sign(const unsigned char *dgst,
115     int dlen, DSA *dsa);
116 static int cryptodev_dsa_verify(const unsigned char *dgst, int dgst_len,
117     DSA_SIG *sig, DSA *dsa);
118 static int cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
119     const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
120     BN_MONT_CTX *m_ctx);
121 static int cryptodev_dh_compute_key(unsigned char *key,
122     const BIGNUM *pub_key, DH *dh);
123 static int cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p,
124     void (*f)());
125 void ENGINE_load_cryptodev(void);
126
127 static const ENGINE_CMD_DEFN cryptodev_defns[] = {
128         { 0, NULL, NULL, 0 }
129 };
130
131 static struct {
132         int     id;
133         int     nid;
134         int     ivmax;
135         int     keylen;
136 } ciphers[] = {
137         { CRYPTO_DES_CBC,               NID_des_cbc,            8,       8, },
138         { CRYPTO_3DES_CBC,              NID_des_ede3_cbc,       8,      24, },
139         { CRYPTO_AES_CBC,               NID_aes_128_cbc,        16,     16, },
140         { CRYPTO_BLF_CBC,               NID_bf_cbc,             8,      16, },
141         { CRYPTO_CAST_CBC,              NID_cast5_cbc,          8,      16, },
142         { CRYPTO_SKIPJACK_CBC,          NID_undef,              0,       0, },
143         { 0,                            NID_undef,              0,       0, },
144 };
145
146 #if 0
147 static struct {
148         int     id;
149         int     nid;
150 } digests[] = {
151         { CRYPTO_SHA1_HMAC,             NID_hmacWithSHA1,       },
152         { CRYPTO_RIPEMD160_HMAC,        NID_ripemd160,          },
153         { CRYPTO_MD5_KPDK,              NID_undef,              },
154         { CRYPTO_SHA1_KPDK,             NID_undef,              },
155         { CRYPTO_MD5,                   NID_md5,                },
156         { CRYPTO_SHA1,                  NID_undef,              },
157         { 0,                            NID_undef,              },
158 };
159 #endif
160
161 /*
162  * Return a fd if /dev/crypto seems usable, 0 otherwise.
163  */
164 static int
165 open_dev_crypto(void)
166 {
167         static int fd = -1;
168
169         if (fd == -1) {
170                 if ((fd = open("/dev/crypto", O_RDWR, 0)) == -1)
171                         return (-1);
172                 /* close on exec */
173                 if (fcntl(fd, F_SETFD, 1) == -1) {
174                         close(fd);
175                         fd = -1;
176                         return (-1);
177                 }
178         }
179         return (fd);
180 }
181
182 static int
183 get_dev_crypto(void)
184 {
185         int fd, retfd;
186
187         if ((fd = open_dev_crypto()) == -1)
188                 return (-1);
189         if (ioctl(fd, CRIOGET, &retfd) == -1)
190                 return (-1);
191
192         /* close on exec */
193         if (fcntl(retfd, F_SETFD, 1) == -1) {
194                 close(retfd);
195                 return (-1);
196         }
197         return (retfd);
198 }
199
200 /* Caching version for asym operations */
201 static int
202 get_asym_dev_crypto(void)
203 {
204         static int fd = -1;
205
206         if (fd == -1)
207                 fd = get_dev_crypto();
208         return fd;
209 }
210
211 /*
212  * XXXX this needs to be set for each alg - and determined from
213  * a running card.
214  */
215 static int
216 cryptodev_max_iv(int cipher)
217 {
218         int i;
219
220         for (i = 0; ciphers[i].id; i++)
221                 if (ciphers[i].id == cipher)
222                         return (ciphers[i].ivmax);
223         return (0);
224 }
225
226 /*
227  * XXXX this needs to be set for each alg - and determined from
228  * a running card. For now, fake it out - but most of these
229  * for real devices should return 1 for the supported key
230  * sizes the device can handle.
231  */
232 static int
233 cryptodev_key_length_valid(int cipher, int len)
234 {
235         int i;
236
237         for (i = 0; ciphers[i].id; i++)
238                 if (ciphers[i].id == cipher)
239                         return (ciphers[i].keylen == len);
240         return (0);
241 }
242
243 /* convert libcrypto nids to cryptodev */
244 static int
245 cipher_nid_to_cryptodev(int nid)
246 {
247         int i;
248
249         for (i = 0; ciphers[i].id; i++)
250                 if (ciphers[i].nid == nid)
251                         return (ciphers[i].id);
252         return (0);
253 }
254
255 /*
256  * Find out what ciphers /dev/crypto will let us have a session for.
257  * XXX note, that some of these openssl doesn't deal with yet!
258  * returning them here is harmless, as long as we return NULL
259  * when asked for a handler in the cryptodev_engine_ciphers routine
260  */
261 static int
262 get_cryptodev_ciphers(const int **cnids)
263 {
264         static int nids[CRYPTO_ALGORITHM_MAX];
265         struct session_op sess;
266         int fd, i, count = 0;
267
268         if ((fd = get_dev_crypto()) < 0) {
269                 *cnids = NULL;
270                 return (0);
271         }
272         memset(&sess, 0, sizeof(sess));
273         sess.key = (caddr_t)"123456781234567812345678";
274
275         for (i = 0; ciphers[i].id && count < CRYPTO_ALGORITHM_MAX; i++) {
276                 if (ciphers[i].nid == NID_undef)
277                         continue;
278                 sess.cipher = ciphers[i].id;
279                 sess.keylen = ciphers[i].keylen;
280                 sess.mac = 0;
281                 if (ioctl(fd, CIOCGSESSION, &sess) != -1 &&
282                     ioctl(fd, CIOCFSESSION, &sess.ses) != -1)
283                         nids[count++] = ciphers[i].nid;
284         }
285         close(fd);
286
287         if (count > 0)
288                 *cnids = nids;
289         else
290                 *cnids = NULL;
291         return (count);
292 }
293
294 #if 0  /* unused */
295 /*
296  * Find out what digests /dev/crypto will let us have a session for.
297  * XXX note, that some of these openssl doesn't deal with yet!
298  * returning them here is harmless, as long as we return NULL
299  * when asked for a handler in the cryptodev_engine_digests routine
300  */
301 static int
302 get_cryptodev_digests(const int **cnids)
303 {
304         static int nids[CRYPTO_ALGORITHM_MAX];
305         struct session_op sess;
306         int fd, i, count = 0;
307
308         if ((fd = get_dev_crypto()) < 0) {
309                 *cnids = NULL;
310                 return (0);
311         }
312         memset(&sess, 0, sizeof(sess));
313         for (i = 0; digests[i].id && count < CRYPTO_ALGORITHM_MAX; i++) {
314                 if (digests[i].nid == NID_undef)
315                         continue;
316                 sess.mac = digests[i].id;
317                 sess.cipher = 0;
318                 if (ioctl(fd, CIOCGSESSION, &sess) != -1 &&
319                     ioctl(fd, CIOCFSESSION, &sess.ses) != -1)
320                         nids[count++] = digests[i].nid;
321         }
322         close(fd);
323
324         if (count > 0)
325                 *cnids = nids;
326         else
327                 *cnids = NULL;
328         return (count);
329 }
330
331 #endif
332
333 /*
334  * Find the useable ciphers|digests from dev/crypto - this is the first
335  * thing called by the engine init crud which determines what it
336  * can use for ciphers from this engine. We want to return
337  * only what we can do, anythine else is handled by software.
338  *
339  * If we can't initialize the device to do anything useful for
340  * any reason, we want to return a NULL array, and 0 length,
341  * which forces everything to be done is software. By putting
342  * the initalization of the device in here, we ensure we can
343  * use this engine as the default, and if for whatever reason
344  * /dev/crypto won't do what we want it will just be done in
345  * software
346  *
347  * This can (should) be greatly expanded to perhaps take into
348  * account speed of the device, and what we want to do.
349  * (although the disabling of particular alg's could be controlled
350  * by the device driver with sysctl's.) - this is where we
351  * want most of the decisions made about what we actually want
352  * to use from /dev/crypto.
353  */
354 static int
355 cryptodev_usable_ciphers(const int **nids)
356 {
357         return (get_cryptodev_ciphers(nids));
358 }
359
360 static int
361 cryptodev_usable_digests(const int **nids)
362 {
363         /*
364          * XXXX just disable all digests for now, because it sucks.
365          * we need a better way to decide this - i.e. I may not
366          * want digests on slow cards like hifn on fast machines,
367          * but might want them on slow or loaded machines, etc.
368          * will also want them when using crypto cards that don't
369          * suck moose gonads - would be nice to be able to decide something
370          * as reasonable default without having hackery that's card dependent.
371          * of course, the default should probably be just do everything,
372          * with perhaps a sysctl to turn algoritms off (or have them off
373          * by default) on cards that generally suck like the hifn.
374          */
375         *nids = NULL;
376         return (0);
377 }
378
379 static int
380 cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
381     const unsigned char *in, unsigned int inl)
382 {
383         struct crypt_op cryp;
384         struct dev_crypto_state *state = ctx->cipher_data;
385         struct session_op *sess = &state->d_sess;
386         const void *iiv;
387         unsigned char save_iv[EVP_MAX_IV_LENGTH];
388
389         if (state->d_fd < 0)
390                 return (0);
391         if (!inl)
392                 return (1);
393         if ((inl % ctx->cipher->block_size) != 0)
394                 return (0);
395
396         memset(&cryp, 0, sizeof(cryp));
397
398         cryp.ses = sess->ses;
399         cryp.flags = 0;
400         cryp.len = inl;
401         cryp.src = (caddr_t) in;
402         cryp.dst = (caddr_t) out;
403         cryp.mac = 0;
404
405         cryp.op = ctx->encrypt ? COP_ENCRYPT : COP_DECRYPT;
406
407         if (ctx->cipher->iv_len) {
408                 cryp.iv = (caddr_t) ctx->iv;
409                 if (!ctx->encrypt) {
410                         iiv = in + inl - ctx->cipher->iv_len;
411                         memcpy(save_iv, iiv, ctx->cipher->iv_len);
412                 }
413         } else
414                 cryp.iv = NULL;
415
416         if (ioctl(state->d_fd, CIOCCRYPT, &cryp) == -1) {
417                 /* XXX need better errror handling
418                  * this can fail for a number of different reasons.
419                  */
420                 return (0);
421         }
422
423         if (ctx->cipher->iv_len) {
424                 if (ctx->encrypt)
425                         iiv = out + inl - ctx->cipher->iv_len;
426                 else
427                         iiv = save_iv;
428                 memcpy(ctx->iv, iiv, ctx->cipher->iv_len);
429         }
430         return (1);
431 }
432
433 static int
434 cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
435     const unsigned char *iv, int enc)
436 {
437         struct dev_crypto_state *state = ctx->cipher_data;
438         struct session_op *sess = &state->d_sess;
439         int cipher;
440
441         if ((cipher = cipher_nid_to_cryptodev(ctx->cipher->nid)) == NID_undef)
442                 return (0);
443
444         if (ctx->cipher->iv_len > cryptodev_max_iv(cipher))
445                 return (0);
446
447         if (!cryptodev_key_length_valid(cipher, ctx->key_len))
448                 return (0);
449
450         memset(sess, 0, sizeof(struct session_op));
451
452         if ((state->d_fd = get_dev_crypto()) < 0)
453                 return (0);
454
455         sess->key = (char *)key;
456         sess->keylen = ctx->key_len;
457         sess->cipher = cipher;
458
459         if (ioctl(state->d_fd, CIOCGSESSION, sess) == -1) {
460                 close(state->d_fd);
461                 state->d_fd = -1;
462                 return (0);
463         }
464         return (1);
465 }
466
467 /*
468  * free anything we allocated earlier when initting a
469  * session, and close the session.
470  */
471 static int
472 cryptodev_cleanup(EVP_CIPHER_CTX *ctx)
473 {
474         int ret = 0;
475         struct dev_crypto_state *state = ctx->cipher_data;
476         struct session_op *sess = &state->d_sess;
477
478         if (state->d_fd < 0)
479                 return (0);
480
481         /* XXX if this ioctl fails, someting's wrong. the invoker
482          * may have called us with a bogus ctx, or we could
483          * have a device that for whatever reason just doesn't
484          * want to play ball - it's not clear what's right
485          * here - should this be an error? should it just
486          * increase a counter, hmm. For right now, we return
487          * 0 - I don't believe that to be "right". we could
488          * call the gorpy openssl lib error handlers that
489          * print messages to users of the library. hmm..
490          */
491
492         if (ioctl(state->d_fd, CIOCFSESSION, &sess->ses) == -1) {
493                 ret = 0;
494         } else {
495                 ret = 1;
496         }
497         close(state->d_fd);
498         state->d_fd = -1;
499
500         return (ret);
501 }
502
503 /*
504  * libcrypto EVP stuff - this is how we get wired to EVP so the engine
505  * gets called when libcrypto requests a cipher NID.
506  */
507
508 /* DES CBC EVP */
509 const EVP_CIPHER cryptodev_des_cbc = {
510         NID_des_cbc,
511         8, 8, 8,
512         EVP_CIPH_CBC_MODE,
513         cryptodev_init_key,
514         cryptodev_cipher,
515         cryptodev_cleanup,
516         sizeof(struct dev_crypto_state),
517         EVP_CIPHER_set_asn1_iv,
518         EVP_CIPHER_get_asn1_iv,
519         NULL
520 };
521
522 /* 3DES CBC EVP */
523 const EVP_CIPHER cryptodev_3des_cbc = {
524         NID_des_ede3_cbc,
525         8, 24, 8,
526         EVP_CIPH_CBC_MODE,
527         cryptodev_init_key,
528         cryptodev_cipher,
529         cryptodev_cleanup,
530         sizeof(struct dev_crypto_state),
531         EVP_CIPHER_set_asn1_iv,
532         EVP_CIPHER_get_asn1_iv,
533         NULL
534 };
535
536 const EVP_CIPHER cryptodev_bf_cbc = {
537         NID_bf_cbc,
538         8, 16, 8,
539         EVP_CIPH_CBC_MODE,
540         cryptodev_init_key,
541         cryptodev_cipher,
542         cryptodev_cleanup,
543         sizeof(struct dev_crypto_state),
544         EVP_CIPHER_set_asn1_iv,
545         EVP_CIPHER_get_asn1_iv,
546         NULL
547 };
548
549 const EVP_CIPHER cryptodev_cast_cbc = {
550         NID_cast5_cbc,
551         8, 16, 8,
552         EVP_CIPH_CBC_MODE,
553         cryptodev_init_key,
554         cryptodev_cipher,
555         cryptodev_cleanup,
556         sizeof(struct dev_crypto_state),
557         EVP_CIPHER_set_asn1_iv,
558         EVP_CIPHER_get_asn1_iv,
559         NULL
560 };
561
562 const EVP_CIPHER cryptodev_aes_cbc = {
563         NID_aes_128_cbc,
564         16, 16, 16,
565         EVP_CIPH_CBC_MODE,
566         cryptodev_init_key,
567         cryptodev_cipher,
568         cryptodev_cleanup,
569         sizeof(struct dev_crypto_state),
570         EVP_CIPHER_set_asn1_iv,
571         EVP_CIPHER_get_asn1_iv,
572         NULL
573 };
574
575 /*
576  * Registered by the ENGINE when used to find out how to deal with
577  * a particular NID in the ENGINE. this says what we'll do at the
578  * top level - note, that list is restricted by what we answer with
579  */
580 static int
581 cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
582     const int **nids, int nid)
583 {
584         if (!cipher)
585                 return (cryptodev_usable_ciphers(nids));
586
587         switch (nid) {
588         case NID_des_ede3_cbc:
589                 *cipher = &cryptodev_3des_cbc;
590                 break;
591         case NID_des_cbc:
592                 *cipher = &cryptodev_des_cbc;
593                 break;
594         case NID_bf_cbc:
595                 *cipher = &cryptodev_bf_cbc;
596                 break;
597         case NID_cast5_cbc:
598                 *cipher = &cryptodev_cast_cbc;
599                 break;
600         case NID_aes_128_cbc:
601                 *cipher = &cryptodev_aes_cbc;
602                 break;
603         default:
604                 *cipher = NULL;
605                 break;
606         }
607         return (*cipher != NULL);
608 }
609
610 static int
611 cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest,
612     const int **nids, int nid)
613 {
614         if (!digest)
615                 return (cryptodev_usable_digests(nids));
616
617         switch (nid) {
618         case NID_md5:
619                 *digest = NULL; /* need to make a clean md5 critter */
620                 break;
621         default:
622                 *digest = NULL;
623                 break;
624         }
625         return (*digest != NULL);
626 }
627
628 /*
629  * Convert a BIGNUM to the representation that /dev/crypto needs.
630  * Upon completion of use, the caller is responsible for freeing
631  * crp->crp_p.
632  */
633 static int
634 bn2crparam(const BIGNUM *a, struct crparam *crp)
635 {
636         int i, j, k;
637         ssize_t bytes, bits;
638         u_char *b;
639
640         crp->crp_p = NULL;
641         crp->crp_nbits = 0;
642
643         bits = BN_num_bits(a);
644         bytes = (bits + 7) / 8;
645
646         b = malloc(bytes);
647         if (b == NULL)
648                 return (1);
649
650         crp->crp_p = (char *)b;
651         crp->crp_nbits = bits;
652
653         for (i = 0, j = 0; i < a->top; i++) {
654                 for (k = 0; k < BN_BITS2 / 8; k++) {
655                         if ((j + k) >= bytes)
656                                 return (0);
657                         b[j + k] = a->d[i] >> (k * 8);
658                 }
659                 j += BN_BITS2 / 8;
660         }
661         return (0);
662 }
663
664 /* Convert a /dev/crypto parameter to a BIGNUM */
665 static int
666 crparam2bn(struct crparam *crp, BIGNUM *a)
667 {
668         u_int8_t *pd;
669         int i, bytes;
670
671         bytes = (crp->crp_nbits + 7) / 8;
672
673         if (bytes == 0)
674                 return (-1);
675
676         if ((pd = (u_int8_t *) malloc(bytes)) == NULL)
677                 return (-1);
678
679         for (i = 0; i < bytes; i++)
680                 pd[i] = crp->crp_p[bytes - i - 1];
681
682         BN_bin2bn(pd, bytes, a);
683         free(pd);
684
685         return (0);
686 }
687
688 static void
689 zapparams(struct crypt_kop *kop)
690 {
691         int i;
692
693         for (i = 0; i <= kop->crk_iparams + kop->crk_oparams; i++) {
694                 if (kop->crk_param[i].crp_p)
695                         free(kop->crk_param[i].crp_p);
696                 kop->crk_param[i].crp_p = NULL;
697                 kop->crk_param[i].crp_nbits = 0;
698         }
699 }
700
701 static int
702 cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r, int slen, BIGNUM *s)
703 {
704         int fd, ret = -1;
705
706         if ((fd = get_asym_dev_crypto()) < 0)
707                 return (ret);
708
709         if (r) {
710                 kop->crk_param[kop->crk_iparams].crp_p = calloc(rlen, sizeof(char));
711                 kop->crk_param[kop->crk_iparams].crp_nbits = rlen * 8;
712                 kop->crk_oparams++;
713         }
714         if (s) {
715                 kop->crk_param[kop->crk_iparams+1].crp_p = calloc(slen, sizeof(char));
716                 kop->crk_param[kop->crk_iparams+1].crp_nbits = slen * 8;
717                 kop->crk_oparams++;
718         }
719
720         if (ioctl(fd, CIOCKEY, kop) == 0) {
721                 if (r)
722                         crparam2bn(&kop->crk_param[kop->crk_iparams], r);
723                 if (s)
724                         crparam2bn(&kop->crk_param[kop->crk_iparams+1], s);
725                 ret = 0;
726         }
727
728         return (ret);
729 }
730
731 static int
732 cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
733     const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
734 {
735         struct crypt_kop kop;
736         int ret = 1;
737
738         /* Currently, we know we can do mod exp iff we can do any
739          * asymmetric operations at all.
740          */
741         if (cryptodev_asymfeat == 0) {
742                 ret = BN_mod_exp(r, a, p, m, ctx);
743                 return (ret);
744         }
745
746         memset(&kop, 0, sizeof kop);
747         kop.crk_op = CRK_MOD_EXP;
748
749         /* inputs: a^p % m */
750         if (bn2crparam(a, &kop.crk_param[0]))
751                 goto err;
752         if (bn2crparam(p, &kop.crk_param[1]))
753                 goto err;
754         if (bn2crparam(m, &kop.crk_param[2]))
755                 goto err;
756         kop.crk_iparams = 3;
757
758         if (cryptodev_asym(&kop, BN_num_bytes(m), r, 0, NULL) == -1) {
759                 const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
760                 ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont);
761         }
762 err:
763         zapparams(&kop);
764         return (ret);
765 }
766
767 static int
768 cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
769 {
770         int r;
771
772         r = cryptodev_bn_mod_exp(r0, I, rsa->d, rsa->n, ctx, NULL);
773         return (r);
774 }
775
776 static int
777 cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
778 {
779         struct crypt_kop kop;
780         int ret = 1;
781
782         if (!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) {
783                 /* XXX 0 means failure?? */
784                 return (0);
785         }
786
787         memset(&kop, 0, sizeof kop);
788         kop.crk_op = CRK_MOD_EXP_CRT;
789         /* inputs: rsa->p rsa->q I rsa->dmp1 rsa->dmq1 rsa->iqmp */
790         if (bn2crparam(rsa->p, &kop.crk_param[0]))
791                 goto err;
792         if (bn2crparam(rsa->q, &kop.crk_param[1]))
793                 goto err;
794         if (bn2crparam(I, &kop.crk_param[2]))
795                 goto err;
796         if (bn2crparam(rsa->dmp1, &kop.crk_param[3]))
797                 goto err;
798         if (bn2crparam(rsa->dmq1, &kop.crk_param[4]))
799                 goto err;
800         if (bn2crparam(rsa->iqmp, &kop.crk_param[5]))
801                 goto err;
802         kop.crk_iparams = 6;
803
804         if (cryptodev_asym(&kop, BN_num_bytes(rsa->n), r0, 0, NULL) == -1) {
805                 const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
806                 ret = (*meth->rsa_mod_exp)(r0, I, rsa, ctx);
807         }
808 err:
809         zapparams(&kop);
810         return (ret);
811 }
812
813 static RSA_METHOD cryptodev_rsa = {
814         "cryptodev RSA method",
815         NULL,                           /* rsa_pub_enc */
816         NULL,                           /* rsa_pub_dec */
817         NULL,                           /* rsa_priv_enc */
818         NULL,                           /* rsa_priv_dec */
819         NULL,
820         NULL,
821         NULL,                           /* init */
822         NULL,                           /* finish */
823         0,                              /* flags */
824         NULL,                           /* app_data */
825         NULL,                           /* rsa_sign */
826         NULL                            /* rsa_verify */
827 };
828
829 static int
830 cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p,
831     const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
832 {
833         return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx));
834 }
835
836 static int
837 cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g,
838     BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2, BIGNUM *p,
839     BN_CTX *ctx, BN_MONT_CTX *mont)
840 {
841         BIGNUM t2;
842         int ret = 0;
843
844         BN_init(&t2);
845
846         /* v = ( g^u1 * y^u2 mod p ) mod q */
847         /* let t1 = g ^ u1 mod p */
848         ret = 0;
849
850         if (!dsa->meth->bn_mod_exp(dsa,t1,dsa->g,u1,dsa->p,ctx,mont))
851                 goto err;
852
853         /* let t2 = y ^ u2 mod p */
854         if (!dsa->meth->bn_mod_exp(dsa,&t2,dsa->pub_key,u2,dsa->p,ctx,mont))
855                 goto err;
856         /* let u1 = t1 * t2 mod p */
857         if (!BN_mod_mul(u1,t1,&t2,dsa->p,ctx))
858                 goto err;
859
860         BN_copy(t1,u1);
861
862         ret = 1;
863 err:
864         BN_free(&t2);
865         return(ret);
866 }
867
868 static DSA_SIG *
869 cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa)
870 {
871         struct crypt_kop kop;
872         BIGNUM *r = NULL, *s = NULL;
873         DSA_SIG *dsaret = NULL;
874
875         if ((r = BN_new()) == NULL)
876                 goto err;
877         if ((s = BN_new()) == NULL) {
878                 BN_free(r);
879                 goto err;
880         }
881
882         memset(&kop, 0, sizeof kop);
883         kop.crk_op = CRK_DSA_SIGN;
884
885         /* inputs: dgst dsa->p dsa->q dsa->g dsa->priv_key */
886         kop.crk_param[0].crp_p = (caddr_t)dgst;
887         kop.crk_param[0].crp_nbits = dlen * 8;
888         if (bn2crparam(dsa->p, &kop.crk_param[1]))
889                 goto err;
890         if (bn2crparam(dsa->q, &kop.crk_param[2]))
891                 goto err;
892         if (bn2crparam(dsa->g, &kop.crk_param[3]))
893                 goto err;
894         if (bn2crparam(dsa->priv_key, &kop.crk_param[4]))
895                 goto err;
896         kop.crk_iparams = 5;
897
898         if (cryptodev_asym(&kop, BN_num_bytes(dsa->q), r,
899             BN_num_bytes(dsa->q), s) == 0) {
900                 dsaret = DSA_SIG_new();
901                 dsaret->r = r;
902                 dsaret->s = s;
903         } else {
904                 const DSA_METHOD *meth = DSA_OpenSSL();
905                 BN_free(r);
906                 BN_free(s);
907                 dsaret = (meth->dsa_do_sign)(dgst, dlen, dsa);
908         }
909 err:
910         kop.crk_param[0].crp_p = NULL;
911         zapparams(&kop);
912         return (dsaret);
913 }
914
915 static int
916 cryptodev_dsa_verify(const unsigned char *dgst, int dlen,
917     DSA_SIG *sig, DSA *dsa)
918 {
919         struct crypt_kop kop;
920         int dsaret = 1;
921
922         memset(&kop, 0, sizeof kop);
923         kop.crk_op = CRK_DSA_VERIFY;
924
925         /* inputs: dgst dsa->p dsa->q dsa->g dsa->pub_key sig->r sig->s */
926         kop.crk_param[0].crp_p = (caddr_t)dgst;
927         kop.crk_param[0].crp_nbits = dlen * 8;
928         if (bn2crparam(dsa->p, &kop.crk_param[1]))
929                 goto err;
930         if (bn2crparam(dsa->q, &kop.crk_param[2]))
931                 goto err;
932         if (bn2crparam(dsa->g, &kop.crk_param[3]))
933                 goto err;
934         if (bn2crparam(dsa->pub_key, &kop.crk_param[4]))
935                 goto err;
936         if (bn2crparam(sig->r, &kop.crk_param[5]))
937                 goto err;
938         if (bn2crparam(sig->s, &kop.crk_param[6]))
939                 goto err;
940         kop.crk_iparams = 7;
941
942         if (cryptodev_asym(&kop, 0, NULL, 0, NULL) == 0) {
943                 dsaret = kop.crk_status;
944         } else {
945                 const DSA_METHOD *meth = DSA_OpenSSL();
946
947                 dsaret = (meth->dsa_do_verify)(dgst, dlen, sig, dsa);
948         }
949 err:
950         kop.crk_param[0].crp_p = NULL;
951         zapparams(&kop);
952         return (dsaret);
953 }
954
955 static DSA_METHOD cryptodev_dsa = {
956         "cryptodev DSA method",
957         NULL,
958         NULL,                           /* dsa_sign_setup */
959         NULL,
960         NULL,                           /* dsa_mod_exp */
961         NULL,
962         NULL,                           /* init */
963         NULL,                           /* finish */
964         0,      /* flags */
965         NULL    /* app_data */
966 };
967
968 static int
969 cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
970     const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
971     BN_MONT_CTX *m_ctx)
972 {
973         return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx));
974 }
975
976 static int
977 cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh)
978 {
979         struct crypt_kop kop;
980         int dhret = 1;
981         int fd, keylen;
982
983         if ((fd = get_asym_dev_crypto()) < 0) {
984                 const DH_METHOD *meth = DH_OpenSSL();
985
986                 return ((meth->compute_key)(key, pub_key, dh));
987         }
988
989         keylen = BN_num_bits(dh->p);
990
991         memset(&kop, 0, sizeof kop);
992         kop.crk_op = CRK_DH_COMPUTE_KEY;
993
994         /* inputs: dh->priv_key pub_key dh->p key */
995         if (bn2crparam(dh->priv_key, &kop.crk_param[0]))
996                 goto err;
997         if (bn2crparam(pub_key, &kop.crk_param[1]))
998                 goto err;
999         if (bn2crparam(dh->p, &kop.crk_param[2]))
1000                 goto err;
1001         kop.crk_iparams = 3;
1002
1003         kop.crk_param[3].crp_p = (char *)key;
1004         kop.crk_param[3].crp_nbits = keylen * 8;
1005         kop.crk_oparams = 1;
1006
1007         if (ioctl(fd, CIOCKEY, &kop) == -1) {
1008                 const DH_METHOD *meth = DH_OpenSSL();
1009
1010                 dhret = (meth->compute_key)(key, pub_key, dh);
1011         }
1012 err:
1013         kop.crk_param[3].crp_p = NULL;
1014         zapparams(&kop);
1015         return (dhret);
1016 }
1017
1018 static DH_METHOD cryptodev_dh = {
1019         "cryptodev DH method",
1020         NULL,                           /* cryptodev_dh_generate_key */
1021         NULL,
1022         NULL,
1023         NULL,
1024         NULL,
1025         0,      /* flags */
1026         NULL    /* app_data */
1027 };
1028
1029 /*
1030  * ctrl right now is just a wrapper that doesn't do much
1031  * but I expect we'll want some options soon.
1032  */
1033 static int
1034 cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)())
1035 {
1036 #ifdef HAVE_SYSLOG_R
1037         struct syslog_data sd = SYSLOG_DATA_INIT;
1038 #endif
1039
1040         switch (cmd) {
1041         default:
1042 #ifdef HAVE_SYSLOG_R
1043                 syslog_r(LOG_ERR, &sd,
1044                     "cryptodev_ctrl: unknown command %d", cmd);
1045 #else
1046                 syslog(LOG_ERR, "cryptodev_ctrl: unknown command %d", cmd);
1047 #endif
1048                 break;
1049         }
1050         return (1);
1051 }
1052
1053 void
1054 ENGINE_load_cryptodev(void)
1055 {
1056         ENGINE *engine = ENGINE_new();
1057         int fd;
1058
1059         if (engine == NULL)
1060                 return;
1061         if ((fd = get_dev_crypto()) < 0) {
1062                 ENGINE_free(engine);
1063                 return;
1064         }
1065
1066         /*
1067          * find out what asymmetric crypto algorithms we support
1068          */
1069         if (ioctl(fd, CIOCASYMFEAT, &cryptodev_asymfeat) == -1) {
1070                 close(fd);
1071                 ENGINE_free(engine);
1072                 return;
1073         }
1074         close(fd);
1075
1076         if (!ENGINE_set_id(engine, "cryptodev") ||
1077             !ENGINE_set_name(engine, "BSD cryptodev engine") ||
1078             !ENGINE_set_ciphers(engine, cryptodev_engine_ciphers) ||
1079             !ENGINE_set_digests(engine, cryptodev_engine_digests) ||
1080             !ENGINE_set_ctrl_function(engine, cryptodev_ctrl) ||
1081             !ENGINE_set_cmd_defns(engine, cryptodev_defns)) {
1082                 ENGINE_free(engine);
1083                 return;
1084         }
1085
1086         if (ENGINE_set_RSA(engine, &cryptodev_rsa)) {
1087                 const RSA_METHOD *rsa_meth = RSA_PKCS1_SSLeay();
1088
1089                 cryptodev_rsa.bn_mod_exp = rsa_meth->bn_mod_exp;
1090                 cryptodev_rsa.rsa_mod_exp = rsa_meth->rsa_mod_exp;
1091                 cryptodev_rsa.rsa_pub_enc = rsa_meth->rsa_pub_enc;
1092                 cryptodev_rsa.rsa_pub_dec = rsa_meth->rsa_pub_dec;
1093                 cryptodev_rsa.rsa_priv_enc = rsa_meth->rsa_priv_enc;
1094                 cryptodev_rsa.rsa_priv_dec = rsa_meth->rsa_priv_dec;
1095                 if (cryptodev_asymfeat & CRF_MOD_EXP) {
1096                         cryptodev_rsa.bn_mod_exp = cryptodev_bn_mod_exp;
1097                         if (cryptodev_asymfeat & CRF_MOD_EXP_CRT)
1098                                 cryptodev_rsa.rsa_mod_exp =
1099                                     cryptodev_rsa_mod_exp;
1100                         else
1101                                 cryptodev_rsa.rsa_mod_exp =
1102                                     cryptodev_rsa_nocrt_mod_exp;
1103                 }
1104         }
1105
1106         if (ENGINE_set_DSA(engine, &cryptodev_dsa)) {
1107                 const DSA_METHOD *meth = DSA_OpenSSL();
1108
1109                 memcpy(&cryptodev_dsa, meth, sizeof(DSA_METHOD));
1110                 if (cryptodev_asymfeat & CRF_DSA_SIGN)
1111                         cryptodev_dsa.dsa_do_sign = cryptodev_dsa_do_sign;
1112                 if (cryptodev_asymfeat & CRF_MOD_EXP) {
1113                         cryptodev_dsa.bn_mod_exp = cryptodev_dsa_bn_mod_exp;
1114                         cryptodev_dsa.dsa_mod_exp = cryptodev_dsa_dsa_mod_exp;
1115                 }
1116                 if (cryptodev_asymfeat & CRF_DSA_VERIFY)
1117                         cryptodev_dsa.dsa_do_verify = cryptodev_dsa_verify;
1118         }
1119
1120         if (ENGINE_set_DH(engine, &cryptodev_dh)){
1121                 const DH_METHOD *dh_meth = DH_OpenSSL();
1122
1123                 cryptodev_dh.generate_key = dh_meth->generate_key;
1124                 cryptodev_dh.compute_key = dh_meth->compute_key;
1125                 cryptodev_dh.bn_mod_exp = dh_meth->bn_mod_exp;
1126                 if (cryptodev_asymfeat & CRF_MOD_EXP) {
1127                         cryptodev_dh.bn_mod_exp = cryptodev_mod_exp_dh;
1128                         if (cryptodev_asymfeat & CRF_DH_COMPUTE_KEY)
1129                                 cryptodev_dh.compute_key =
1130                                     cryptodev_dh_compute_key;
1131                 }
1132         }
1133
1134         ENGINE_add(engine);
1135         ENGINE_free(engine);
1136         ERR_clear_error();
1137 }
1138
1139 #endif /* HAVE_CRYPTODEV */