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