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