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