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