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