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