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