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