cryptodev_asym, zapparams: use OPENSSL_* allocation routines, handle errors
[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         OPENSSL_free(kop->crk_param[i].crp_p);
1261         kop->crk_param[i].crp_p = NULL;
1262         kop->crk_param[i].crp_nbits = 0;
1263     }
1264 }
1265
1266 static int
1267 cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r, int slen,
1268                BIGNUM *s)
1269 {
1270     int fd, ret = -1;
1271
1272     if ((fd = get_asym_dev_crypto()) < 0)
1273         return ret;
1274
1275     if (r) {
1276         kop->crk_param[kop->crk_iparams].crp_p = OPENSSL_zalloc(rlen);
1277         if (kop->crk_param[kop->crk_iparams].crp_p == NULL)
1278             return ret;
1279         kop->crk_param[kop->crk_iparams].crp_nbits = rlen * 8;
1280         kop->crk_oparams++;
1281     }
1282     if (s) {
1283         kop->crk_param[kop->crk_iparams + 1].crp_p =
1284             OPENSSL_zalloc(slen);
1285         /* No need to free the kop->crk_iparams parameter if it was allocated,
1286          * callers of this routine have to free allocated parameters through
1287          * zapparams both in case of success and failure
1288          */
1289         if (kop->crk_param[kop->crk_iparams+1].crp_p == NULL)
1290             return ret;
1291         kop->crk_param[kop->crk_iparams + 1].crp_nbits = slen * 8;
1292         kop->crk_oparams++;
1293     }
1294
1295     if (ioctl(fd, CIOCKEY, kop) == 0) {
1296         if (r)
1297             crparam2bn(&kop->crk_param[kop->crk_iparams], r);
1298         if (s)
1299             crparam2bn(&kop->crk_param[kop->crk_iparams + 1], s);
1300         ret = 0;
1301     }
1302
1303     return ret;
1304 }
1305
1306 static int
1307 cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
1308                      const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
1309 {
1310     struct crypt_kop kop;
1311     int ret = 1;
1312
1313     /*
1314      * Currently, we know we can do mod exp iff we can do any asymmetric
1315      * operations at all.
1316      */
1317     if (cryptodev_asymfeat == 0) {
1318         ret = BN_mod_exp(r, a, p, m, ctx);
1319         return (ret);
1320     }
1321
1322     memset(&kop, 0, sizeof(kop));
1323     kop.crk_op = CRK_MOD_EXP;
1324
1325     /* inputs: a^p % m */
1326     if (bn2crparam(a, &kop.crk_param[0]))
1327         goto err;
1328     if (bn2crparam(p, &kop.crk_param[1]))
1329         goto err;
1330     if (bn2crparam(m, &kop.crk_param[2]))
1331         goto err;
1332     kop.crk_iparams = 3;
1333
1334     if (cryptodev_asym(&kop, BN_num_bytes(m), r, 0, NULL)) {
1335         const RSA_METHOD *meth = RSA_PKCS1_OpenSSL();
1336         printf("OCF asym process failed, Running in software\n");
1337         ret = RSA_meth_get_bn_mod_exp(meth)(r, a, p, m, ctx, in_mont);
1338
1339     } else if (ECANCELED == kop.crk_status) {
1340         const RSA_METHOD *meth = RSA_PKCS1_OpenSSL();
1341         printf("OCF hardware operation cancelled. Running in Software\n");
1342         ret = RSA_meth_get_bn_mod_exp(meth)(r, a, p, m, ctx, in_mont);
1343     }
1344     /* else cryptodev operation worked ok ==> ret = 1 */
1345
1346  err:
1347     zapparams(&kop);
1348     return (ret);
1349 }
1350
1351 static int
1352 cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
1353                             BN_CTX *ctx)
1354 {
1355     int r;
1356     BIGNUM *n = NULL;
1357     BIGNUM *d = NULL;
1358
1359     ctx = BN_CTX_new();
1360     RSA_get0_key(rsa, &n, NULL, &d);
1361     r = cryptodev_bn_mod_exp(r0, I, d, n, ctx, NULL);
1362     BN_CTX_free(ctx);
1363     return (r);
1364 }
1365
1366 static int
1367 cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
1368 {
1369     struct crypt_kop kop;
1370     int ret = 1;
1371     BIGNUM *p = NULL;
1372     BIGNUM *q = NULL;
1373     BIGNUM *dmp1 = NULL;
1374     BIGNUM *dmq1 = NULL;
1375     BIGNUM *iqmp = NULL;
1376     BIGNUM *n = NULL;
1377
1378     RSA_get0_factors(rsa, &p, &q);
1379     RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp);
1380     RSA_get0_key(rsa, &n, NULL, NULL);
1381
1382     if (!p || !q || !dmp1 || !dmq1 || !iqmp) {
1383         /* XXX 0 means failure?? */
1384         return (0);
1385     }
1386
1387     memset(&kop, 0, sizeof(kop));
1388     kop.crk_op = CRK_MOD_EXP_CRT;
1389     /* inputs: rsa->p rsa->q I rsa->dmp1 rsa->dmq1 rsa->iqmp */
1390     if (bn2crparam(p, &kop.crk_param[0]))
1391         goto err;
1392     if (bn2crparam(q, &kop.crk_param[1]))
1393         goto err;
1394     if (bn2crparam(I, &kop.crk_param[2]))
1395         goto err;
1396     if (bn2crparam(dmp1, &kop.crk_param[3]))
1397         goto err;
1398     if (bn2crparam(dmq1, &kop.crk_param[4]))
1399         goto err;
1400     if (bn2crparam(iqmp, &kop.crk_param[5]))
1401         goto err;
1402     kop.crk_iparams = 6;
1403
1404     if (cryptodev_asym(&kop, BN_num_bytes(n), r0, 0, NULL)) {
1405         const RSA_METHOD *meth = RSA_PKCS1_OpenSSL();
1406         printf("OCF asym process failed, running in Software\n");
1407         ret = RSA_meth_get_mod_exp(meth)(r0, I, rsa, ctx);
1408
1409     } else if (ECANCELED == kop.crk_status) {
1410         const RSA_METHOD *meth = RSA_PKCS1_OpenSSL();
1411         printf("OCF hardware operation cancelled. Running in Software\n");
1412         ret = RSA_meth_get_mod_exp(meth)(r0, I, rsa, ctx);
1413     }
1414     /* else cryptodev operation worked ok ==> ret = 1 */
1415
1416  err:
1417     zapparams(&kop);
1418     return (ret);
1419 }
1420
1421 #ifndef OPENSSL_NO_DSA
1422 static int
1423 cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p,
1424                          const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
1425 {
1426     return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx));
1427 }
1428
1429 static int
1430 cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g,
1431                           BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2, BIGNUM *p,
1432                           BN_CTX *ctx, BN_MONT_CTX *mont)
1433 {
1434     BIGNUM *t2, *dsag, *dsap, *dsapub_key;
1435     int ret = 0;
1436     const DSA_METHOD *meth;
1437     int (*bn_mod_exp)(DSA *, BIGNUM *, BIGNUM *, const BIGNUM *, const BIGNUM *,
1438                       BN_CTX *, BN_MONT_CTX *);
1439
1440     t2 = BN_new();
1441     if (t2 == NULL)
1442         goto err;
1443
1444     /* v = ( g^u1 * y^u2 mod p ) mod q */
1445     /* let t1 = g ^ u1 mod p */
1446     ret = 0;
1447
1448     DSA_get0_pqg(dsa, &dsap, NULL, &dsag);
1449     DSA_get0_key(dsa, &dsapub_key, NULL);
1450
1451     meth = DSA_get_method(dsa);
1452     if (meth == NULL)
1453         goto err;
1454     bn_mod_exp = DSA_meth_get_bn_mod_exp(meth);
1455     if (bn_mod_exp == NULL)
1456         goto err;
1457
1458     if (!bn_mod_exp(dsa, t1, dsag, u1, dsap, ctx, mont))
1459         goto err;
1460
1461     /* let t2 = y ^ u2 mod p */
1462     if (!bn_mod_exp(dsa, t2, dsapub_key, u2, dsap, ctx, mont))
1463         goto err;
1464     /* let u1 = t1 * t2 mod p */
1465     if (!BN_mod_mul(u1, t1, t2, dsap, ctx))
1466         goto err;
1467
1468     BN_copy(t1, u1);
1469
1470     ret = 1;
1471  err:
1472     BN_free(t2);
1473     return (ret);
1474 }
1475
1476 static DSA_SIG *cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen,
1477                                       DSA *dsa)
1478 {
1479     struct crypt_kop kop;
1480     BIGNUM *r = NULL, *s = NULL, *dsap = NULL, *dsaq = NULL, *dsag = NULL;
1481     BIGNUM *priv_key = NULL;
1482     DSA_SIG *dsasig, *dsaret = NULL;
1483
1484     dsasig = DSA_SIG_new();
1485     if (dsasig == NULL)
1486         goto err;
1487     DSA_SIG_get0(&r, &s, dsasig);
1488
1489     memset(&kop, 0, sizeof(kop));
1490     kop.crk_op = CRK_DSA_SIGN;
1491
1492     /* inputs: dgst dsa->p dsa->q dsa->g dsa->priv_key */
1493     kop.crk_param[0].crp_p = (caddr_t) dgst;
1494     kop.crk_param[0].crp_nbits = dlen * 8;
1495     DSA_get0_pqg(dsa, &dsap, &dsaq, &dsag);
1496     DSA_get0_key(dsa, NULL, &priv_key);
1497     if (bn2crparam(dsap, &kop.crk_param[1]))
1498         goto err;
1499     if (bn2crparam(dsaq, &kop.crk_param[2]))
1500         goto err;
1501     if (bn2crparam(dsag, &kop.crk_param[3]))
1502         goto err;
1503     if (bn2crparam(priv_key, &kop.crk_param[4]))
1504         goto err;
1505     kop.crk_iparams = 5;
1506
1507     if (cryptodev_asym(&kop, BN_num_bytes(dsaq), r,
1508                        BN_num_bytes(dsaq), s) == 0) {
1509         dsaret = dsasig;
1510     } else {
1511         dsaret = DSA_meth_get_sign(DSA_OpenSSL())(dgst, dlen, dsa);
1512     }
1513  err:
1514     if (dsaret != dsasig)
1515         DSA_SIG_free(dsasig);
1516     kop.crk_param[0].crp_p = NULL;
1517     zapparams(&kop);
1518     return dsaret;
1519 }
1520
1521 static int
1522 cryptodev_dsa_verify(const unsigned char *dgst, int dlen,
1523                      DSA_SIG *sig, DSA *dsa)
1524 {
1525     struct crypt_kop kop;
1526     int dsaret = 1;
1527     BIGNUM *pr, *ps, *p = NULL, *q = NULL, *g = NULL, *pub_key = NULL;
1528
1529     memset(&kop, 0, sizeof(kop));
1530     kop.crk_op = CRK_DSA_VERIFY;
1531
1532     /* inputs: dgst dsa->p dsa->q dsa->g dsa->pub_key sig->r sig->s */
1533     kop.crk_param[0].crp_p = (caddr_t) dgst;
1534     kop.crk_param[0].crp_nbits = dlen * 8;
1535     DSA_get0_pqg(dsa, &p, &q, &g);
1536     if (bn2crparam(p, &kop.crk_param[1]))
1537         goto err;
1538     if (bn2crparam(q, &kop.crk_param[2]))
1539         goto err;
1540     if (bn2crparam(g, &kop.crk_param[3]))
1541         goto err;
1542     DSA_get0_key(dsa, &pub_key, NULL);
1543     if (bn2crparam(pub_key, &kop.crk_param[4]))
1544         goto err;
1545     DSA_SIG_get0(&pr, &ps, sig);
1546     if (bn2crparam(pr, &kop.crk_param[5]))
1547         goto err;
1548     if (bn2crparam(ps, &kop.crk_param[6]))
1549         goto err;
1550     kop.crk_iparams = 7;
1551
1552     if (cryptodev_asym(&kop, 0, NULL, 0, NULL) == 0) {
1553         /*
1554          * OCF success value is 0, if not zero, change dsaret to fail
1555          */
1556         if (0 != kop.crk_status)
1557             dsaret = 0;
1558     } else {
1559         dsaret = DSA_meth_get_verify(DSA_OpenSSL())(dgst, dlen, sig, dsa);
1560     }
1561  err:
1562     kop.crk_param[0].crp_p = NULL;
1563     zapparams(&kop);
1564     return (dsaret);
1565 }
1566 #endif
1567
1568 #ifndef OPENSSL_NO_DH
1569 static int
1570 cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
1571                      const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
1572                      BN_MONT_CTX *m_ctx)
1573 {
1574     return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx));
1575 }
1576
1577 static int
1578 cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh)
1579 {
1580     struct crypt_kop kop;
1581     int dhret = 1;
1582     int fd, keylen;
1583     BIGNUM *p = NULL;
1584     BIGNUM *priv_key = NULL;
1585
1586     if ((fd = get_asym_dev_crypto()) < 0) {
1587         const DH_METHOD *meth = DH_OpenSSL();
1588
1589         return DH_meth_get_compute_key(meth)(key, pub_key, dh);
1590     }
1591
1592     DH_get0_pqg(dh, &p, NULL, NULL);
1593     DH_get0_key(dh, NULL, &priv_key);
1594
1595     keylen = BN_num_bits(p);
1596
1597     memset(&kop, 0, sizeof(kop));
1598     kop.crk_op = CRK_DH_COMPUTE_KEY;
1599
1600     /* inputs: dh->priv_key pub_key dh->p key */
1601     if (bn2crparam(priv_key, &kop.crk_param[0]))
1602         goto err;
1603     if (bn2crparam(pub_key, &kop.crk_param[1]))
1604         goto err;
1605     if (bn2crparam(p, &kop.crk_param[2]))
1606         goto err;
1607     kop.crk_iparams = 3;
1608
1609     kop.crk_param[3].crp_p = (caddr_t) key;
1610     kop.crk_param[3].crp_nbits = keylen * 8;
1611     kop.crk_oparams = 1;
1612
1613     if (ioctl(fd, CIOCKEY, &kop) == -1) {
1614         const DH_METHOD *meth = DH_OpenSSL();
1615
1616         dhret = DH_meth_get_compute_key(meth)(key, pub_key, dh);
1617     }
1618  err:
1619     kop.crk_param[3].crp_p = NULL;
1620     zapparams(&kop);
1621     return (dhret);
1622 }
1623
1624 #endif /* ndef OPENSSL_NO_DH */
1625
1626 /*
1627  * ctrl right now is just a wrapper that doesn't do much
1628  * but I expect we'll want some options soon.
1629  */
1630 static int
1631 cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
1632 {
1633 # ifdef HAVE_SYSLOG_R
1634     struct syslog_data sd = SYSLOG_DATA_INIT;
1635 # endif
1636
1637     switch (cmd) {
1638     default:
1639 # ifdef HAVE_SYSLOG_R
1640         syslog_r(LOG_ERR, &sd, "cryptodev_ctrl: unknown command %d", cmd);
1641 # else
1642         syslog(LOG_ERR, "cryptodev_ctrl: unknown command %d", cmd);
1643 # endif
1644         break;
1645     }
1646     return (1);
1647 }
1648
1649 void engine_load_cryptodev_int(void)
1650 {
1651     ENGINE *engine = ENGINE_new();
1652     int fd;
1653
1654     if (engine == NULL)
1655         return;
1656     if ((fd = get_dev_crypto()) < 0) {
1657         ENGINE_free(engine);
1658         return;
1659     }
1660
1661     /*
1662      * find out what asymmetric crypto algorithms we support
1663      */
1664     if (ioctl(fd, CIOCASYMFEAT, &cryptodev_asymfeat) == -1) {
1665         put_dev_crypto(fd);
1666         ENGINE_free(engine);
1667         return;
1668     }
1669     put_dev_crypto(fd);
1670
1671     if (!ENGINE_set_id(engine, "cryptodev") ||
1672         !ENGINE_set_name(engine, "BSD cryptodev engine") ||
1673         !ENGINE_set_destroy_function(engine, cryptodev_engine_destroy) ||
1674         !ENGINE_set_ciphers(engine, cryptodev_engine_ciphers) ||
1675         !ENGINE_set_digests(engine, cryptodev_engine_digests) ||
1676         !ENGINE_set_ctrl_function(engine, cryptodev_ctrl) ||
1677         !ENGINE_set_cmd_defns(engine, cryptodev_defns)) {
1678         ENGINE_free(engine);
1679         return;
1680     }
1681
1682     cryptodev_rsa = RSA_meth_dup(RSA_PKCS1_OpenSSL());
1683     if (cryptodev_rsa != NULL) {
1684         RSA_meth_set1_name(cryptodev_rsa, "cryptodev RSA method");
1685         RSA_meth_set_flags(cryptodev_rsa, 0);
1686         if (ENGINE_set_RSA(engine, cryptodev_rsa)) {
1687             if (cryptodev_asymfeat & CRF_MOD_EXP) {
1688                 RSA_meth_set_bn_mod_exp(cryptodev_rsa, cryptodev_bn_mod_exp);
1689                 if (cryptodev_asymfeat & CRF_MOD_EXP_CRT)
1690                     RSA_meth_set_mod_exp(cryptodev_rsa, cryptodev_rsa_mod_exp);
1691                 else
1692                     RSA_meth_set_mod_exp(cryptodev_rsa,
1693                                          cryptodev_rsa_nocrt_mod_exp);
1694             }
1695         }
1696     } else {
1697         ENGINE_free(engine);
1698         return;
1699     }
1700
1701 #ifndef OPENSSL_NO_DSA
1702     cryptodev_dsa = DSA_meth_dup(DSA_OpenSSL());
1703     if (cryptodev_dsa != NULL) {
1704         DSA_meth_set1_name(cryptodev_dsa, "cryptodev DSA method");
1705         DSA_meth_set_flags(cryptodev_dsa, 0);
1706         if (ENGINE_set_DSA(engine, cryptodev_dsa)) {
1707             if (cryptodev_asymfeat & CRF_DSA_SIGN)
1708                 DSA_meth_set_sign(cryptodev_dsa, cryptodev_dsa_do_sign);
1709             if (cryptodev_asymfeat & CRF_MOD_EXP) {
1710                 DSA_meth_set_bn_mod_exp(cryptodev_dsa,
1711                                         cryptodev_dsa_bn_mod_exp);
1712                 DSA_meth_set_mod_exp(cryptodev_dsa, cryptodev_dsa_dsa_mod_exp);
1713             }
1714             if (cryptodev_asymfeat & CRF_DSA_VERIFY)
1715                 DSA_meth_set_verify(cryptodev_dsa, cryptodev_dsa_verify);
1716         }
1717     } else {
1718         ENGINE_free(engine);
1719         return;
1720     }
1721 #endif
1722
1723 #ifndef OPENSSL_NO_DH
1724     cryptodev_dh = DH_meth_dup(DH_OpenSSL());
1725     if (cryptodev_dh != NULL) {
1726         DH_meth_set1_name(cryptodev_dh, "cryptodev DH method");
1727         DH_meth_set_flags(cryptodev_dh, 0);
1728         if (ENGINE_set_DH(engine, cryptodev_dh)) {
1729             if (cryptodev_asymfeat & CRF_MOD_EXP) {
1730                 DH_meth_set_bn_mod_exp(cryptodev_dh, cryptodev_mod_exp_dh);
1731                 if (cryptodev_asymfeat & CRF_DH_COMPUTE_KEY)
1732                     DH_meth_set_compute_key(cryptodev_dh,
1733                                             cryptodev_dh_compute_key);
1734             }
1735         }
1736     } else {
1737         ENGINE_free(engine);
1738         return;
1739     }
1740 #endif
1741
1742     ENGINE_add(engine);
1743     ENGINE_free(engine);
1744     ERR_clear_error();
1745 }
1746
1747 #endif                          /* HAVE_CRYPTODEV */