Use OPENSSL_malloc rather than malloc/calloc
[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__))
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 ENGINE_load_cryptodev(void)
48 {
49     /* This is a NOP on platforms without /dev/crypto */
50     return;
51 }
52
53 #else
54
55 # include <sys/types.h>
56 # include <crypto/cryptodev.h>
57 # include <openssl/dh.h>
58 # include <openssl/dsa.h>
59 # include <openssl/err.h>
60 # include <openssl/rsa.h>
61 # include <sys/ioctl.h>
62 # include <errno.h>
63 # include <stdio.h>
64 # include <unistd.h>
65 # include <fcntl.h>
66 # include <stdarg.h>
67 # include <syslog.h>
68 # include <errno.h>
69 # include <string.h>
70
71 struct dev_crypto_state {
72     struct session_op d_sess;
73     int d_fd;
74 # ifdef USE_CRYPTODEV_DIGESTS
75     char dummy_mac_key[HASH_MAX_LEN];
76     unsigned char digest_res[HASH_MAX_LEN];
77     char *mac_data;
78     int mac_len;
79 # endif
80 };
81
82 static u_int32_t cryptodev_asymfeat = 0;
83
84 static int get_asym_dev_crypto(void);
85 static int open_dev_crypto(void);
86 static int get_dev_crypto(void);
87 static int get_cryptodev_ciphers(const int **cnids);
88 # ifdef USE_CRYPTODEV_DIGESTS
89 static int get_cryptodev_digests(const int **cnids);
90 # endif
91 static int cryptodev_usable_ciphers(const int **nids);
92 static int cryptodev_usable_digests(const int **nids);
93 static int cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
94                             const unsigned char *in, size_t inl);
95 static int cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
96                               const unsigned char *iv, int enc);
97 static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx);
98 static int cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
99                                     const int **nids, int nid);
100 static int cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest,
101                                     const int **nids, int nid);
102 static int bn2crparam(const BIGNUM *a, struct crparam *crp);
103 static int crparam2bn(struct crparam *crp, BIGNUM *a);
104 static void zapparams(struct crypt_kop *kop);
105 static int cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r,
106                           int slen, BIGNUM *s);
107
108 static int cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a,
109                                 const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
110                                 BN_MONT_CTX *m_ctx);
111 static int cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
112                                        BN_CTX *ctx);
113 static int cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
114                                  BN_CTX *ctx);
115 static int cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a,
116                                     const BIGNUM *p, const BIGNUM *m,
117                                     BN_CTX *ctx, BN_MONT_CTX *m_ctx);
118 static int cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g,
119                                      BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2,
120                                      BIGNUM *p, BN_CTX *ctx,
121                                      BN_MONT_CTX *mont);
122 static DSA_SIG *cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen,
123                                       DSA *dsa);
124 static int cryptodev_dsa_verify(const unsigned char *dgst, int dgst_len,
125                                 DSA_SIG *sig, DSA *dsa);
126 static int cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
127                                 const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
128                                 BN_MONT_CTX *m_ctx);
129 static int cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key,
130                                     DH *dh);
131 static int cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p,
132                           void (*f) (void));
133 void ENGINE_load_cryptodev(void);
134
135 static const ENGINE_CMD_DEFN cryptodev_defns[] = {
136     {0, NULL, NULL, 0}
137 };
138
139 static struct {
140     int id;
141     int nid;
142     int ivmax;
143     int keylen;
144 } ciphers[] = {
145     {
146         CRYPTO_ARC4, NID_rc4, 0, 16,
147     },
148     {
149         CRYPTO_DES_CBC, NID_des_cbc, 8, 8,
150     },
151     {
152         CRYPTO_3DES_CBC, NID_des_ede3_cbc, 8, 24,
153     },
154     {
155         CRYPTO_AES_CBC, NID_aes_128_cbc, 16, 16,
156     },
157     {
158         CRYPTO_AES_CBC, NID_aes_192_cbc, 16, 24,
159     },
160     {
161         CRYPTO_AES_CBC, NID_aes_256_cbc, 16, 32,
162     },
163 # ifdef CRYPTO_AES_CTR
164     {
165         CRYPTO_AES_CTR, NID_aes_128_ctr, 14, 16,
166     },
167     {
168         CRYPTO_AES_CTR, NID_aes_192_ctr, 14, 24,
169     },
170     {
171         CRYPTO_AES_CTR, NID_aes_256_ctr, 14, 32,
172     },
173 # endif
174     {
175         CRYPTO_BLF_CBC, NID_bf_cbc, 8, 16,
176     },
177     {
178         CRYPTO_CAST_CBC, NID_cast5_cbc, 8, 16,
179     },
180     {
181         CRYPTO_SKIPJACK_CBC, NID_undef, 0, 0,
182     },
183     {
184         0, NID_undef, 0, 0,
185     },
186 };
187
188 # ifdef USE_CRYPTODEV_DIGESTS
189 static struct {
190     int id;
191     int nid;
192     int keylen;
193 } digests[] = {
194     {
195         CRYPTO_MD5_HMAC, NID_hmacWithMD5, 16
196     },
197     {
198         CRYPTO_SHA1_HMAC, NID_hmacWithSHA1, 20
199     },
200     {
201         CRYPTO_RIPEMD160_HMAC, NID_ripemd160, 16
202         /* ? */
203     },
204     {
205         CRYPTO_MD5_KPDK, NID_undef, 0
206     },
207     {
208         CRYPTO_SHA1_KPDK, NID_undef, 0
209     },
210     {
211         CRYPTO_MD5, NID_md5, 16
212     },
213     {
214         CRYPTO_SHA1, NID_sha1, 20
215     },
216     {
217         0, NID_undef, 0
218     },
219 };
220 # endif
221
222 /*
223  * Return a fd if /dev/crypto seems usable, 0 otherwise.
224  */
225 static int open_dev_crypto(void)
226 {
227     static int fd = -1;
228
229     if (fd == -1) {
230         if ((fd = open("/dev/crypto", O_RDWR, 0)) == -1)
231             return (-1);
232         /* close on exec */
233         if (fcntl(fd, F_SETFD, 1) == -1) {
234             close(fd);
235             fd = -1;
236             return (-1);
237         }
238     }
239     return (fd);
240 }
241
242 static int get_dev_crypto(void)
243 {
244     int fd, retfd;
245
246     if ((fd = open_dev_crypto()) == -1)
247         return (-1);
248 # ifndef CRIOGET_NOT_NEEDED
249     if (ioctl(fd, CRIOGET, &retfd) == -1)
250         return (-1);
251
252     /* close on exec */
253     if (fcntl(retfd, F_SETFD, 1) == -1) {
254         close(retfd);
255         return (-1);
256     }
257 # else
258     retfd = fd;
259 # endif
260     return (retfd);
261 }
262
263 static void put_dev_crypto(int fd)
264 {
265 # ifndef CRIOGET_NOT_NEEDED
266     close(fd);
267 # endif
268 }
269
270 /* Caching version for asym operations */
271 static int get_asym_dev_crypto(void)
272 {
273     static int fd = -1;
274
275     if (fd == -1)
276         fd = get_dev_crypto();
277     return fd;
278 }
279
280 /*
281  * Find out what ciphers /dev/crypto will let us have a session for.
282  * XXX note, that some of these openssl doesn't deal with yet!
283  * returning them here is harmless, as long as we return NULL
284  * when asked for a handler in the cryptodev_engine_ciphers routine
285  */
286 static int get_cryptodev_ciphers(const int **cnids)
287 {
288     static int nids[CRYPTO_ALGORITHM_MAX];
289     struct session_op sess;
290     int fd, i, count = 0;
291
292     if ((fd = get_dev_crypto()) < 0) {
293         *cnids = NULL;
294         return (0);
295     }
296     memset(&sess, 0, sizeof(sess));
297     sess.key = (caddr_t) "123456789abcdefghijklmno";
298
299     for (i = 0; ciphers[i].id && count < CRYPTO_ALGORITHM_MAX; i++) {
300         if (ciphers[i].nid == NID_undef)
301             continue;
302         sess.cipher = ciphers[i].id;
303         sess.keylen = ciphers[i].keylen;
304         sess.mac = 0;
305         if (ioctl(fd, CIOCGSESSION, &sess) != -1 &&
306             ioctl(fd, CIOCFSESSION, &sess.ses) != -1)
307             nids[count++] = ciphers[i].nid;
308     }
309     put_dev_crypto(fd);
310
311     if (count > 0)
312         *cnids = nids;
313     else
314         *cnids = NULL;
315     return (count);
316 }
317
318 # ifdef USE_CRYPTODEV_DIGESTS
319 /*
320  * Find out what digests /dev/crypto will let us have a session for.
321  * XXX note, that some of these openssl doesn't deal with yet!
322  * returning them here is harmless, as long as we return NULL
323  * when asked for a handler in the cryptodev_engine_digests routine
324  */
325 static int get_cryptodev_digests(const int **cnids)
326 {
327     static int nids[CRYPTO_ALGORITHM_MAX];
328     struct session_op sess;
329     int fd, i, count = 0;
330
331     if ((fd = get_dev_crypto()) < 0) {
332         *cnids = NULL;
333         return (0);
334     }
335     memset(&sess, 0, sizeof(sess));
336     sess.mackey = (caddr_t) "123456789abcdefghijklmno";
337     for (i = 0; digests[i].id && count < CRYPTO_ALGORITHM_MAX; i++) {
338         if (digests[i].nid == NID_undef)
339             continue;
340         sess.mac = digests[i].id;
341         sess.mackeylen = digests[i].keylen;
342         sess.cipher = 0;
343         if (ioctl(fd, CIOCGSESSION, &sess) != -1 &&
344             ioctl(fd, CIOCFSESSION, &sess.ses) != -1)
345             nids[count++] = digests[i].nid;
346     }
347     put_dev_crypto(fd);
348
349     if (count > 0)
350         *cnids = nids;
351     else
352         *cnids = NULL;
353     return (count);
354 }
355 # endif                         /* 0 */
356
357 /*
358  * Find the useable ciphers|digests from dev/crypto - this is the first
359  * thing called by the engine init crud which determines what it
360  * can use for ciphers from this engine. We want to return
361  * only what we can do, anythine else is handled by software.
362  *
363  * If we can't initialize the device to do anything useful for
364  * any reason, we want to return a NULL array, and 0 length,
365  * which forces everything to be done is software. By putting
366  * the initalization of the device in here, we ensure we can
367  * use this engine as the default, and if for whatever reason
368  * /dev/crypto won't do what we want it will just be done in
369  * software
370  *
371  * This can (should) be greatly expanded to perhaps take into
372  * account speed of the device, and what we want to do.
373  * (although the disabling of particular alg's could be controlled
374  * by the device driver with sysctl's.) - this is where we
375  * want most of the decisions made about what we actually want
376  * to use from /dev/crypto.
377  */
378 static int cryptodev_usable_ciphers(const int **nids)
379 {
380     return (get_cryptodev_ciphers(nids));
381 }
382
383 static int cryptodev_usable_digests(const int **nids)
384 {
385 # ifdef USE_CRYPTODEV_DIGESTS
386     return (get_cryptodev_digests(nids));
387 # else
388     /*
389      * XXXX just disable all digests for now, because it sucks.
390      * we need a better way to decide this - i.e. I may not
391      * want digests on slow cards like hifn on fast machines,
392      * but might want them on slow or loaded machines, etc.
393      * will also want them when using crypto cards that don't
394      * suck moose gonads - would be nice to be able to decide something
395      * as reasonable default without having hackery that's card dependent.
396      * of course, the default should probably be just do everything,
397      * with perhaps a sysctl to turn algoritms off (or have them off
398      * by default) on cards that generally suck like the hifn.
399      */
400     *nids = NULL;
401     return (0);
402 # endif
403 }
404
405 static int
406 cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
407                  const unsigned char *in, size_t inl)
408 {
409     struct crypt_op cryp;
410     struct dev_crypto_state *state = ctx->cipher_data;
411     struct session_op *sess = &state->d_sess;
412     const void *iiv;
413     unsigned char save_iv[EVP_MAX_IV_LENGTH];
414
415     if (state->d_fd < 0)
416         return (0);
417     if (!inl)
418         return (1);
419     if ((inl % ctx->cipher->block_size) != 0)
420         return (0);
421
422     memset(&cryp, 0, sizeof(cryp));
423
424     cryp.ses = sess->ses;
425     cryp.flags = 0;
426     cryp.len = inl;
427     cryp.src = (caddr_t) in;
428     cryp.dst = (caddr_t) out;
429     cryp.mac = 0;
430
431     cryp.op = ctx->encrypt ? COP_ENCRYPT : COP_DECRYPT;
432
433     if (ctx->cipher->iv_len) {
434         cryp.iv = (caddr_t) ctx->iv;
435         if (!ctx->encrypt) {
436             iiv = in + inl - ctx->cipher->iv_len;
437             memcpy(save_iv, iiv, ctx->cipher->iv_len);
438         }
439     } else
440         cryp.iv = NULL;
441
442     if (ioctl(state->d_fd, CIOCCRYPT, &cryp) == -1) {
443         /*
444          * XXX need better errror handling this can fail for a number of
445          * different reasons.
446          */
447         return (0);
448     }
449
450     if (ctx->cipher->iv_len) {
451         if (ctx->encrypt)
452             iiv = out + inl - ctx->cipher->iv_len;
453         else
454             iiv = save_iv;
455         memcpy(ctx->iv, iiv, ctx->cipher->iv_len);
456     }
457     return (1);
458 }
459
460 static int
461 cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
462                    const unsigned char *iv, int enc)
463 {
464     struct dev_crypto_state *state = ctx->cipher_data;
465     struct session_op *sess = &state->d_sess;
466     int cipher = -1, i;
467
468     for (i = 0; ciphers[i].id; i++)
469         if (ctx->cipher->nid == ciphers[i].nid &&
470             ctx->cipher->iv_len <= ciphers[i].ivmax &&
471             ctx->key_len == ciphers[i].keylen) {
472             cipher = ciphers[i].id;
473             break;
474         }
475
476     if (!ciphers[i].id) {
477         state->d_fd = -1;
478         return (0);
479     }
480
481     memset(sess, 0, sizeof(struct session_op));
482
483     if ((state->d_fd = get_dev_crypto()) < 0)
484         return (0);
485
486     sess->key = (caddr_t) key;
487     sess->keylen = ctx->key_len;
488     sess->cipher = cipher;
489
490     if (ioctl(state->d_fd, CIOCGSESSION, sess) == -1) {
491         put_dev_crypto(state->d_fd);
492         state->d_fd = -1;
493         return (0);
494     }
495     return (1);
496 }
497
498 /*
499  * free anything we allocated earlier when initting a
500  * session, and close the session.
501  */
502 static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx)
503 {
504     int ret = 0;
505     struct dev_crypto_state *state = ctx->cipher_data;
506     struct session_op *sess = &state->d_sess;
507
508     if (state->d_fd < 0)
509         return (0);
510
511     /*
512      * XXX if this ioctl fails, someting's wrong. the invoker may have called
513      * us with a bogus ctx, or we could have a device that for whatever
514      * reason just doesn't want to play ball - it's not clear what's right
515      * here - should this be an error? should it just increase a counter,
516      * hmm. For right now, we return 0 - I don't believe that to be "right".
517      * we could call the gorpy openssl lib error handlers that print messages
518      * to users of the library. hmm..
519      */
520
521     if (ioctl(state->d_fd, CIOCFSESSION, &sess->ses) == -1) {
522         ret = 0;
523     } else {
524         ret = 1;
525     }
526     put_dev_crypto(state->d_fd);
527     state->d_fd = -1;
528
529     return (ret);
530 }
531
532 /*
533  * libcrypto EVP stuff - this is how we get wired to EVP so the engine
534  * gets called when libcrypto requests a cipher NID.
535  */
536
537 /* RC4 */
538 const EVP_CIPHER cryptodev_rc4 = {
539     NID_rc4,
540     1, 16, 0,
541     EVP_CIPH_VARIABLE_LENGTH,
542     cryptodev_init_key,
543     cryptodev_cipher,
544     cryptodev_cleanup,
545     sizeof(struct dev_crypto_state),
546     NULL,
547     NULL,
548     NULL
549 };
550
551 /* DES CBC EVP */
552 const EVP_CIPHER cryptodev_des_cbc = {
553     NID_des_cbc,
554     8, 8, 8,
555     EVP_CIPH_CBC_MODE,
556     cryptodev_init_key,
557     cryptodev_cipher,
558     cryptodev_cleanup,
559     sizeof(struct dev_crypto_state),
560     EVP_CIPHER_set_asn1_iv,
561     EVP_CIPHER_get_asn1_iv,
562     NULL
563 };
564
565 /* 3DES CBC EVP */
566 const EVP_CIPHER cryptodev_3des_cbc = {
567     NID_des_ede3_cbc,
568     8, 24, 8,
569     EVP_CIPH_CBC_MODE,
570     cryptodev_init_key,
571     cryptodev_cipher,
572     cryptodev_cleanup,
573     sizeof(struct dev_crypto_state),
574     EVP_CIPHER_set_asn1_iv,
575     EVP_CIPHER_get_asn1_iv,
576     NULL
577 };
578
579 const EVP_CIPHER cryptodev_bf_cbc = {
580     NID_bf_cbc,
581     8, 16, 8,
582     EVP_CIPH_CBC_MODE,
583     cryptodev_init_key,
584     cryptodev_cipher,
585     cryptodev_cleanup,
586     sizeof(struct dev_crypto_state),
587     EVP_CIPHER_set_asn1_iv,
588     EVP_CIPHER_get_asn1_iv,
589     NULL
590 };
591
592 const EVP_CIPHER cryptodev_cast_cbc = {
593     NID_cast5_cbc,
594     8, 16, 8,
595     EVP_CIPH_CBC_MODE,
596     cryptodev_init_key,
597     cryptodev_cipher,
598     cryptodev_cleanup,
599     sizeof(struct dev_crypto_state),
600     EVP_CIPHER_set_asn1_iv,
601     EVP_CIPHER_get_asn1_iv,
602     NULL
603 };
604
605 const EVP_CIPHER cryptodev_aes_cbc = {
606     NID_aes_128_cbc,
607     16, 16, 16,
608     EVP_CIPH_CBC_MODE,
609     cryptodev_init_key,
610     cryptodev_cipher,
611     cryptodev_cleanup,
612     sizeof(struct dev_crypto_state),
613     EVP_CIPHER_set_asn1_iv,
614     EVP_CIPHER_get_asn1_iv,
615     NULL
616 };
617
618 const EVP_CIPHER cryptodev_aes_192_cbc = {
619     NID_aes_192_cbc,
620     16, 24, 16,
621     EVP_CIPH_CBC_MODE,
622     cryptodev_init_key,
623     cryptodev_cipher,
624     cryptodev_cleanup,
625     sizeof(struct dev_crypto_state),
626     EVP_CIPHER_set_asn1_iv,
627     EVP_CIPHER_get_asn1_iv,
628     NULL
629 };
630
631 const EVP_CIPHER cryptodev_aes_256_cbc = {
632     NID_aes_256_cbc,
633     16, 32, 16,
634     EVP_CIPH_CBC_MODE,
635     cryptodev_init_key,
636     cryptodev_cipher,
637     cryptodev_cleanup,
638     sizeof(struct dev_crypto_state),
639     EVP_CIPHER_set_asn1_iv,
640     EVP_CIPHER_get_asn1_iv,
641     NULL
642 };
643
644 # ifdef CRYPTO_AES_CTR
645 const EVP_CIPHER cryptodev_aes_ctr = {
646     NID_aes_128_ctr,
647     16, 16, 14,
648     EVP_CIPH_CTR_MODE,
649     cryptodev_init_key,
650     cryptodev_cipher,
651     cryptodev_cleanup,
652     sizeof(struct dev_crypto_state),
653     EVP_CIPHER_set_asn1_iv,
654     EVP_CIPHER_get_asn1_iv,
655     NULL
656 };
657
658 const EVP_CIPHER cryptodev_aes_ctr_192 = {
659     NID_aes_192_ctr,
660     16, 24, 14,
661     EVP_CIPH_CTR_MODE,
662     cryptodev_init_key,
663     cryptodev_cipher,
664     cryptodev_cleanup,
665     sizeof(struct dev_crypto_state),
666     EVP_CIPHER_set_asn1_iv,
667     EVP_CIPHER_get_asn1_iv,
668     NULL
669 };
670
671 const EVP_CIPHER cryptodev_aes_ctr_256 = {
672     NID_aes_256_ctr,
673     16, 32, 14,
674     EVP_CIPH_CTR_MODE,
675     cryptodev_init_key,
676     cryptodev_cipher,
677     cryptodev_cleanup,
678     sizeof(struct dev_crypto_state),
679     EVP_CIPHER_set_asn1_iv,
680     EVP_CIPHER_get_asn1_iv,
681     NULL
682 };
683 # endif
684 /*
685  * Registered by the ENGINE when used to find out how to deal with
686  * a particular NID in the ENGINE. this says what we'll do at the
687  * top level - note, that list is restricted by what we answer with
688  */
689 static int
690 cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
691                          const int **nids, int nid)
692 {
693     if (!cipher)
694         return (cryptodev_usable_ciphers(nids));
695
696     switch (nid) {
697     case NID_rc4:
698         *cipher = &cryptodev_rc4;
699         break;
700     case NID_des_ede3_cbc:
701         *cipher = &cryptodev_3des_cbc;
702         break;
703     case NID_des_cbc:
704         *cipher = &cryptodev_des_cbc;
705         break;
706     case NID_bf_cbc:
707         *cipher = &cryptodev_bf_cbc;
708         break;
709     case NID_cast5_cbc:
710         *cipher = &cryptodev_cast_cbc;
711         break;
712     case NID_aes_128_cbc:
713         *cipher = &cryptodev_aes_cbc;
714         break;
715     case NID_aes_192_cbc:
716         *cipher = &cryptodev_aes_192_cbc;
717         break;
718     case NID_aes_256_cbc:
719         *cipher = &cryptodev_aes_256_cbc;
720         break;
721 # ifdef CRYPTO_AES_CTR
722     case NID_aes_128_ctr:
723         *cipher = &cryptodev_aes_ctr;
724         break;
725     case NID_aes_192_ctr:
726         *cipher = &cryptodev_aes_ctr_192;
727         break;
728     case NID_aes_256_ctr:
729         *cipher = &cryptodev_aes_ctr_256;
730         break;
731 # endif
732     default:
733         *cipher = NULL;
734         break;
735     }
736     return (*cipher != NULL);
737 }
738
739 # ifdef USE_CRYPTODEV_DIGESTS
740
741 /* convert digest type to cryptodev */
742 static int digest_nid_to_cryptodev(int nid)
743 {
744     int i;
745
746     for (i = 0; digests[i].id; i++)
747         if (digests[i].nid == nid)
748             return (digests[i].id);
749     return (0);
750 }
751
752 static int digest_key_length(int nid)
753 {
754     int i;
755
756     for (i = 0; digests[i].id; i++)
757         if (digests[i].nid == nid)
758             return digests[i].keylen;
759     return (0);
760 }
761
762 static int cryptodev_digest_init(EVP_MD_CTX *ctx)
763 {
764     struct dev_crypto_state *state = ctx->md_data;
765     struct session_op *sess = &state->d_sess;
766     int digest;
767
768     if ((digest = digest_nid_to_cryptodev(ctx->digest->type)) == NID_undef) {
769         printf("cryptodev_digest_init: Can't get digest \n");
770         return (0);
771     }
772
773     memset(state, 0, sizeof(struct dev_crypto_state));
774
775     if ((state->d_fd = get_dev_crypto()) < 0) {
776         printf("cryptodev_digest_init: Can't get Dev \n");
777         return (0);
778     }
779
780     sess->mackey = state->dummy_mac_key;
781     sess->mackeylen = digest_key_length(ctx->digest->type);
782     sess->mac = digest;
783
784     if (ioctl(state->d_fd, CIOCGSESSION, sess) < 0) {
785         put_dev_crypto(state->d_fd);
786         state->d_fd = -1;
787         printf("cryptodev_digest_init: Open session failed\n");
788         return (0);
789     }
790
791     return (1);
792 }
793
794 static int cryptodev_digest_update(EVP_MD_CTX *ctx, const void *data,
795                                    size_t count)
796 {
797     struct crypt_op cryp;
798     struct dev_crypto_state *state = ctx->md_data;
799     struct session_op *sess = &state->d_sess;
800     char *new_mac_data;
801
802     if (!data || state->d_fd < 0) {
803         printf("cryptodev_digest_update: illegal inputs \n");
804         return (0);
805     }
806
807     if (!count) {
808         return (0);
809     }
810
811     if (!(ctx->flags & EVP_MD_CTX_FLAG_ONESHOT)) {
812         /* if application doesn't support one buffer */
813         new_mac_data =
814             OPENSSL_realloc(state->mac_data, state->mac_len + count);
815
816         if (!new_mac_data) {
817             printf("cryptodev_digest_update: realloc failed\n");
818             return (0);
819         }
820         state->mac_data = new_mac_data;
821
822         memcpy(state->mac_data + state->mac_len, data, count);
823         state->mac_len += count;
824
825         return (1);
826     }
827
828     memset(&cryp, 0, sizeof(cryp));
829
830     cryp.ses = sess->ses;
831     cryp.flags = 0;
832     cryp.len = count;
833     cryp.src = (caddr_t) data;
834     cryp.dst = NULL;
835     cryp.mac = (caddr_t) state->digest_res;
836     if (ioctl(state->d_fd, CIOCCRYPT, &cryp) < 0) {
837         printf("cryptodev_digest_update: digest failed\n");
838         return (0);
839     }
840     return (1);
841 }
842
843 static int cryptodev_digest_final(EVP_MD_CTX *ctx, unsigned char *md)
844 {
845     struct crypt_op cryp;
846     struct dev_crypto_state *state = ctx->md_data;
847     struct session_op *sess = &state->d_sess;
848
849     int ret = 1;
850
851     if (!md || state->d_fd < 0) {
852         printf("cryptodev_digest_final: illegal input\n");
853         return (0);
854     }
855
856     if (!(ctx->flags & EVP_MD_CTX_FLAG_ONESHOT)) {
857         /* if application doesn't support one buffer */
858         memset(&cryp, 0, sizeof(cryp));
859         cryp.ses = sess->ses;
860         cryp.flags = 0;
861         cryp.len = state->mac_len;
862         cryp.src = state->mac_data;
863         cryp.dst = NULL;
864         cryp.mac = (caddr_t) md;
865         if (ioctl(state->d_fd, CIOCCRYPT, &cryp) < 0) {
866             printf("cryptodev_digest_final: digest failed\n");
867             return (0);
868         }
869
870         return 1;
871     }
872
873     memcpy(md, state->digest_res, ctx->digest->md_size);
874
875     return (ret);
876 }
877
878 static int cryptodev_digest_cleanup(EVP_MD_CTX *ctx)
879 {
880     int ret = 1;
881     struct dev_crypto_state *state = ctx->md_data;
882     struct session_op *sess = &state->d_sess;
883
884     if (state == NULL)
885         return 0;
886
887     if (state->d_fd < 0) {
888         printf("cryptodev_digest_cleanup: illegal input\n");
889         return (0);
890     }
891
892     if (state->mac_data) {
893         OPENSSL_free(state->mac_data);
894         state->mac_data = NULL;
895         state->mac_len = 0;
896     }
897
898     if (ioctl(state->d_fd, CIOCFSESSION, &sess->ses) < 0) {
899         printf("cryptodev_digest_cleanup: failed to close session\n");
900         ret = 0;
901     } else {
902         ret = 1;
903     }
904     put_dev_crypto(state->d_fd);
905     state->d_fd = -1;
906
907     return (ret);
908 }
909
910 static int cryptodev_digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from)
911 {
912     struct dev_crypto_state *fstate = from->md_data;
913     struct dev_crypto_state *dstate = to->md_data;
914     struct session_op *sess;
915     int digest;
916
917     if (dstate == NULL || fstate == NULL)
918         return 1;
919
920     memcpy(dstate, fstate, sizeof(struct dev_crypto_state));
921
922     sess = &dstate->d_sess;
923
924     digest = digest_nid_to_cryptodev(to->digest->type);
925
926     sess->mackey = dstate->dummy_mac_key;
927     sess->mackeylen = digest_key_length(to->digest->type);
928     sess->mac = digest;
929
930     dstate->d_fd = get_dev_crypto();
931
932     if (ioctl(dstate->d_fd, CIOCGSESSION, sess) < 0) {
933         put_dev_crypto(dstate->d_fd);
934         dstate->d_fd = -1;
935         printf("cryptodev_digest_copy: Open session failed\n");
936         return (0);
937     }
938
939     if (fstate->mac_len != 0) {
940         if (fstate->mac_data != NULL) {
941             dstate->mac_data = OPENSSL_malloc(fstate->mac_len);
942             if (dstate->mac_data == NULL) {
943                 printf("cryptodev_digest_copy: mac_data allocation failed\n");
944                 return (0);
945             }
946             memcpy(dstate->mac_data, fstate->mac_data, fstate->mac_len);
947             dstate->mac_len = fstate->mac_len;
948         }
949     }
950
951     return 1;
952 }
953
954 const EVP_MD cryptodev_sha1 = {
955     NID_sha1,
956     NID_undef,
957     SHA_DIGEST_LENGTH,
958     EVP_MD_FLAG_ONESHOT,
959     cryptodev_digest_init,
960     cryptodev_digest_update,
961     cryptodev_digest_final,
962     cryptodev_digest_copy,
963     cryptodev_digest_cleanup,
964     EVP_PKEY_NULL_method,
965     SHA_CBLOCK,
966     sizeof(struct dev_crypto_state),
967 };
968
969 const EVP_MD cryptodev_md5 = {
970     NID_md5,
971     NID_undef,
972     16 /* MD5_DIGEST_LENGTH */ ,
973     EVP_MD_FLAG_ONESHOT,
974     cryptodev_digest_init,
975     cryptodev_digest_update,
976     cryptodev_digest_final,
977     cryptodev_digest_copy,
978     cryptodev_digest_cleanup,
979     EVP_PKEY_NULL_method,
980     64 /* MD5_CBLOCK */ ,
981     sizeof(struct dev_crypto_state),
982 };
983
984 # endif                         /* USE_CRYPTODEV_DIGESTS */
985
986 static int
987 cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest,
988                          const int **nids, int nid)
989 {
990     if (!digest)
991         return (cryptodev_usable_digests(nids));
992
993     switch (nid) {
994 # ifdef USE_CRYPTODEV_DIGESTS
995     case NID_md5:
996         *digest = &cryptodev_md5;
997         break;
998     case NID_sha1:
999         *digest = &cryptodev_sha1;
1000         break;
1001     default:
1002 # endif                         /* USE_CRYPTODEV_DIGESTS */
1003         *digest = NULL;
1004         break;
1005     }
1006     return (*digest != NULL);
1007 }
1008
1009 /*
1010  * Convert a BIGNUM to the representation that /dev/crypto needs.
1011  * Upon completion of use, the caller is responsible for freeing
1012  * crp->crp_p.
1013  */
1014 static int bn2crparam(const BIGNUM *a, struct crparam *crp)
1015 {
1016     ssize_t bytes, bits;
1017     u_char *b;
1018
1019     crp->crp_p = NULL;
1020     crp->crp_nbits = 0;
1021
1022     bits = BN_num_bits(a);
1023     bytes = BN_num_bytes(a);
1024
1025     b = OPENSSL_malloc(bytes);
1026     if (b == NULL)
1027         return (1);
1028     memset(b, 0, bytes);
1029
1030     crp->crp_p = (caddr_t) b;
1031     crp->crp_nbits = bits;
1032
1033     BN_bn2bin(a, b);
1034     return (0);
1035 }
1036
1037 /* Convert a /dev/crypto parameter to a BIGNUM */
1038 static int crparam2bn(struct crparam *crp, BIGNUM *a)
1039 {
1040     u_int8_t *pd;
1041     int i, bytes;
1042
1043     bytes = (crp->crp_nbits + 7) / 8;
1044
1045     if (bytes == 0)
1046         return (-1);
1047
1048     if ((pd = (u_int8_t *) OPENSSL_malloc(bytes)) == NULL)
1049         return (-1);
1050
1051     for (i = 0; i < bytes; i++)
1052         pd[i] = crp->crp_p[bytes - i - 1];
1053
1054     BN_bin2bn(pd, bytes, a);
1055     free(pd);
1056
1057     return (0);
1058 }
1059
1060 static void zapparams(struct crypt_kop *kop)
1061 {
1062     int i;
1063
1064     for (i = 0; i < kop->crk_iparams + kop->crk_oparams; i++) {
1065         if (kop->crk_param[i].crp_p)
1066             free(kop->crk_param[i].crp_p);
1067         kop->crk_param[i].crp_p = NULL;
1068         kop->crk_param[i].crp_nbits = 0;
1069     }
1070 }
1071
1072 static int
1073 cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r, int slen,
1074                BIGNUM *s)
1075 {
1076     int fd, ret = -1;
1077
1078     if ((fd = get_asym_dev_crypto()) < 0)
1079         return (ret);
1080
1081     if (r) {
1082         kop->crk_param[kop->crk_iparams].crp_p = calloc(rlen, sizeof(char));
1083         kop->crk_param[kop->crk_iparams].crp_nbits = rlen * 8;
1084         kop->crk_oparams++;
1085     }
1086     if (s) {
1087         kop->crk_param[kop->crk_iparams + 1].crp_p =
1088             calloc(slen, sizeof(char));
1089         kop->crk_param[kop->crk_iparams + 1].crp_nbits = slen * 8;
1090         kop->crk_oparams++;
1091     }
1092
1093     if (ioctl(fd, CIOCKEY, kop) == 0) {
1094         if (r)
1095             crparam2bn(&kop->crk_param[kop->crk_iparams], r);
1096         if (s)
1097             crparam2bn(&kop->crk_param[kop->crk_iparams + 1], s);
1098         ret = 0;
1099     }
1100
1101     return (ret);
1102 }
1103
1104 static int
1105 cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
1106                      const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
1107 {
1108     struct crypt_kop kop;
1109     int ret = 1;
1110
1111     /*
1112      * Currently, we know we can do mod exp iff we can do any asymmetric
1113      * operations at all.
1114      */
1115     if (cryptodev_asymfeat == 0) {
1116         ret = BN_mod_exp(r, a, p, m, ctx);
1117         return (ret);
1118     }
1119
1120     memset(&kop, 0, sizeof kop);
1121     kop.crk_op = CRK_MOD_EXP;
1122
1123     /* inputs: a^p % m */
1124     if (bn2crparam(a, &kop.crk_param[0]))
1125         goto err;
1126     if (bn2crparam(p, &kop.crk_param[1]))
1127         goto err;
1128     if (bn2crparam(m, &kop.crk_param[2]))
1129         goto err;
1130     kop.crk_iparams = 3;
1131
1132     if (cryptodev_asym(&kop, BN_num_bytes(m), r, 0, NULL)) {
1133         const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
1134         printf("OCF asym process failed, Running in software\n");
1135         ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont);
1136
1137     } else if (ECANCELED == kop.crk_status) {
1138         const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
1139         printf("OCF hardware operation cancelled. Running in Software\n");
1140         ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont);
1141     }
1142     /* else cryptodev operation worked ok ==> ret = 1 */
1143
1144  err:
1145     zapparams(&kop);
1146     return (ret);
1147 }
1148
1149 static int
1150 cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
1151                             BN_CTX *ctx)
1152 {
1153     int r;
1154     ctx = BN_CTX_new();
1155     r = cryptodev_bn_mod_exp(r0, I, rsa->d, rsa->n, ctx, NULL);
1156     BN_CTX_free(ctx);
1157     return (r);
1158 }
1159
1160 static int
1161 cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
1162 {
1163     struct crypt_kop kop;
1164     int ret = 1;
1165
1166     if (!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) {
1167         /* XXX 0 means failure?? */
1168         return (0);
1169     }
1170
1171     memset(&kop, 0, sizeof kop);
1172     kop.crk_op = CRK_MOD_EXP_CRT;
1173     /* inputs: rsa->p rsa->q I rsa->dmp1 rsa->dmq1 rsa->iqmp */
1174     if (bn2crparam(rsa->p, &kop.crk_param[0]))
1175         goto err;
1176     if (bn2crparam(rsa->q, &kop.crk_param[1]))
1177         goto err;
1178     if (bn2crparam(I, &kop.crk_param[2]))
1179         goto err;
1180     if (bn2crparam(rsa->dmp1, &kop.crk_param[3]))
1181         goto err;
1182     if (bn2crparam(rsa->dmq1, &kop.crk_param[4]))
1183         goto err;
1184     if (bn2crparam(rsa->iqmp, &kop.crk_param[5]))
1185         goto err;
1186     kop.crk_iparams = 6;
1187
1188     if (cryptodev_asym(&kop, BN_num_bytes(rsa->n), r0, 0, NULL)) {
1189         const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
1190         printf("OCF asym process failed, running in Software\n");
1191         ret = (*meth->rsa_mod_exp) (r0, I, rsa, ctx);
1192
1193     } else if (ECANCELED == kop.crk_status) {
1194         const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
1195         printf("OCF hardware operation cancelled. Running in Software\n");
1196         ret = (*meth->rsa_mod_exp) (r0, I, rsa, ctx);
1197     }
1198     /* else cryptodev operation worked ok ==> ret = 1 */
1199
1200  err:
1201     zapparams(&kop);
1202     return (ret);
1203 }
1204
1205 static RSA_METHOD cryptodev_rsa = {
1206     "cryptodev RSA method",
1207     NULL,                       /* rsa_pub_enc */
1208     NULL,                       /* rsa_pub_dec */
1209     NULL,                       /* rsa_priv_enc */
1210     NULL,                       /* rsa_priv_dec */
1211     NULL,
1212     NULL,
1213     NULL,                       /* init */
1214     NULL,                       /* finish */
1215     0,                          /* flags */
1216     NULL,                       /* app_data */
1217     NULL,                       /* rsa_sign */
1218     NULL                        /* rsa_verify */
1219 };
1220
1221 static int
1222 cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p,
1223                          const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
1224 {
1225     return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx));
1226 }
1227
1228 static int
1229 cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g,
1230                           BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2, BIGNUM *p,
1231                           BN_CTX *ctx, BN_MONT_CTX *mont)
1232 {
1233     BIGNUM *t2;
1234     int ret = 0;
1235
1236     t2 = BN_new();
1237
1238     /* v = ( g^u1 * y^u2 mod p ) mod q */
1239     /* let t1 = g ^ u1 mod p */
1240     ret = 0;
1241
1242     if (!dsa->meth->bn_mod_exp(dsa, t1, dsa->g, u1, dsa->p, ctx, mont))
1243         goto err;
1244
1245     /* let t2 = y ^ u2 mod p */
1246     if (!dsa->meth->bn_mod_exp(dsa, t2, dsa->pub_key, u2, dsa->p, ctx, mont))
1247         goto err;
1248     /* let u1 = t1 * t2 mod p */
1249     if (!BN_mod_mul(u1, t1, t2, dsa->p, ctx))
1250         goto err;
1251
1252     BN_copy(t1, u1);
1253
1254     ret = 1;
1255  err:
1256     BN_free(t2);
1257     return (ret);
1258 }
1259
1260 static DSA_SIG *cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen,
1261                                       DSA *dsa)
1262 {
1263     struct crypt_kop kop;
1264     BIGNUM *r = NULL, *s = NULL;
1265     DSA_SIG *dsaret = NULL;
1266
1267     if ((r = BN_new()) == NULL)
1268         goto err;
1269     if ((s = BN_new()) == NULL) {
1270         BN_free(r);
1271         goto err;
1272     }
1273
1274     memset(&kop, 0, sizeof kop);
1275     kop.crk_op = CRK_DSA_SIGN;
1276
1277     /* inputs: dgst dsa->p dsa->q dsa->g dsa->priv_key */
1278     kop.crk_param[0].crp_p = (caddr_t) dgst;
1279     kop.crk_param[0].crp_nbits = dlen * 8;
1280     if (bn2crparam(dsa->p, &kop.crk_param[1]))
1281         goto err;
1282     if (bn2crparam(dsa->q, &kop.crk_param[2]))
1283         goto err;
1284     if (bn2crparam(dsa->g, &kop.crk_param[3]))
1285         goto err;
1286     if (bn2crparam(dsa->priv_key, &kop.crk_param[4]))
1287         goto err;
1288     kop.crk_iparams = 5;
1289
1290     if (cryptodev_asym(&kop, BN_num_bytes(dsa->q), r,
1291                        BN_num_bytes(dsa->q), s) == 0) {
1292         dsaret = DSA_SIG_new();
1293         dsaret->r = r;
1294         dsaret->s = s;
1295     } else {
1296         const DSA_METHOD *meth = DSA_OpenSSL();
1297         BN_free(r);
1298         BN_free(s);
1299         dsaret = (meth->dsa_do_sign) (dgst, dlen, dsa);
1300     }
1301  err:
1302     kop.crk_param[0].crp_p = NULL;
1303     zapparams(&kop);
1304     return (dsaret);
1305 }
1306
1307 static int
1308 cryptodev_dsa_verify(const unsigned char *dgst, int dlen,
1309                      DSA_SIG *sig, DSA *dsa)
1310 {
1311     struct crypt_kop kop;
1312     int dsaret = 1;
1313
1314     memset(&kop, 0, sizeof kop);
1315     kop.crk_op = CRK_DSA_VERIFY;
1316
1317     /* inputs: dgst dsa->p dsa->q dsa->g dsa->pub_key sig->r sig->s */
1318     kop.crk_param[0].crp_p = (caddr_t) dgst;
1319     kop.crk_param[0].crp_nbits = dlen * 8;
1320     if (bn2crparam(dsa->p, &kop.crk_param[1]))
1321         goto err;
1322     if (bn2crparam(dsa->q, &kop.crk_param[2]))
1323         goto err;
1324     if (bn2crparam(dsa->g, &kop.crk_param[3]))
1325         goto err;
1326     if (bn2crparam(dsa->pub_key, &kop.crk_param[4]))
1327         goto err;
1328     if (bn2crparam(sig->r, &kop.crk_param[5]))
1329         goto err;
1330     if (bn2crparam(sig->s, &kop.crk_param[6]))
1331         goto err;
1332     kop.crk_iparams = 7;
1333
1334     if (cryptodev_asym(&kop, 0, NULL, 0, NULL) == 0) {
1335         /*
1336          * OCF success value is 0, if not zero, change dsaret to fail
1337          */
1338         if (0 != kop.crk_status)
1339             dsaret = 0;
1340     } else {
1341         const DSA_METHOD *meth = DSA_OpenSSL();
1342
1343         dsaret = (meth->dsa_do_verify) (dgst, dlen, sig, dsa);
1344     }
1345  err:
1346     kop.crk_param[0].crp_p = NULL;
1347     zapparams(&kop);
1348     return (dsaret);
1349 }
1350
1351 static DSA_METHOD cryptodev_dsa = {
1352     "cryptodev DSA method",
1353     NULL,
1354     NULL,                       /* dsa_sign_setup */
1355     NULL,
1356     NULL,                       /* dsa_mod_exp */
1357     NULL,
1358     NULL,                       /* init */
1359     NULL,                       /* finish */
1360     0,                          /* flags */
1361     NULL                        /* app_data */
1362 };
1363
1364 static int
1365 cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
1366                      const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
1367                      BN_MONT_CTX *m_ctx)
1368 {
1369     return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx));
1370 }
1371
1372 static int
1373 cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh)
1374 {
1375     struct crypt_kop kop;
1376     int dhret = 1;
1377     int fd, keylen;
1378
1379     if ((fd = get_asym_dev_crypto()) < 0) {
1380         const DH_METHOD *meth = DH_OpenSSL();
1381
1382         return ((meth->compute_key) (key, pub_key, dh));
1383     }
1384
1385     keylen = BN_num_bits(dh->p);
1386
1387     memset(&kop, 0, sizeof kop);
1388     kop.crk_op = CRK_DH_COMPUTE_KEY;
1389
1390     /* inputs: dh->priv_key pub_key dh->p key */
1391     if (bn2crparam(dh->priv_key, &kop.crk_param[0]))
1392         goto err;
1393     if (bn2crparam(pub_key, &kop.crk_param[1]))
1394         goto err;
1395     if (bn2crparam(dh->p, &kop.crk_param[2]))
1396         goto err;
1397     kop.crk_iparams = 3;
1398
1399     kop.crk_param[3].crp_p = (caddr_t) key;
1400     kop.crk_param[3].crp_nbits = keylen * 8;
1401     kop.crk_oparams = 1;
1402
1403     if (ioctl(fd, CIOCKEY, &kop) == -1) {
1404         const DH_METHOD *meth = DH_OpenSSL();
1405
1406         dhret = (meth->compute_key) (key, pub_key, dh);
1407     }
1408  err:
1409     kop.crk_param[3].crp_p = NULL;
1410     zapparams(&kop);
1411     return (dhret);
1412 }
1413
1414 static DH_METHOD cryptodev_dh = {
1415     "cryptodev DH method",
1416     NULL,                       /* cryptodev_dh_generate_key */
1417     NULL,
1418     NULL,
1419     NULL,
1420     NULL,
1421     0,                          /* flags */
1422     NULL                        /* app_data */
1423 };
1424
1425 /*
1426  * ctrl right now is just a wrapper that doesn't do much
1427  * but I expect we'll want some options soon.
1428  */
1429 static int
1430 cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
1431 {
1432 # ifdef HAVE_SYSLOG_R
1433     struct syslog_data sd = SYSLOG_DATA_INIT;
1434 # endif
1435
1436     switch (cmd) {
1437     default:
1438 # ifdef HAVE_SYSLOG_R
1439         syslog_r(LOG_ERR, &sd, "cryptodev_ctrl: unknown command %d", cmd);
1440 # else
1441         syslog(LOG_ERR, "cryptodev_ctrl: unknown command %d", cmd);
1442 # endif
1443         break;
1444     }
1445     return (1);
1446 }
1447
1448 void ENGINE_load_cryptodev(void)
1449 {
1450     ENGINE *engine = ENGINE_new();
1451     int fd;
1452
1453     if (engine == NULL)
1454         return;
1455     if ((fd = get_dev_crypto()) < 0) {
1456         ENGINE_free(engine);
1457         return;
1458     }
1459
1460     /*
1461      * find out what asymmetric crypto algorithms we support
1462      */
1463     if (ioctl(fd, CIOCASYMFEAT, &cryptodev_asymfeat) == -1) {
1464         put_dev_crypto(fd);
1465         ENGINE_free(engine);
1466         return;
1467     }
1468     put_dev_crypto(fd);
1469
1470     if (!ENGINE_set_id(engine, "cryptodev") ||
1471         !ENGINE_set_name(engine, "BSD cryptodev engine") ||
1472         !ENGINE_set_ciphers(engine, cryptodev_engine_ciphers) ||
1473         !ENGINE_set_digests(engine, cryptodev_engine_digests) ||
1474         !ENGINE_set_ctrl_function(engine, cryptodev_ctrl) ||
1475         !ENGINE_set_cmd_defns(engine, cryptodev_defns)) {
1476         ENGINE_free(engine);
1477         return;
1478     }
1479
1480     if (ENGINE_set_RSA(engine, &cryptodev_rsa)) {
1481         const RSA_METHOD *rsa_meth = RSA_PKCS1_SSLeay();
1482
1483         cryptodev_rsa.bn_mod_exp = rsa_meth->bn_mod_exp;
1484         cryptodev_rsa.rsa_mod_exp = rsa_meth->rsa_mod_exp;
1485         cryptodev_rsa.rsa_pub_enc = rsa_meth->rsa_pub_enc;
1486         cryptodev_rsa.rsa_pub_dec = rsa_meth->rsa_pub_dec;
1487         cryptodev_rsa.rsa_priv_enc = rsa_meth->rsa_priv_enc;
1488         cryptodev_rsa.rsa_priv_dec = rsa_meth->rsa_priv_dec;
1489         if (cryptodev_asymfeat & CRF_MOD_EXP) {
1490             cryptodev_rsa.bn_mod_exp = cryptodev_bn_mod_exp;
1491             if (cryptodev_asymfeat & CRF_MOD_EXP_CRT)
1492                 cryptodev_rsa.rsa_mod_exp = cryptodev_rsa_mod_exp;
1493             else
1494                 cryptodev_rsa.rsa_mod_exp = cryptodev_rsa_nocrt_mod_exp;
1495         }
1496     }
1497
1498     if (ENGINE_set_DSA(engine, &cryptodev_dsa)) {
1499         const DSA_METHOD *meth = DSA_OpenSSL();
1500
1501         memcpy(&cryptodev_dsa, meth, sizeof(DSA_METHOD));
1502         if (cryptodev_asymfeat & CRF_DSA_SIGN)
1503             cryptodev_dsa.dsa_do_sign = cryptodev_dsa_do_sign;
1504         if (cryptodev_asymfeat & CRF_MOD_EXP) {
1505             cryptodev_dsa.bn_mod_exp = cryptodev_dsa_bn_mod_exp;
1506             cryptodev_dsa.dsa_mod_exp = cryptodev_dsa_dsa_mod_exp;
1507         }
1508         if (cryptodev_asymfeat & CRF_DSA_VERIFY)
1509             cryptodev_dsa.dsa_do_verify = cryptodev_dsa_verify;
1510     }
1511
1512     if (ENGINE_set_DH(engine, &cryptodev_dh)) {
1513         const DH_METHOD *dh_meth = DH_OpenSSL();
1514
1515         cryptodev_dh.generate_key = dh_meth->generate_key;
1516         cryptodev_dh.compute_key = dh_meth->compute_key;
1517         cryptodev_dh.bn_mod_exp = dh_meth->bn_mod_exp;
1518         if (cryptodev_asymfeat & CRF_MOD_EXP) {
1519             cryptodev_dh.bn_mod_exp = cryptodev_mod_exp_dh;
1520             if (cryptodev_asymfeat & CRF_DH_COMPUTE_KEY)
1521                 cryptodev_dh.compute_key = cryptodev_dh_compute_key;
1522         }
1523     }
1524
1525     ENGINE_add(engine);
1526     ENGINE_free(engine);
1527     ERR_clear_error();
1528 }
1529
1530 #endif                          /* HAVE_CRYPTODEV */