]> CyberLeo.Net >> Repos - FreeBSD/releng/9.3.git/blob - crypto/openssl/crypto/engine/eng_cryptodev.c
Fix multiple OpenSSL vulnerabilities.
[FreeBSD/releng/9.3.git] / crypto / openssl / crypto / engine / eng_cryptodev.c
1 /*
2  * Copyright (c) 2002 Bob Beck <beck@openbsd.org>
3  * Copyright (c) 2002 Theo de Raadt
4  * Copyright (c) 2002 Markus Friedl
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
20  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  *
27  */
28
29 #include <openssl/objects.h>
30 #include <openssl/engine.h>
31 #include <openssl/evp.h>
32 #include <openssl/bn.h>
33 #include <openssl/dsa.h>
34 #include <openssl/rsa.h>
35 #include <openssl/dh.h>
36 #include <openssl/err.h>
37
38 #if (defined(__unix__) || defined(unix)) && !defined(USG) && \
39         (defined(OpenBSD) || defined(__FreeBSD__))
40 # include <sys/param.h>
41 # if (OpenBSD >= 200112) || ((__FreeBSD_version >= 470101 && __FreeBSD_version < 500000) || __FreeBSD_version >= 500041)
42 #  define HAVE_CRYPTODEV
43 # endif
44 # if (OpenBSD >= 200110)
45 #  define HAVE_SYSLOG_R
46 # endif
47 #endif
48
49 #ifndef HAVE_CRYPTODEV
50
51 void ENGINE_load_cryptodev(void)
52 {
53     /* This is a NOP on platforms without /dev/crypto */
54     return;
55 }
56
57 #else
58
59 # include <sys/types.h>
60 # include <crypto/cryptodev.h>
61 # include <sys/ioctl.h>
62 # include <errno.h>
63 # include <stdio.h>
64 # include <unistd.h>
65 # include <fcntl.h>
66 # include <stdarg.h>
67 # include <syslog.h>
68 # include <errno.h>
69 # include <string.h>
70
71 struct dev_crypto_state {
72     struct session_op d_sess;
73     int d_fd;
74 };
75
76 static u_int32_t cryptodev_asymfeat = 0;
77
78 static int get_asym_dev_crypto(void);
79 static int open_dev_crypto(void);
80 static int get_dev_crypto(void);
81 static int cryptodev_max_iv(int cipher);
82 static int cryptodev_key_length_valid(int cipher, int len);
83 static int cipher_nid_to_cryptodev(int nid);
84 static int get_cryptodev_ciphers(const int **cnids);
85 /*
86  * static int get_cryptodev_digests(const int **cnids);
87  */
88 static int cryptodev_usable_ciphers(const int **nids);
89 static int cryptodev_usable_digests(const int **nids);
90 static int cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
91                             const unsigned char *in, unsigned int inl);
92 static int cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
93                               const unsigned char *iv, int enc);
94 static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx);
95 static int cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
96                                     const int **nids, int nid);
97 static int cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest,
98                                     const int **nids, int nid);
99 static int bn2crparam(const BIGNUM *a, struct crparam *crp);
100 static int crparam2bn(struct crparam *crp, BIGNUM *a);
101 static void zapparams(struct crypt_kop *kop);
102 static int cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r,
103                           int slen, BIGNUM *s);
104
105 static int cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a,
106                                 const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
107                                 BN_MONT_CTX *m_ctx);
108 static int cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
109                                        BN_CTX *ctx);
110 static int cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
111                                  BN_CTX *ctx);
112 static int cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a,
113                                     const BIGNUM *p, const BIGNUM *m,
114                                     BN_CTX *ctx, BN_MONT_CTX *m_ctx);
115 static int cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g,
116                                      BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2,
117                                      BIGNUM *p, BN_CTX *ctx,
118                                      BN_MONT_CTX *mont);
119 static DSA_SIG *cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen,
120                                       DSA *dsa);
121 static int cryptodev_dsa_verify(const unsigned char *dgst, int dgst_len,
122                                 DSA_SIG *sig, DSA *dsa);
123 static int cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
124                                 const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
125                                 BN_MONT_CTX *m_ctx);
126 static int cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key,
127                                     DH *dh);
128 static int cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) ());
129 void ENGINE_load_cryptodev(void);
130
131 static const ENGINE_CMD_DEFN cryptodev_defns[] = {
132     {0, NULL, NULL, 0}
133 };
134
135 static struct {
136     int id;
137     int nid;
138     int ivmax;
139     int keylen;
140 } ciphers[] = {
141     {
142         CRYPTO_DES_CBC, NID_des_cbc, 8, 8,
143     },
144     {
145         CRYPTO_3DES_CBC, NID_des_ede3_cbc, 8, 24,
146     },
147     {
148         CRYPTO_AES_CBC, NID_aes_128_cbc, 16, 16,
149     },
150     {
151         CRYPTO_BLF_CBC, NID_bf_cbc, 8, 16,
152     },
153     {
154         CRYPTO_CAST_CBC, NID_cast5_cbc, 8, 16,
155     },
156     {
157         CRYPTO_SKIPJACK_CBC, NID_undef, 0, 0,
158     },
159     {
160         0, NID_undef, 0, 0,
161     },
162 };
163
164 # if 0
165 static struct {
166     int id;
167     int nid;
168 } digests[] = {
169     {
170         CRYPTO_SHA1_HMAC, NID_hmacWithSHA1,
171     },
172     {
173         CRYPTO_RIPEMD160_HMAC, NID_ripemd160,
174     },
175     {
176         CRYPTO_MD5_KPDK, NID_undef,
177     },
178     {
179         CRYPTO_SHA1_KPDK, NID_undef,
180     },
181     {
182         CRYPTO_MD5, NID_md5,
183     },
184     {
185         CRYPTO_SHA1, NID_undef,
186     },
187     {
188         0, NID_undef,
189     },
190 };
191 # endif
192
193 /*
194  * Return a fd if /dev/crypto seems usable, 0 otherwise.
195  */
196 static int open_dev_crypto(void)
197 {
198     static int fd = -1;
199
200     if (fd == -1) {
201         if ((fd = open("/dev/crypto", O_RDWR, 0)) == -1)
202             return (-1);
203         /* close on exec */
204         if (fcntl(fd, F_SETFD, 1) == -1) {
205             close(fd);
206             fd = -1;
207             return (-1);
208         }
209     }
210     return (fd);
211 }
212
213 static int get_dev_crypto(void)
214 {
215     int fd, retfd;
216
217     if ((fd = open_dev_crypto()) == -1)
218         return (-1);
219     if (ioctl(fd, CRIOGET, &retfd) == -1)
220         return (-1);
221
222     /* close on exec */
223     if (fcntl(retfd, F_SETFD, 1) == -1) {
224         close(retfd);
225         return (-1);
226     }
227     return (retfd);
228 }
229
230 /* Caching version for asym operations */
231 static int get_asym_dev_crypto(void)
232 {
233     static int fd = -1;
234
235     if (fd == -1)
236         fd = get_dev_crypto();
237     return fd;
238 }
239
240 /*
241  * XXXX this needs to be set for each alg - and determined from
242  * a running card.
243  */
244 static int cryptodev_max_iv(int cipher)
245 {
246     int i;
247
248     for (i = 0; ciphers[i].id; i++)
249         if (ciphers[i].id == cipher)
250             return (ciphers[i].ivmax);
251     return (0);
252 }
253
254 /*
255  * XXXX this needs to be set for each alg - and determined from
256  * a running card. For now, fake it out - but most of these
257  * for real devices should return 1 for the supported key
258  * sizes the device can handle.
259  */
260 static int cryptodev_key_length_valid(int cipher, int len)
261 {
262     int i;
263
264     for (i = 0; ciphers[i].id; i++)
265         if (ciphers[i].id == cipher)
266             return (ciphers[i].keylen == len);
267     return (0);
268 }
269
270 /* convert libcrypto nids to cryptodev */
271 static int cipher_nid_to_cryptodev(int nid)
272 {
273     int i;
274
275     for (i = 0; ciphers[i].id; i++)
276         if (ciphers[i].nid == nid)
277             return (ciphers[i].id);
278     return (0);
279 }
280
281 /*
282  * Find out what ciphers /dev/crypto will let us have a session for.
283  * XXX note, that some of these openssl doesn't deal with yet!
284  * returning them here is harmless, as long as we return NULL
285  * when asked for a handler in the cryptodev_engine_ciphers routine
286  */
287 static int get_cryptodev_ciphers(const int **cnids)
288 {
289     static int nids[CRYPTO_ALGORITHM_MAX];
290     struct session_op sess;
291     int fd, i, count = 0;
292
293     if ((fd = get_dev_crypto()) < 0) {
294         *cnids = NULL;
295         return (0);
296     }
297     memset(&sess, 0, sizeof(sess));
298     sess.key = (caddr_t) "123456781234567812345678";
299
300     for (i = 0; ciphers[i].id && count < CRYPTO_ALGORITHM_MAX; i++) {
301         if (ciphers[i].nid == NID_undef)
302             continue;
303         sess.cipher = ciphers[i].id;
304         sess.keylen = ciphers[i].keylen;
305         sess.mac = 0;
306         if (ioctl(fd, CIOCGSESSION, &sess) != -1 &&
307             ioctl(fd, CIOCFSESSION, &sess.ses) != -1)
308             nids[count++] = ciphers[i].nid;
309     }
310     close(fd);
311
312     if (count > 0)
313         *cnids = nids;
314     else
315         *cnids = NULL;
316     return (count);
317 }
318
319 # if 0                          /* unused */
320 /*
321  * Find out what digests /dev/crypto will let us have a session for.
322  * XXX note, that some of these openssl doesn't deal with yet!
323  * returning them here is harmless, as long as we return NULL
324  * when asked for a handler in the cryptodev_engine_digests routine
325  */
326 static int get_cryptodev_digests(const int **cnids)
327 {
328     static int nids[CRYPTO_ALGORITHM_MAX];
329     struct session_op sess;
330     int fd, i, count = 0;
331
332     if ((fd = get_dev_crypto()) < 0) {
333         *cnids = NULL;
334         return (0);
335     }
336     memset(&sess, 0, sizeof(sess));
337     for (i = 0; digests[i].id && count < CRYPTO_ALGORITHM_MAX; i++) {
338         if (digests[i].nid == NID_undef)
339             continue;
340         sess.mac = digests[i].id;
341         sess.cipher = 0;
342         if (ioctl(fd, CIOCGSESSION, &sess) != -1 &&
343             ioctl(fd, CIOCFSESSION, &sess.ses) != -1)
344             nids[count++] = digests[i].nid;
345     }
346     close(fd);
347
348     if (count > 0)
349         *cnids = nids;
350     else
351         *cnids = NULL;
352     return (count);
353 }
354
355 # endif
356
357 /*
358  * Find the useable ciphers|digests from dev/crypto - this is the first
359  * thing called by the engine init crud which determines what it
360  * can use for ciphers from this engine. We want to return
361  * only what we can do, anythine else is handled by software.
362  *
363  * If we can't initialize the device to do anything useful for
364  * any reason, we want to return a NULL array, and 0 length,
365  * which forces everything to be done is software. By putting
366  * the initalization of the device in here, we ensure we can
367  * use this engine as the default, and if for whatever reason
368  * /dev/crypto won't do what we want it will just be done in
369  * software
370  *
371  * This can (should) be greatly expanded to perhaps take into
372  * account speed of the device, and what we want to do.
373  * (although the disabling of particular alg's could be controlled
374  * by the device driver with sysctl's.) - this is where we
375  * want most of the decisions made about what we actually want
376  * to use from /dev/crypto.
377  */
378 static int cryptodev_usable_ciphers(const int **nids)
379 {
380     return (get_cryptodev_ciphers(nids));
381 }
382
383 static int cryptodev_usable_digests(const int **nids)
384 {
385     /*
386      * XXXX just disable all digests for now, because it sucks.
387      * we need a better way to decide this - i.e. I may not
388      * want digests on slow cards like hifn on fast machines,
389      * but might want them on slow or loaded machines, etc.
390      * will also want them when using crypto cards that don't
391      * suck moose gonads - would be nice to be able to decide something
392      * as reasonable default without having hackery that's card dependent.
393      * of course, the default should probably be just do everything,
394      * with perhaps a sysctl to turn algoritms off (or have them off
395      * by default) on cards that generally suck like the hifn.
396      */
397     *nids = NULL;
398     return (0);
399 }
400
401 static int
402 cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
403                  const unsigned char *in, unsigned int inl)
404 {
405     struct crypt_op cryp;
406     struct dev_crypto_state *state = ctx->cipher_data;
407     struct session_op *sess = &state->d_sess;
408     const void *iiv;
409     unsigned char save_iv[EVP_MAX_IV_LENGTH];
410
411     if (state->d_fd < 0)
412         return (0);
413     if (!inl)
414         return (1);
415     if ((inl % ctx->cipher->block_size) != 0)
416         return (0);
417
418     memset(&cryp, 0, sizeof(cryp));
419
420     cryp.ses = sess->ses;
421     cryp.flags = 0;
422     cryp.len = inl;
423     cryp.src = (caddr_t) in;
424     cryp.dst = (caddr_t) out;
425     cryp.mac = 0;
426
427     cryp.op = ctx->encrypt ? COP_ENCRYPT : COP_DECRYPT;
428
429     if (ctx->cipher->iv_len) {
430         cryp.iv = (caddr_t) ctx->iv;
431         if (!ctx->encrypt) {
432             iiv = in + inl - ctx->cipher->iv_len;
433             memcpy(save_iv, iiv, ctx->cipher->iv_len);
434         }
435     } else
436         cryp.iv = NULL;
437
438     if (ioctl(state->d_fd, CIOCCRYPT, &cryp) == -1) {
439         /*
440          * XXX need better errror handling this can fail for a number of
441          * different reasons.
442          */
443         return (0);
444     }
445
446     if (ctx->cipher->iv_len) {
447         if (ctx->encrypt)
448             iiv = out + inl - ctx->cipher->iv_len;
449         else
450             iiv = save_iv;
451         memcpy(ctx->iv, iiv, ctx->cipher->iv_len);
452     }
453     return (1);
454 }
455
456 static int
457 cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
458                    const unsigned char *iv, int enc)
459 {
460     struct dev_crypto_state *state = ctx->cipher_data;
461     struct session_op *sess = &state->d_sess;
462     int cipher;
463
464     if ((cipher = cipher_nid_to_cryptodev(ctx->cipher->nid)) == NID_undef)
465         return (0);
466
467     if (ctx->cipher->iv_len > cryptodev_max_iv(cipher))
468         return (0);
469
470     if (!cryptodev_key_length_valid(cipher, ctx->key_len))
471         return (0);
472
473     memset(sess, 0, sizeof(struct session_op));
474
475     if ((state->d_fd = get_dev_crypto()) < 0)
476         return (0);
477
478     sess->key = (char *)key;
479     sess->keylen = ctx->key_len;
480     sess->cipher = cipher;
481
482     if (ioctl(state->d_fd, CIOCGSESSION, sess) == -1) {
483         close(state->d_fd);
484         state->d_fd = -1;
485         return (0);
486     }
487     return (1);
488 }
489
490 /*
491  * free anything we allocated earlier when initting a
492  * session, and close the session.
493  */
494 static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx)
495 {
496     int ret = 0;
497     struct dev_crypto_state *state = ctx->cipher_data;
498     struct session_op *sess = &state->d_sess;
499
500     if (state->d_fd < 0)
501         return (0);
502
503     /*
504      * XXX if this ioctl fails, someting's wrong. the invoker may have called
505      * us with a bogus ctx, or we could have a device that for whatever
506      * reason just doesn't want to play ball - it's not clear what's right
507      * here - should this be an error? should it just increase a counter,
508      * hmm. For right now, we return 0 - I don't believe that to be "right".
509      * we could call the gorpy openssl lib error handlers that print messages
510      * to users of the library. hmm..
511      */
512
513     if (ioctl(state->d_fd, CIOCFSESSION, &sess->ses) == -1) {
514         ret = 0;
515     } else {
516         ret = 1;
517     }
518     close(state->d_fd);
519     state->d_fd = -1;
520
521     return (ret);
522 }
523
524 /*
525  * libcrypto EVP stuff - this is how we get wired to EVP so the engine
526  * gets called when libcrypto requests a cipher NID.
527  */
528
529 /* DES CBC EVP */
530 const EVP_CIPHER cryptodev_des_cbc = {
531     NID_des_cbc,
532     8, 8, 8,
533     EVP_CIPH_CBC_MODE,
534     cryptodev_init_key,
535     cryptodev_cipher,
536     cryptodev_cleanup,
537     sizeof(struct dev_crypto_state),
538     EVP_CIPHER_set_asn1_iv,
539     EVP_CIPHER_get_asn1_iv,
540     NULL
541 };
542
543 /* 3DES CBC EVP */
544 const EVP_CIPHER cryptodev_3des_cbc = {
545     NID_des_ede3_cbc,
546     8, 24, 8,
547     EVP_CIPH_CBC_MODE,
548     cryptodev_init_key,
549     cryptodev_cipher,
550     cryptodev_cleanup,
551     sizeof(struct dev_crypto_state),
552     EVP_CIPHER_set_asn1_iv,
553     EVP_CIPHER_get_asn1_iv,
554     NULL
555 };
556
557 const EVP_CIPHER cryptodev_bf_cbc = {
558     NID_bf_cbc,
559     8, 16, 8,
560     EVP_CIPH_CBC_MODE,
561     cryptodev_init_key,
562     cryptodev_cipher,
563     cryptodev_cleanup,
564     sizeof(struct dev_crypto_state),
565     EVP_CIPHER_set_asn1_iv,
566     EVP_CIPHER_get_asn1_iv,
567     NULL
568 };
569
570 const EVP_CIPHER cryptodev_cast_cbc = {
571     NID_cast5_cbc,
572     8, 16, 8,
573     EVP_CIPH_CBC_MODE,
574     cryptodev_init_key,
575     cryptodev_cipher,
576     cryptodev_cleanup,
577     sizeof(struct dev_crypto_state),
578     EVP_CIPHER_set_asn1_iv,
579     EVP_CIPHER_get_asn1_iv,
580     NULL
581 };
582
583 const EVP_CIPHER cryptodev_aes_cbc = {
584     NID_aes_128_cbc,
585     16, 16, 16,
586     EVP_CIPH_CBC_MODE,
587     cryptodev_init_key,
588     cryptodev_cipher,
589     cryptodev_cleanup,
590     sizeof(struct dev_crypto_state),
591     EVP_CIPHER_set_asn1_iv,
592     EVP_CIPHER_get_asn1_iv,
593     NULL
594 };
595
596 /*
597  * Registered by the ENGINE when used to find out how to deal with
598  * a particular NID in the ENGINE. this says what we'll do at the
599  * top level - note, that list is restricted by what we answer with
600  */
601 static int
602 cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
603                          const int **nids, int nid)
604 {
605     if (!cipher)
606         return (cryptodev_usable_ciphers(nids));
607
608     switch (nid) {
609     case NID_des_ede3_cbc:
610         *cipher = &cryptodev_3des_cbc;
611         break;
612     case NID_des_cbc:
613         *cipher = &cryptodev_des_cbc;
614         break;
615     case NID_bf_cbc:
616         *cipher = &cryptodev_bf_cbc;
617         break;
618     case NID_cast5_cbc:
619         *cipher = &cryptodev_cast_cbc;
620         break;
621     case NID_aes_128_cbc:
622         *cipher = &cryptodev_aes_cbc;
623         break;
624     default:
625         *cipher = NULL;
626         break;
627     }
628     return (*cipher != NULL);
629 }
630
631 static int
632 cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest,
633                          const int **nids, int nid)
634 {
635     if (!digest)
636         return (cryptodev_usable_digests(nids));
637
638     switch (nid) {
639     case NID_md5:
640         *digest = NULL;         /* need to make a clean md5 critter */
641         break;
642     default:
643         *digest = NULL;
644         break;
645     }
646     return (*digest != NULL);
647 }
648
649 /*
650  * Convert a BIGNUM to the representation that /dev/crypto needs.
651  * Upon completion of use, the caller is responsible for freeing
652  * crp->crp_p.
653  */
654 static int bn2crparam(const BIGNUM *a, struct crparam *crp)
655 {
656     int i, j, k;
657     ssize_t bytes, bits;
658     u_char *b;
659
660     crp->crp_p = NULL;
661     crp->crp_nbits = 0;
662
663     bits = BN_num_bits(a);
664     bytes = (bits + 7) / 8;
665
666     b = malloc(bytes);
667     if (b == NULL)
668         return (1);
669
670     crp->crp_p = (char *)b;
671     crp->crp_nbits = bits;
672
673     for (i = 0, j = 0; i < a->top; i++) {
674         for (k = 0; k < BN_BITS2 / 8; k++) {
675             if ((j + k) >= bytes)
676                 return (0);
677             b[j + k] = a->d[i] >> (k * 8);
678         }
679         j += BN_BITS2 / 8;
680     }
681     return (0);
682 }
683
684 /* Convert a /dev/crypto parameter to a BIGNUM */
685 static int crparam2bn(struct crparam *crp, BIGNUM *a)
686 {
687     u_int8_t *pd;
688     int i, bytes;
689
690     bytes = (crp->crp_nbits + 7) / 8;
691
692     if (bytes == 0)
693         return (-1);
694
695     if ((pd = (u_int8_t *) malloc(bytes)) == NULL)
696         return (-1);
697
698     for (i = 0; i < bytes; i++)
699         pd[i] = crp->crp_p[bytes - i - 1];
700
701     BN_bin2bn(pd, bytes, a);
702     free(pd);
703
704     return (0);
705 }
706
707 static void zapparams(struct crypt_kop *kop)
708 {
709     int i;
710
711     for (i = 0; i <= kop->crk_iparams + kop->crk_oparams; i++) {
712         if (kop->crk_param[i].crp_p)
713             free(kop->crk_param[i].crp_p);
714         kop->crk_param[i].crp_p = NULL;
715         kop->crk_param[i].crp_nbits = 0;
716     }
717 }
718
719 static int
720 cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r, int slen,
721                BIGNUM *s)
722 {
723     int fd, ret = -1;
724
725     if ((fd = get_asym_dev_crypto()) < 0)
726         return (ret);
727
728     if (r) {
729         kop->crk_param[kop->crk_iparams].crp_p = calloc(rlen, sizeof(char));
730         kop->crk_param[kop->crk_iparams].crp_nbits = rlen * 8;
731         kop->crk_oparams++;
732     }
733     if (s) {
734         kop->crk_param[kop->crk_iparams + 1].crp_p =
735             calloc(slen, sizeof(char));
736         kop->crk_param[kop->crk_iparams + 1].crp_nbits = slen * 8;
737         kop->crk_oparams++;
738     }
739
740     if (ioctl(fd, CIOCKEY, kop) == 0) {
741         if (r)
742             crparam2bn(&kop->crk_param[kop->crk_iparams], r);
743         if (s)
744             crparam2bn(&kop->crk_param[kop->crk_iparams + 1], s);
745         ret = 0;
746     }
747
748     return (ret);
749 }
750
751 static int
752 cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
753                      const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
754 {
755     struct crypt_kop kop;
756     int ret = 1;
757
758     /*
759      * Currently, we know we can do mod exp iff we can do any asymmetric
760      * operations at all.
761      */
762     if (cryptodev_asymfeat == 0) {
763         ret = BN_mod_exp(r, a, p, m, ctx);
764         return (ret);
765     }
766
767     memset(&kop, 0, sizeof kop);
768     kop.crk_op = CRK_MOD_EXP;
769
770     /* inputs: a^p % m */
771     if (bn2crparam(a, &kop.crk_param[0]))
772         goto err;
773     if (bn2crparam(p, &kop.crk_param[1]))
774         goto err;
775     if (bn2crparam(m, &kop.crk_param[2]))
776         goto err;
777     kop.crk_iparams = 3;
778
779     if (cryptodev_asym(&kop, BN_num_bytes(m), r, 0, NULL)) {
780         const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
781         printf("OCF asym process failed, Running in software\n");
782         ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont);
783
784     } else if (ECANCELED == kop.crk_status) {
785         const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
786         printf("OCF hardware operation cancelled. Running in Software\n");
787         ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont);
788     }
789     /* else cryptodev operation worked ok ==> ret = 1 */
790
791  err:
792     zapparams(&kop);
793     return (ret);
794 }
795
796 static int
797 cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
798                             BN_CTX *ctx)
799 {
800     int r;
801
802     r = cryptodev_bn_mod_exp(r0, I, rsa->d, rsa->n, ctx, NULL);
803     return (r);
804 }
805
806 static int
807 cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
808 {
809     struct crypt_kop kop;
810     int ret = 1;
811
812     if (!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) {
813         /* XXX 0 means failure?? */
814         return (0);
815     }
816
817     memset(&kop, 0, sizeof kop);
818     kop.crk_op = CRK_MOD_EXP_CRT;
819     /* inputs: rsa->p rsa->q I rsa->dmp1 rsa->dmq1 rsa->iqmp */
820     if (bn2crparam(rsa->p, &kop.crk_param[0]))
821         goto err;
822     if (bn2crparam(rsa->q, &kop.crk_param[1]))
823         goto err;
824     if (bn2crparam(I, &kop.crk_param[2]))
825         goto err;
826     if (bn2crparam(rsa->dmp1, &kop.crk_param[3]))
827         goto err;
828     if (bn2crparam(rsa->dmq1, &kop.crk_param[4]))
829         goto err;
830     if (bn2crparam(rsa->iqmp, &kop.crk_param[5]))
831         goto err;
832     kop.crk_iparams = 6;
833
834     if (cryptodev_asym(&kop, BN_num_bytes(rsa->n), r0, 0, NULL)) {
835         const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
836         printf("OCF asym process failed, running in Software\n");
837         ret = (*meth->rsa_mod_exp) (r0, I, rsa, ctx);
838
839     } else if (ECANCELED == kop.crk_status) {
840         const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
841         printf("OCF hardware operation cancelled. Running in Software\n");
842         ret = (*meth->rsa_mod_exp) (r0, I, rsa, ctx);
843     }
844     /* else cryptodev operation worked ok ==> ret = 1 */
845
846  err:
847     zapparams(&kop);
848     return (ret);
849 }
850
851 static RSA_METHOD cryptodev_rsa = {
852     "cryptodev RSA method",
853     NULL,                       /* rsa_pub_enc */
854     NULL,                       /* rsa_pub_dec */
855     NULL,                       /* rsa_priv_enc */
856     NULL,                       /* rsa_priv_dec */
857     NULL,
858     NULL,
859     NULL,                       /* init */
860     NULL,                       /* finish */
861     0,                          /* flags */
862     NULL,                       /* app_data */
863     NULL,                       /* rsa_sign */
864     NULL                        /* rsa_verify */
865 };
866
867 static int
868 cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p,
869                          const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
870 {
871     return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx));
872 }
873
874 static int
875 cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g,
876                           BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2, BIGNUM *p,
877                           BN_CTX *ctx, BN_MONT_CTX *mont)
878 {
879     BIGNUM t2;
880     int ret = 0;
881
882     BN_init(&t2);
883
884     /* v = ( g^u1 * y^u2 mod p ) mod q */
885     /* let t1 = g ^ u1 mod p */
886     ret = 0;
887
888     if (!dsa->meth->bn_mod_exp(dsa, t1, dsa->g, u1, dsa->p, ctx, mont))
889         goto err;
890
891     /* let t2 = y ^ u2 mod p */
892     if (!dsa->meth->bn_mod_exp(dsa, &t2, dsa->pub_key, u2, dsa->p, ctx, mont))
893         goto err;
894     /* let u1 = t1 * t2 mod p */
895     if (!BN_mod_mul(u1, t1, &t2, dsa->p, ctx))
896         goto err;
897
898     BN_copy(t1, u1);
899
900     ret = 1;
901  err:
902     BN_free(&t2);
903     return (ret);
904 }
905
906 static DSA_SIG *cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen,
907                                       DSA *dsa)
908 {
909     struct crypt_kop kop;
910     BIGNUM *r = NULL, *s = NULL;
911     DSA_SIG *dsaret = NULL;
912
913     if ((r = BN_new()) == NULL)
914         goto err;
915     if ((s = BN_new()) == NULL) {
916         BN_free(r);
917         goto err;
918     }
919
920     memset(&kop, 0, sizeof kop);
921     kop.crk_op = CRK_DSA_SIGN;
922
923     /* inputs: dgst dsa->p dsa->q dsa->g dsa->priv_key */
924     kop.crk_param[0].crp_p = (caddr_t) dgst;
925     kop.crk_param[0].crp_nbits = dlen * 8;
926     if (bn2crparam(dsa->p, &kop.crk_param[1]))
927         goto err;
928     if (bn2crparam(dsa->q, &kop.crk_param[2]))
929         goto err;
930     if (bn2crparam(dsa->g, &kop.crk_param[3]))
931         goto err;
932     if (bn2crparam(dsa->priv_key, &kop.crk_param[4]))
933         goto err;
934     kop.crk_iparams = 5;
935
936     if (cryptodev_asym(&kop, BN_num_bytes(dsa->q), r,
937                        BN_num_bytes(dsa->q), s) == 0) {
938         dsaret = DSA_SIG_new();
939         dsaret->r = r;
940         dsaret->s = s;
941     } else {
942         const DSA_METHOD *meth = DSA_OpenSSL();
943         BN_free(r);
944         BN_free(s);
945         dsaret = (meth->dsa_do_sign) (dgst, dlen, dsa);
946     }
947  err:
948     kop.crk_param[0].crp_p = NULL;
949     zapparams(&kop);
950     return (dsaret);
951 }
952
953 static int
954 cryptodev_dsa_verify(const unsigned char *dgst, int dlen,
955                      DSA_SIG *sig, DSA *dsa)
956 {
957     struct crypt_kop kop;
958     int dsaret = 1;
959
960     memset(&kop, 0, sizeof kop);
961     kop.crk_op = CRK_DSA_VERIFY;
962
963     /* inputs: dgst dsa->p dsa->q dsa->g dsa->pub_key sig->r sig->s */
964     kop.crk_param[0].crp_p = (caddr_t) dgst;
965     kop.crk_param[0].crp_nbits = dlen * 8;
966     if (bn2crparam(dsa->p, &kop.crk_param[1]))
967         goto err;
968     if (bn2crparam(dsa->q, &kop.crk_param[2]))
969         goto err;
970     if (bn2crparam(dsa->g, &kop.crk_param[3]))
971         goto err;
972     if (bn2crparam(dsa->pub_key, &kop.crk_param[4]))
973         goto err;
974     if (bn2crparam(sig->r, &kop.crk_param[5]))
975         goto err;
976     if (bn2crparam(sig->s, &kop.crk_param[6]))
977         goto err;
978     kop.crk_iparams = 7;
979
980     if (cryptodev_asym(&kop, 0, NULL, 0, NULL) == 0) {
981         /*
982          * OCF success value is 0, if not zero, change dsaret to fail
983          */
984         if (0 != kop.crk_status)
985             dsaret = 0;
986     } else {
987         const DSA_METHOD *meth = DSA_OpenSSL();
988
989         dsaret = (meth->dsa_do_verify) (dgst, dlen, sig, dsa);
990     }
991  err:
992     kop.crk_param[0].crp_p = NULL;
993     zapparams(&kop);
994     return (dsaret);
995 }
996
997 static DSA_METHOD cryptodev_dsa = {
998     "cryptodev DSA method",
999     NULL,
1000     NULL,                       /* dsa_sign_setup */
1001     NULL,
1002     NULL,                       /* dsa_mod_exp */
1003     NULL,
1004     NULL,                       /* init */
1005     NULL,                       /* finish */
1006     0,                          /* flags */
1007     NULL                        /* app_data */
1008 };
1009
1010 static int
1011 cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
1012                      const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
1013                      BN_MONT_CTX *m_ctx)
1014 {
1015     return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx));
1016 }
1017
1018 static int
1019 cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh)
1020 {
1021     struct crypt_kop kop;
1022     int dhret = 1;
1023     int fd, keylen;
1024
1025     if ((fd = get_asym_dev_crypto()) < 0) {
1026         const DH_METHOD *meth = DH_OpenSSL();
1027
1028         return ((meth->compute_key) (key, pub_key, dh));
1029     }
1030
1031     keylen = BN_num_bits(dh->p);
1032
1033     memset(&kop, 0, sizeof kop);
1034     kop.crk_op = CRK_DH_COMPUTE_KEY;
1035
1036     /* inputs: dh->priv_key pub_key dh->p key */
1037     if (bn2crparam(dh->priv_key, &kop.crk_param[0]))
1038         goto err;
1039     if (bn2crparam(pub_key, &kop.crk_param[1]))
1040         goto err;
1041     if (bn2crparam(dh->p, &kop.crk_param[2]))
1042         goto err;
1043     kop.crk_iparams = 3;
1044
1045     kop.crk_param[3].crp_p = (char *)key;
1046     kop.crk_param[3].crp_nbits = keylen * 8;
1047     kop.crk_oparams = 1;
1048
1049     if (ioctl(fd, CIOCKEY, &kop) == -1) {
1050         const DH_METHOD *meth = DH_OpenSSL();
1051
1052         dhret = (meth->compute_key) (key, pub_key, dh);
1053     }
1054  err:
1055     kop.crk_param[3].crp_p = NULL;
1056     zapparams(&kop);
1057     return (dhret);
1058 }
1059
1060 static DH_METHOD cryptodev_dh = {
1061     "cryptodev DH method",
1062     NULL,                       /* cryptodev_dh_generate_key */
1063     NULL,
1064     NULL,
1065     NULL,
1066     NULL,
1067     0,                          /* flags */
1068     NULL                        /* app_data */
1069 };
1070
1071 /*
1072  * ctrl right now is just a wrapper that doesn't do much
1073  * but I expect we'll want some options soon.
1074  */
1075 static int cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) ())
1076 {
1077 # ifdef HAVE_SYSLOG_R
1078     struct syslog_data sd = SYSLOG_DATA_INIT;
1079 # endif
1080
1081     switch (cmd) {
1082     default:
1083 # ifdef HAVE_SYSLOG_R
1084         syslog_r(LOG_ERR, &sd, "cryptodev_ctrl: unknown command %d", cmd);
1085 # else
1086         syslog(LOG_ERR, "cryptodev_ctrl: unknown command %d", cmd);
1087 # endif
1088         break;
1089     }
1090     return (1);
1091 }
1092
1093 void ENGINE_load_cryptodev(void)
1094 {
1095     ENGINE *engine = ENGINE_new();
1096     int fd;
1097
1098     if (engine == NULL)
1099         return;
1100     if ((fd = get_dev_crypto()) < 0) {
1101         ENGINE_free(engine);
1102         return;
1103     }
1104
1105     /*
1106      * find out what asymmetric crypto algorithms we support
1107      */
1108     if (ioctl(fd, CIOCASYMFEAT, &cryptodev_asymfeat) == -1) {
1109         close(fd);
1110         ENGINE_free(engine);
1111         return;
1112     }
1113     close(fd);
1114
1115     if (!ENGINE_set_id(engine, "cryptodev") ||
1116         !ENGINE_set_name(engine, "BSD cryptodev engine") ||
1117         !ENGINE_set_ciphers(engine, cryptodev_engine_ciphers) ||
1118         !ENGINE_set_digests(engine, cryptodev_engine_digests) ||
1119         !ENGINE_set_ctrl_function(engine, cryptodev_ctrl) ||
1120         !ENGINE_set_cmd_defns(engine, cryptodev_defns)) {
1121         ENGINE_free(engine);
1122         return;
1123     }
1124
1125     if (ENGINE_set_RSA(engine, &cryptodev_rsa)) {
1126         const RSA_METHOD *rsa_meth = RSA_PKCS1_SSLeay();
1127
1128         cryptodev_rsa.bn_mod_exp = rsa_meth->bn_mod_exp;
1129         cryptodev_rsa.rsa_mod_exp = rsa_meth->rsa_mod_exp;
1130         cryptodev_rsa.rsa_pub_enc = rsa_meth->rsa_pub_enc;
1131         cryptodev_rsa.rsa_pub_dec = rsa_meth->rsa_pub_dec;
1132         cryptodev_rsa.rsa_priv_enc = rsa_meth->rsa_priv_enc;
1133         cryptodev_rsa.rsa_priv_dec = rsa_meth->rsa_priv_dec;
1134         if (cryptodev_asymfeat & CRF_MOD_EXP) {
1135             cryptodev_rsa.bn_mod_exp = cryptodev_bn_mod_exp;
1136             if (cryptodev_asymfeat & CRF_MOD_EXP_CRT)
1137                 cryptodev_rsa.rsa_mod_exp = cryptodev_rsa_mod_exp;
1138             else
1139                 cryptodev_rsa.rsa_mod_exp = cryptodev_rsa_nocrt_mod_exp;
1140         }
1141     }
1142
1143     if (ENGINE_set_DSA(engine, &cryptodev_dsa)) {
1144         const DSA_METHOD *meth = DSA_OpenSSL();
1145
1146         memcpy(&cryptodev_dsa, meth, sizeof(DSA_METHOD));
1147         if (cryptodev_asymfeat & CRF_DSA_SIGN)
1148             cryptodev_dsa.dsa_do_sign = cryptodev_dsa_do_sign;
1149         if (cryptodev_asymfeat & CRF_MOD_EXP) {
1150             cryptodev_dsa.bn_mod_exp = cryptodev_dsa_bn_mod_exp;
1151             cryptodev_dsa.dsa_mod_exp = cryptodev_dsa_dsa_mod_exp;
1152         }
1153         if (cryptodev_asymfeat & CRF_DSA_VERIFY)
1154             cryptodev_dsa.dsa_do_verify = cryptodev_dsa_verify;
1155     }
1156
1157     if (ENGINE_set_DH(engine, &cryptodev_dh)) {
1158         const DH_METHOD *dh_meth = DH_OpenSSL();
1159
1160         cryptodev_dh.generate_key = dh_meth->generate_key;
1161         cryptodev_dh.compute_key = dh_meth->compute_key;
1162         cryptodev_dh.bn_mod_exp = dh_meth->bn_mod_exp;
1163         if (cryptodev_asymfeat & CRF_MOD_EXP) {
1164             cryptodev_dh.bn_mod_exp = cryptodev_mod_exp_dh;
1165             if (cryptodev_asymfeat & CRF_DH_COMPUTE_KEY)
1166                 cryptodev_dh.compute_key = cryptodev_dh_compute_key;
1167         }
1168     }
1169
1170     ENGINE_add(engine);
1171     ENGINE_free(engine);
1172     ERR_clear_error();
1173 }
1174
1175 #endif                          /* HAVE_CRYPTODEV */