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