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