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