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