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