8e6777753d607888dbbad7d45d713b282185fcf2
[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__))
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 <openssl/dh.h>
59 #include <openssl/dsa.h>
60 #include <openssl/err.h>
61 #include <openssl/rsa.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 #ifdef USE_CRYPTODEV_DIGESTS
77         char dummy_mac_key[HASH_MAX_LEN];
78
79         unsigned char digest_res[HASH_MAX_LEN];
80         char *mac_data;
81         int mac_len;
82 #endif
83 };
84
85 static u_int32_t cryptodev_asymfeat = 0;
86
87 static int get_asym_dev_crypto(void);
88 static int open_dev_crypto(void);
89 static int get_dev_crypto(void);
90 static int get_cryptodev_ciphers(const int **cnids);
91 #ifdef USE_CRYPTODEV_DIGESTS
92 static int get_cryptodev_digests(const int **cnids);
93 #endif
94 static int cryptodev_usable_ciphers(const int **nids);
95 static int cryptodev_usable_digests(const int **nids);
96 static int cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
97     const unsigned char *in, size_t inl);
98 static int cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
99     const unsigned char *iv, int enc);
100 static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx);
101 static int cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
102     const int **nids, int nid);
103 static int cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest,
104     const int **nids, int nid);
105 static int bn2crparam(const BIGNUM *a, struct crparam *crp);
106 static int crparam2bn(struct crparam *crp, BIGNUM *a);
107 static void zapparams(struct crypt_kop *kop);
108 static int cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r,
109     int slen, BIGNUM *s);
110
111 static int cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a,
112     const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
113 static int cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I,
114     RSA *rsa, BN_CTX *ctx);
115 static int cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx);
116 static int cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a,
117     const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
118 static int cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g,
119     BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2, BIGNUM *p,
120     BN_CTX *ctx, BN_MONT_CTX *mont);
121 static DSA_SIG *cryptodev_dsa_do_sign(const unsigned char *dgst,
122     int dlen, DSA *dsa);
123 static int cryptodev_dsa_verify(const unsigned char *dgst, int dgst_len,
124     DSA_SIG *sig, DSA *dsa);
125 static int cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
126     const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
127     BN_MONT_CTX *m_ctx);
128 static int cryptodev_dh_compute_key(unsigned char *key,
129     const BIGNUM *pub_key, DH *dh);
130 static int cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p,
131     void (*f)(void));
132 void ENGINE_load_cryptodev(void);
133
134 static const ENGINE_CMD_DEFN cryptodev_defns[] = {
135         { 0, NULL, NULL, 0 }
136 };
137
138 static struct {
139         int     id;
140         int     nid;
141         int     ivmax;
142         int     keylen;
143 } ciphers[] = {
144         { CRYPTO_ARC4,                  NID_rc4,                0,      16, },
145         { CRYPTO_DES_CBC,               NID_des_cbc,            8,       8, },
146         { CRYPTO_3DES_CBC,              NID_des_ede3_cbc,       8,      24, },
147         { CRYPTO_AES_CBC,               NID_aes_128_cbc,        16,     16, },
148         { CRYPTO_AES_CBC,               NID_aes_192_cbc,        16,     24, },
149         { CRYPTO_AES_CBC,               NID_aes_256_cbc,        16,     32, },
150         { CRYPTO_AES_CTR,               NID_aes_128_ctr,        14,     16, },
151         { CRYPTO_AES_CTR,               NID_aes_192_ctr,        14,     24, },
152         { CRYPTO_AES_CTR,               NID_aes_256_ctr,        14,     32, },
153         { CRYPTO_BLF_CBC,               NID_bf_cbc,             8,      16, },
154         { CRYPTO_CAST_CBC,              NID_cast5_cbc,          8,      16, },
155         { CRYPTO_SKIPJACK_CBC,          NID_undef,              0,       0, },
156         { 0,                            NID_undef,              0,       0, },
157 };
158
159 #ifdef USE_CRYPTODEV_DIGESTS
160 static struct {
161         int     id;
162         int     nid;
163         int     keylen;
164 } digests[] = {
165         { CRYPTO_MD5_HMAC,              NID_hmacWithMD5,        16},
166         { CRYPTO_SHA1_HMAC,             NID_hmacWithSHA1,       20},
167         { CRYPTO_RIPEMD160_HMAC,        NID_ripemd160,          16/*?*/},
168         { CRYPTO_MD5_KPDK,              NID_undef,              0},
169         { CRYPTO_SHA1_KPDK,             NID_undef,              0},
170         { CRYPTO_MD5,                   NID_md5,                16},
171         { CRYPTO_SHA1,                  NID_sha1,               20},
172         { 0,                            NID_undef,              0},
173 };
174 #endif
175
176 /*
177  * Return a fd if /dev/crypto seems usable, 0 otherwise.
178  */
179 static int
180 open_dev_crypto(void)
181 {
182         static int fd = -1;
183
184         if (fd == -1) {
185                 if ((fd = open("/dev/crypto", O_RDWR, 0)) == -1)
186                         return (-1);
187                 /* close on exec */
188                 if (fcntl(fd, F_SETFD, 1) == -1) {
189                         close(fd);
190                         fd = -1;
191                         return (-1);
192                 }
193         }
194         return (fd);
195 }
196
197 static int
198 get_dev_crypto(void)
199 {
200         int fd, retfd;
201
202         if ((fd = open_dev_crypto()) == -1)
203                 return (-1);
204 #ifndef CRIOGET_NOT_NEEDED
205         if (ioctl(fd, CRIOGET, &retfd) == -1)
206                 return (-1);
207
208         /* close on exec */
209         if (fcntl(retfd, F_SETFD, 1) == -1) {
210                 close(retfd);
211                 return (-1);
212         }
213 #else
214         retfd = fd;
215 #endif
216         return (retfd);
217 }
218
219 static void put_dev_crypto(int fd)
220 {
221 #ifndef CRIOGET_NOT_NEEDED
222         close(fd);
223 #endif
224 }
225
226 /* Caching version for asym operations */
227 static int
228 get_asym_dev_crypto(void)
229 {
230         static int fd = -1;
231
232         if (fd == -1)
233                 fd = get_dev_crypto();
234         return fd;
235 }
236
237 /*
238  * Find out what ciphers /dev/crypto will let us have a session for.
239  * XXX note, that some of these openssl doesn't deal with yet!
240  * returning them here is harmless, as long as we return NULL
241  * when asked for a handler in the cryptodev_engine_ciphers routine
242  */
243 static int
244 get_cryptodev_ciphers(const int **cnids)
245 {
246         static int nids[CRYPTO_ALGORITHM_MAX];
247         struct session_op sess;
248         int fd, i, count = 0;
249
250         if ((fd = get_dev_crypto()) < 0) {
251                 *cnids = NULL;
252                 return (0);
253         }
254         memset(&sess, 0, sizeof(sess));
255         sess.key = (caddr_t)"123456789abcdefghijklmno";
256
257         for (i = 0; ciphers[i].id && count < CRYPTO_ALGORITHM_MAX; i++) {
258                 if (ciphers[i].nid == NID_undef)
259                         continue;
260                 sess.cipher = ciphers[i].id;
261                 sess.keylen = ciphers[i].keylen;
262                 sess.mac = 0;
263                 if (ioctl(fd, CIOCGSESSION, &sess) != -1 &&
264                     ioctl(fd, CIOCFSESSION, &sess.ses) != -1)
265                         nids[count++] = ciphers[i].nid;
266         }
267         put_dev_crypto(fd);
268
269         if (count > 0)
270                 *cnids = nids;
271         else
272                 *cnids = NULL;
273         return (count);
274 }
275
276 #ifdef USE_CRYPTODEV_DIGESTS
277 /*
278  * Find out what digests /dev/crypto will let us have a session for.
279  * XXX note, that some of these openssl doesn't deal with yet!
280  * returning them here is harmless, as long as we return NULL
281  * when asked for a handler in the cryptodev_engine_digests routine
282  */
283 static int
284 get_cryptodev_digests(const int **cnids)
285 {
286         static int nids[CRYPTO_ALGORITHM_MAX];
287         struct session_op sess;
288         int fd, i, count = 0;
289
290         if ((fd = get_dev_crypto()) < 0) {
291                 *cnids = NULL;
292                 return (0);
293         }
294         memset(&sess, 0, sizeof(sess));
295         sess.mackey = (caddr_t)"123456789abcdefghijklmno";
296         for (i = 0; digests[i].id && count < CRYPTO_ALGORITHM_MAX; i++) {
297                 if (digests[i].nid == NID_undef)
298                         continue;
299                 sess.mac = digests[i].id;
300                 sess.mackeylen = digests[i].keylen;
301                 sess.cipher = 0;
302                 if (ioctl(fd, CIOCGSESSION, &sess) != -1 &&
303                     ioctl(fd, CIOCFSESSION, &sess.ses) != -1)
304                         nids[count++] = digests[i].nid;
305         }
306         put_dev_crypto(fd);
307
308         if (count > 0)
309                 *cnids = nids;
310         else
311                 *cnids = NULL;
312         return (count);
313 }
314 #endif  /* 0 */
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 #ifdef USE_CRYPTODEV_DIGESTS
347         return (get_cryptodev_digests(nids));
348 #else
349         /*
350          * XXXX just disable all digests for now, because it sucks.
351          * we need a better way to decide this - i.e. I may not
352          * want digests on slow cards like hifn on fast machines,
353          * but might want them on slow or loaded machines, etc.
354          * will also want them when using crypto cards that don't
355          * suck moose gonads - would be nice to be able to decide something
356          * as reasonable default without having hackery that's card dependent.
357          * of course, the default should probably be just do everything,
358          * with perhaps a sysctl to turn algoritms off (or have them off
359          * by default) on cards that generally suck like the hifn.
360          */
361         *nids = NULL;
362         return (0);
363 #endif
364 }
365
366 static int
367 cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
368     const unsigned char *in, size_t inl)
369 {
370         struct crypt_op cryp;
371         struct dev_crypto_state *state = ctx->cipher_data;
372         struct session_op *sess = &state->d_sess;
373         const void *iiv;
374         unsigned char save_iv[EVP_MAX_IV_LENGTH];
375
376         if (state->d_fd < 0)
377                 return (0);
378         if (!inl)
379                 return (1);
380         if ((inl % ctx->cipher->block_size) != 0)
381                 return (0);
382
383         memset(&cryp, 0, sizeof(cryp));
384
385         cryp.ses = sess->ses;
386         cryp.flags = 0;
387         cryp.len = inl;
388         cryp.src = (caddr_t) in;
389         cryp.dst = (caddr_t) out;
390         cryp.mac = 0;
391
392         cryp.op = ctx->encrypt ? COP_ENCRYPT : COP_DECRYPT;
393
394         if (ctx->cipher->iv_len) {
395                 cryp.iv = (caddr_t) ctx->iv;
396                 if (!ctx->encrypt) {
397                         iiv = in + inl - ctx->cipher->iv_len;
398                         memcpy(save_iv, iiv, ctx->cipher->iv_len);
399                 }
400         } else
401                 cryp.iv = NULL;
402
403         if (ioctl(state->d_fd, CIOCCRYPT, &cryp) == -1) {
404                 /* XXX need better errror handling
405                  * this can fail for a number of different reasons.
406                  */
407                 return (0);
408         }
409
410         if (ctx->cipher->iv_len) {
411                 if (ctx->encrypt)
412                         iiv = out + inl - ctx->cipher->iv_len;
413                 else
414                         iiv = save_iv;
415                 memcpy(ctx->iv, iiv, ctx->cipher->iv_len);
416         }
417         return (1);
418 }
419
420 static int
421 cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
422     const unsigned char *iv, int enc)
423 {
424         struct dev_crypto_state *state = ctx->cipher_data;
425         struct session_op *sess = &state->d_sess;
426         int cipher = -1, i;
427
428         for (i = 0; ciphers[i].id; i++)
429                 if (ctx->cipher->nid == ciphers[i].nid &&
430                     ctx->cipher->iv_len <= ciphers[i].ivmax &&
431                     ctx->key_len == ciphers[i].keylen) {
432                         cipher = ciphers[i].id;
433                         break;
434                 }
435
436         if (!ciphers[i].id) {
437                 state->d_fd = -1;
438                 return (0);
439         }
440
441         memset(sess, 0, sizeof(struct session_op));
442
443         if ((state->d_fd = get_dev_crypto()) < 0)
444                 return (0);
445
446         sess->key = (caddr_t)key;
447         sess->keylen = ctx->key_len;
448         sess->cipher = cipher;
449
450         if (ioctl(state->d_fd, CIOCGSESSION, sess) == -1) {
451                 put_dev_crypto(state->d_fd);
452                 state->d_fd = -1;
453                 return (0);
454         }
455         return (1);
456 }
457
458 /*
459  * free anything we allocated earlier when initting a
460  * session, and close the session.
461  */
462 static int
463 cryptodev_cleanup(EVP_CIPHER_CTX *ctx)
464 {
465         int ret = 0;
466         struct dev_crypto_state *state = ctx->cipher_data;
467         struct session_op *sess = &state->d_sess;
468
469         if (state->d_fd < 0)
470                 return (0);
471
472         /* XXX if this ioctl fails, someting's wrong. the invoker
473          * may have called us with a bogus ctx, or we could
474          * have a device that for whatever reason just doesn't
475          * want to play ball - it's not clear what's right
476          * here - should this be an error? should it just
477          * increase a counter, hmm. For right now, we return
478          * 0 - I don't believe that to be "right". we could
479          * call the gorpy openssl lib error handlers that
480          * print messages to users of the library. hmm..
481          */
482
483         if (ioctl(state->d_fd, CIOCFSESSION, &sess->ses) == -1) {
484                 ret = 0;
485         } else {
486                 ret = 1;
487         }
488         put_dev_crypto(state->d_fd);
489         state->d_fd = -1;
490
491         return (ret);
492 }
493
494 /*
495  * libcrypto EVP stuff - this is how we get wired to EVP so the engine
496  * gets called when libcrypto requests a cipher NID.
497  */
498
499 /* RC4 */
500 const EVP_CIPHER cryptodev_rc4 = {
501         NID_rc4,
502         1, 16, 0,
503         EVP_CIPH_VARIABLE_LENGTH,
504         cryptodev_init_key,
505         cryptodev_cipher,
506         cryptodev_cleanup,
507         sizeof(struct dev_crypto_state),
508         NULL,
509         NULL,
510         NULL
511 };
512
513 /* DES CBC EVP */
514 const EVP_CIPHER cryptodev_des_cbc = {
515         NID_des_cbc,
516         8, 8, 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 /* 3DES CBC EVP */
528 const EVP_CIPHER cryptodev_3des_cbc = {
529         NID_des_ede3_cbc,
530         8, 24, 8,
531         EVP_CIPH_CBC_MODE,
532         cryptodev_init_key,
533         cryptodev_cipher,
534         cryptodev_cleanup,
535         sizeof(struct dev_crypto_state),
536         EVP_CIPHER_set_asn1_iv,
537         EVP_CIPHER_get_asn1_iv,
538         NULL
539 };
540
541 const EVP_CIPHER cryptodev_bf_cbc = {
542         NID_bf_cbc,
543         8, 16, 8,
544         EVP_CIPH_CBC_MODE,
545         cryptodev_init_key,
546         cryptodev_cipher,
547         cryptodev_cleanup,
548         sizeof(struct dev_crypto_state),
549         EVP_CIPHER_set_asn1_iv,
550         EVP_CIPHER_get_asn1_iv,
551         NULL
552 };
553
554 const EVP_CIPHER cryptodev_cast_cbc = {
555         NID_cast5_cbc,
556         8, 16, 8,
557         EVP_CIPH_CBC_MODE,
558         cryptodev_init_key,
559         cryptodev_cipher,
560         cryptodev_cleanup,
561         sizeof(struct dev_crypto_state),
562         EVP_CIPHER_set_asn1_iv,
563         EVP_CIPHER_get_asn1_iv,
564         NULL
565 };
566
567 const EVP_CIPHER cryptodev_aes_cbc = {
568         NID_aes_128_cbc,
569         16, 16, 16,
570         EVP_CIPH_CBC_MODE,
571         cryptodev_init_key,
572         cryptodev_cipher,
573         cryptodev_cleanup,
574         sizeof(struct dev_crypto_state),
575         EVP_CIPHER_set_asn1_iv,
576         EVP_CIPHER_get_asn1_iv,
577         NULL
578 };
579
580 const EVP_CIPHER cryptodev_aes_192_cbc = {
581         NID_aes_192_cbc,
582         16, 24, 16,
583         EVP_CIPH_CBC_MODE,
584         cryptodev_init_key,
585         cryptodev_cipher,
586         cryptodev_cleanup,
587         sizeof(struct dev_crypto_state),
588         EVP_CIPHER_set_asn1_iv,
589         EVP_CIPHER_get_asn1_iv,
590         NULL
591 };
592
593 const EVP_CIPHER cryptodev_aes_256_cbc = {
594         NID_aes_256_cbc,
595         16, 32, 16,
596         EVP_CIPH_CBC_MODE,
597         cryptodev_init_key,
598         cryptodev_cipher,
599         cryptodev_cleanup,
600         sizeof(struct dev_crypto_state),
601         EVP_CIPHER_set_asn1_iv,
602         EVP_CIPHER_get_asn1_iv,
603         NULL
604 };
605
606 const EVP_CIPHER cryptodev_aes_ctr = {
607         NID_aes_128_ctr,
608         16, 16, 14,
609         EVP_CIPH_CTR_MODE,
610         cryptodev_init_key,
611         cryptodev_cipher,
612         cryptodev_cleanup,
613         sizeof(struct dev_crypto_state),
614         EVP_CIPHER_set_asn1_iv,
615         EVP_CIPHER_get_asn1_iv,
616         NULL
617 };
618
619 const EVP_CIPHER cryptodev_aes_ctr_192 = {
620         NID_aes_192_ctr,
621         16, 24, 14,
622         EVP_CIPH_CTR_MODE,
623         cryptodev_init_key,
624         cryptodev_cipher,
625         cryptodev_cleanup,
626         sizeof(struct dev_crypto_state),
627         EVP_CIPHER_set_asn1_iv,
628         EVP_CIPHER_get_asn1_iv,
629         NULL
630 };
631
632 const EVP_CIPHER cryptodev_aes_ctr_256 = {
633         NID_aes_256_ctr,
634         16, 32, 14,
635         EVP_CIPH_CTR_MODE,
636         cryptodev_init_key,
637         cryptodev_cipher,
638         cryptodev_cleanup,
639         sizeof(struct dev_crypto_state),
640         EVP_CIPHER_set_asn1_iv,
641         EVP_CIPHER_get_asn1_iv,
642         NULL
643 };
644
645 /*
646  * Registered by the ENGINE when used to find out how to deal with
647  * a particular NID in the ENGINE. this says what we'll do at the
648  * top level - note, that list is restricted by what we answer with
649  */
650 static int
651 cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
652     const int **nids, int nid)
653 {
654         if (!cipher)
655                 return (cryptodev_usable_ciphers(nids));
656
657         switch (nid) {
658         case NID_rc4:
659                 *cipher = &cryptodev_rc4;
660                 break;
661         case NID_des_ede3_cbc:
662                 *cipher = &cryptodev_3des_cbc;
663                 break;
664         case NID_des_cbc:
665                 *cipher = &cryptodev_des_cbc;
666                 break;
667         case NID_bf_cbc:
668                 *cipher = &cryptodev_bf_cbc;
669                 break;
670         case NID_cast5_cbc:
671                 *cipher = &cryptodev_cast_cbc;
672                 break;
673         case NID_aes_128_cbc:
674                 *cipher = &cryptodev_aes_cbc;
675                 break;
676         case NID_aes_192_cbc:
677                 *cipher = &cryptodev_aes_192_cbc;
678                 break;
679         case NID_aes_256_cbc:
680                 *cipher = &cryptodev_aes_256_cbc;
681                 break;
682         case NID_aes_128_ctr:
683                 *cipher = &cryptodev_aes_ctr;
684                 break;
685         case NID_aes_192_ctr:
686                 *cipher = &cryptodev_aes_ctr_192;
687                 break;
688         case NID_aes_256_ctr:
689                 *cipher = &cryptodev_aes_ctr_256;
690                 break;
691         default:
692                 *cipher = NULL;
693                 break;
694         }
695         return (*cipher != NULL);
696 }
697
698
699 #ifdef USE_CRYPTODEV_DIGESTS
700
701 /* convert digest type to cryptodev */
702 static int
703 digest_nid_to_cryptodev(int nid)
704 {
705         int i;
706
707         for (i = 0; digests[i].id; i++)
708                 if (digests[i].nid == nid)
709                         return (digests[i].id);
710         return (0);
711 }
712
713
714 static int
715 digest_key_length(int nid)
716 {
717         int i;
718
719         for (i = 0; digests[i].id; i++)
720                 if (digests[i].nid == nid)
721                         return digests[i].keylen;
722         return (0);
723 }
724
725
726 static int cryptodev_digest_init(EVP_MD_CTX *ctx)
727 {
728         struct dev_crypto_state *state = ctx->md_data;
729         struct session_op *sess = &state->d_sess;
730         int digest;
731
732         if ((digest = digest_nid_to_cryptodev(ctx->digest->type)) == NID_undef){
733                 printf("cryptodev_digest_init: Can't get digest \n");
734                 return (0);
735         }
736
737         memset(state, 0, sizeof(struct dev_crypto_state));
738
739         if ((state->d_fd = get_dev_crypto()) < 0) {
740                 printf("cryptodev_digest_init: Can't get Dev \n");
741                 return (0);
742         }
743
744         sess->mackey = state->dummy_mac_key;
745         sess->mackeylen = digest_key_length(ctx->digest->type);
746         sess->mac = digest;
747
748         if (ioctl(state->d_fd, CIOCGSESSION, sess) < 0) {
749                 put_dev_crypto(state->d_fd);
750                 state->d_fd = -1;
751                 printf("cryptodev_digest_init: Open session failed\n");
752                 return (0);
753         }
754
755         return (1);
756 }
757
758 static int cryptodev_digest_update(EVP_MD_CTX *ctx, const void *data,
759                 size_t count)
760 {
761         struct crypt_op cryp;
762         struct dev_crypto_state *state = ctx->md_data;
763         struct session_op *sess = &state->d_sess;
764
765         if (!data || state->d_fd < 0) {
766                 printf("cryptodev_digest_update: illegal inputs \n");
767                 return (0);
768         }
769
770         if (!count) {
771                 return (0);
772         }
773
774         if (!(ctx->flags & EVP_MD_CTX_FLAG_ONESHOT)) {
775                 /* if application doesn't support one buffer */
776                 state->mac_data = OPENSSL_realloc(state->mac_data, state->mac_len + count);
777
778                 if (!state->mac_data) {
779                         printf("cryptodev_digest_update: realloc failed\n");
780                         return (0);
781                 }
782
783                 memcpy(state->mac_data + state->mac_len, data, count);
784                 state->mac_len += count;
785         
786                 return (1);
787         }
788
789         memset(&cryp, 0, sizeof(cryp));
790
791         cryp.ses = sess->ses;
792         cryp.flags = 0;
793         cryp.len = count;
794         cryp.src = (caddr_t) data;
795         cryp.dst = NULL;
796         cryp.mac = (caddr_t) state->digest_res;
797         if (ioctl(state->d_fd, CIOCCRYPT, &cryp) < 0) {
798                 printf("cryptodev_digest_update: digest failed\n");
799                 return (0);
800         }
801         return (1);
802 }
803
804
805 static int cryptodev_digest_final(EVP_MD_CTX *ctx, unsigned char *md)
806 {
807         struct crypt_op cryp;
808         struct dev_crypto_state *state = ctx->md_data;
809         struct session_op *sess = &state->d_sess;
810
811         int ret = 1;
812
813         if (!md || state->d_fd < 0) {
814                 printf("cryptodev_digest_final: illegal input\n");
815                 return(0);
816         }
817
818         if (! (ctx->flags & EVP_MD_CTX_FLAG_ONESHOT) ) {
819                 /* if application doesn't support one buffer */
820                 memset(&cryp, 0, sizeof(cryp));
821                 cryp.ses = sess->ses;
822                 cryp.flags = 0;
823                 cryp.len = state->mac_len;
824                 cryp.src = state->mac_data;
825                 cryp.dst = NULL;
826                 cryp.mac = (caddr_t)md;
827                 if (ioctl(state->d_fd, CIOCCRYPT, &cryp) < 0) {
828                         printf("cryptodev_digest_final: digest failed\n");
829                         return (0);
830                 }
831
832                 return 1;
833         }
834
835         memcpy(md, state->digest_res, ctx->digest->md_size);
836
837         return (ret);
838 }
839
840
841 static int cryptodev_digest_cleanup(EVP_MD_CTX *ctx)
842 {
843         int ret = 1;
844         struct dev_crypto_state *state = ctx->md_data;
845         struct session_op *sess = &state->d_sess;
846
847         if (state == NULL)
848           return 0;
849
850         if (state->d_fd < 0) {
851                 printf("cryptodev_digest_cleanup: illegal input\n");
852                 return (0);
853         }
854
855         if (state->mac_data) {
856                 OPENSSL_free(state->mac_data);
857                 state->mac_data = NULL;
858                 state->mac_len = 0;
859         }
860
861         if (ioctl(state->d_fd, CIOCFSESSION, &sess->ses) < 0) {
862                 printf("cryptodev_digest_cleanup: failed to close session\n");
863                 ret = 0;
864         } else {
865                 ret = 1;
866         }
867         put_dev_crypto(state->d_fd);    
868         state->d_fd = -1;
869
870         return (ret);
871 }
872
873 static int cryptodev_digest_copy(EVP_MD_CTX *to,const EVP_MD_CTX *from)
874 {
875         struct dev_crypto_state *fstate = from->md_data;
876         struct dev_crypto_state *dstate = to->md_data;
877         struct session_op *sess;
878         int digest;
879
880         if (dstate == NULL || fstate == NULL)
881           return 1;
882
883         memcpy(dstate, fstate, sizeof(struct dev_crypto_state));
884
885         sess = &dstate->d_sess;
886
887         digest = digest_nid_to_cryptodev(to->digest->type);
888
889         sess->mackey = dstate->dummy_mac_key;
890         sess->mackeylen = digest_key_length(to->digest->type);
891         sess->mac = digest;
892
893         dstate->d_fd = get_dev_crypto();
894
895         if (ioctl(dstate->d_fd, CIOCGSESSION, sess) < 0) {
896                 put_dev_crypto(dstate->d_fd);
897                 dstate->d_fd = -1;
898                 printf("cryptodev_digest_init: Open session failed\n");
899                 return (0);
900         }
901
902         if (fstate->mac_len != 0) {
903                 if (fstate->mac_data != NULL)
904                         {
905                         dstate->mac_data = OPENSSL_malloc(fstate->mac_len);
906                         memcpy(dstate->mac_data, fstate->mac_data, fstate->mac_len);
907                         dstate->mac_len = fstate->mac_len;
908                         }
909         }
910
911         return 1;
912 }
913
914
915 const EVP_MD cryptodev_sha1 = {
916         NID_sha1,
917         NID_undef, 
918         SHA_DIGEST_LENGTH, 
919         EVP_MD_FLAG_ONESHOT,
920         cryptodev_digest_init,
921         cryptodev_digest_update,
922         cryptodev_digest_final,
923         cryptodev_digest_copy,
924         cryptodev_digest_cleanup,
925         EVP_PKEY_NULL_method,
926         SHA_CBLOCK,
927         sizeof(struct dev_crypto_state),
928 };
929
930 const EVP_MD cryptodev_md5 = {
931         NID_md5,
932         NID_undef, 
933         16 /* MD5_DIGEST_LENGTH */, 
934         EVP_MD_FLAG_ONESHOT,
935         cryptodev_digest_init,
936         cryptodev_digest_update,
937         cryptodev_digest_final,
938         cryptodev_digest_copy,
939         cryptodev_digest_cleanup,
940         EVP_PKEY_NULL_method,
941         64 /* MD5_CBLOCK */,
942         sizeof(struct dev_crypto_state),
943 };
944
945 #endif /* USE_CRYPTODEV_DIGESTS */
946
947
948 static int
949 cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest,
950     const int **nids, int nid)
951 {
952         if (!digest)
953                 return (cryptodev_usable_digests(nids));
954
955         switch (nid) {
956 #ifdef USE_CRYPTODEV_DIGESTS
957         case NID_md5:
958                 *digest = &cryptodev_md5; 
959                 break;
960         case NID_sha1:
961                 *digest = &cryptodev_sha1;
962                 break;
963         default:
964 #endif /* USE_CRYPTODEV_DIGESTS */
965                 *digest = NULL;
966                 break;
967         }
968         return (*digest != NULL);
969 }
970
971 /*
972  * Convert a BIGNUM to the representation that /dev/crypto needs.
973  * Upon completion of use, the caller is responsible for freeing
974  * crp->crp_p.
975  */
976 static int
977 bn2crparam(const BIGNUM *a, struct crparam *crp)
978 {
979         int i, j, k;
980         ssize_t bytes, bits;
981         u_char *b;
982
983         crp->crp_p = NULL;
984         crp->crp_nbits = 0;
985
986         bits = BN_num_bits(a);
987         bytes = (bits + 7) / 8;
988
989         b = malloc(bytes);
990         if (b == NULL)
991                 return (1);
992         memset(b, 0, bytes);
993
994         crp->crp_p = (caddr_t) b;
995         crp->crp_nbits = bits;
996
997         for (i = 0, j = 0; i < a->top; i++) {
998                 for (k = 0; k < BN_BITS2 / 8; k++) {
999                         if ((j + k) >= bytes)
1000                                 return (0);
1001                         b[j + k] = a->d[i] >> (k * 8);
1002                 }
1003                 j += BN_BITS2 / 8;
1004         }
1005         return (0);
1006 }
1007
1008 /* Convert a /dev/crypto parameter to a BIGNUM */
1009 static int
1010 crparam2bn(struct crparam *crp, BIGNUM *a)
1011 {
1012         u_int8_t *pd;
1013         int i, bytes;
1014
1015         bytes = (crp->crp_nbits + 7) / 8;
1016
1017         if (bytes == 0)
1018                 return (-1);
1019
1020         if ((pd = (u_int8_t *) malloc(bytes)) == NULL)
1021                 return (-1);
1022
1023         for (i = 0; i < bytes; i++)
1024                 pd[i] = crp->crp_p[bytes - i - 1];
1025
1026         BN_bin2bn(pd, bytes, a);
1027         free(pd);
1028
1029         return (0);
1030 }
1031
1032 static void
1033 zapparams(struct crypt_kop *kop)
1034 {
1035         int i;
1036
1037         for (i = 0; i < kop->crk_iparams + kop->crk_oparams; i++) {
1038                 if (kop->crk_param[i].crp_p)
1039                         free(kop->crk_param[i].crp_p);
1040                 kop->crk_param[i].crp_p = NULL;
1041                 kop->crk_param[i].crp_nbits = 0;
1042         }
1043 }
1044
1045 static int
1046 cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r, int slen, BIGNUM *s)
1047 {
1048         int fd, ret = -1;
1049
1050         if ((fd = get_asym_dev_crypto()) < 0)
1051                 return (ret);
1052
1053         if (r) {
1054                 kop->crk_param[kop->crk_iparams].crp_p = calloc(rlen, sizeof(char));
1055                 kop->crk_param[kop->crk_iparams].crp_nbits = rlen * 8;
1056                 kop->crk_oparams++;
1057         }
1058         if (s) {
1059                 kop->crk_param[kop->crk_iparams+1].crp_p = calloc(slen, sizeof(char));
1060                 kop->crk_param[kop->crk_iparams+1].crp_nbits = slen * 8;
1061                 kop->crk_oparams++;
1062         }
1063
1064         if (ioctl(fd, CIOCKEY, kop) == 0) {
1065                 if (r)
1066                         crparam2bn(&kop->crk_param[kop->crk_iparams], r);
1067                 if (s)
1068                         crparam2bn(&kop->crk_param[kop->crk_iparams+1], s);
1069                 ret = 0;
1070         }
1071
1072         return (ret);
1073 }
1074
1075 static int
1076 cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
1077     const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
1078 {
1079         struct crypt_kop kop;
1080         int ret = 1;
1081
1082         /* Currently, we know we can do mod exp iff we can do any
1083          * asymmetric operations at all.
1084          */
1085         if (cryptodev_asymfeat == 0) {
1086                 ret = BN_mod_exp(r, a, p, m, ctx);
1087                 return (ret);
1088         }
1089
1090         memset(&kop, 0, sizeof kop);
1091         kop.crk_op = CRK_MOD_EXP;
1092
1093         /* inputs: a^p % m */
1094         if (bn2crparam(a, &kop.crk_param[0]))
1095                 goto err;
1096         if (bn2crparam(p, &kop.crk_param[1]))
1097                 goto err;
1098         if (bn2crparam(m, &kop.crk_param[2]))
1099                 goto err;
1100         kop.crk_iparams = 3;
1101
1102         if (cryptodev_asym(&kop, BN_num_bytes(m), r, 0, NULL)) {
1103                 const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
1104                 printf("OCF asym process failed, Running in software\n");
1105                 ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont);
1106
1107         } else if (ECANCELED == kop.crk_status) {
1108                 const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
1109                 printf("OCF hardware operation cancelled. Running in Software\n");
1110                 ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont);
1111         }
1112         /* else cryptodev operation worked ok ==> ret = 1*/
1113
1114 err:
1115         zapparams(&kop);
1116         return (ret);
1117 }
1118
1119 static int
1120 cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
1121 {
1122         int r;
1123         ctx = BN_CTX_new();
1124         r = cryptodev_bn_mod_exp(r0, I, rsa->d, rsa->n, ctx, NULL);
1125         BN_CTX_free(ctx);
1126         return (r);
1127 }
1128
1129 static int
1130 cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
1131 {
1132         struct crypt_kop kop;
1133         int ret = 1;
1134
1135         if (!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) {
1136                 /* XXX 0 means failure?? */
1137                 return (0);
1138         }
1139
1140         memset(&kop, 0, sizeof kop);
1141         kop.crk_op = CRK_MOD_EXP_CRT;
1142         /* inputs: rsa->p rsa->q I rsa->dmp1 rsa->dmq1 rsa->iqmp */
1143         if (bn2crparam(rsa->p, &kop.crk_param[0]))
1144                 goto err;
1145         if (bn2crparam(rsa->q, &kop.crk_param[1]))
1146                 goto err;
1147         if (bn2crparam(I, &kop.crk_param[2]))
1148                 goto err;
1149         if (bn2crparam(rsa->dmp1, &kop.crk_param[3]))
1150                 goto err;
1151         if (bn2crparam(rsa->dmq1, &kop.crk_param[4]))
1152                 goto err;
1153         if (bn2crparam(rsa->iqmp, &kop.crk_param[5]))
1154                 goto err;
1155         kop.crk_iparams = 6;
1156
1157         if (cryptodev_asym(&kop, BN_num_bytes(rsa->n), r0, 0, NULL)) {
1158                 const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
1159                 printf("OCF asym process failed, running in Software\n");
1160                 ret = (*meth->rsa_mod_exp)(r0, I, rsa, ctx);
1161
1162         } else if (ECANCELED == kop.crk_status) {
1163                 const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
1164                 printf("OCF hardware operation cancelled. Running in Software\n");
1165                 ret = (*meth->rsa_mod_exp)(r0, I, rsa, ctx);
1166         }
1167         /* else cryptodev operation worked ok ==> ret = 1*/
1168
1169 err:
1170         zapparams(&kop);
1171         return (ret);
1172 }
1173
1174 static RSA_METHOD cryptodev_rsa = {
1175         "cryptodev RSA method",
1176         NULL,                           /* rsa_pub_enc */
1177         NULL,                           /* rsa_pub_dec */
1178         NULL,                           /* rsa_priv_enc */
1179         NULL,                           /* rsa_priv_dec */
1180         NULL,
1181         NULL,
1182         NULL,                           /* init */
1183         NULL,                           /* finish */
1184         0,                              /* flags */
1185         NULL,                           /* app_data */
1186         NULL,                           /* rsa_sign */
1187         NULL                            /* rsa_verify */
1188 };
1189
1190 static int
1191 cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p,
1192     const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
1193 {
1194         return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx));
1195 }
1196
1197 static int
1198 cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g,
1199     BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2, BIGNUM *p,
1200     BN_CTX *ctx, BN_MONT_CTX *mont)
1201 {
1202         BIGNUM t2;
1203         int ret = 0;
1204
1205         BN_init(&t2);
1206
1207         /* v = ( g^u1 * y^u2 mod p ) mod q */
1208         /* let t1 = g ^ u1 mod p */
1209         ret = 0;
1210
1211         if (!dsa->meth->bn_mod_exp(dsa,t1,dsa->g,u1,dsa->p,ctx,mont))
1212                 goto err;
1213
1214         /* let t2 = y ^ u2 mod p */
1215         if (!dsa->meth->bn_mod_exp(dsa,&t2,dsa->pub_key,u2,dsa->p,ctx,mont))
1216                 goto err;
1217         /* let u1 = t1 * t2 mod p */
1218         if (!BN_mod_mul(u1,t1,&t2,dsa->p,ctx))
1219                 goto err;
1220
1221         BN_copy(t1,u1);
1222
1223         ret = 1;
1224 err:
1225         BN_free(&t2);
1226         return(ret);
1227 }
1228
1229 static DSA_SIG *
1230 cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa)
1231 {
1232         struct crypt_kop kop;
1233         BIGNUM *r = NULL, *s = NULL;
1234         DSA_SIG *dsaret = NULL;
1235
1236         if ((r = BN_new()) == NULL)
1237                 goto err;
1238         if ((s = BN_new()) == NULL) {
1239                 BN_free(r);
1240                 goto err;
1241         }
1242
1243         memset(&kop, 0, sizeof kop);
1244         kop.crk_op = CRK_DSA_SIGN;
1245
1246         /* inputs: dgst dsa->p dsa->q dsa->g dsa->priv_key */
1247         kop.crk_param[0].crp_p = (caddr_t)dgst;
1248         kop.crk_param[0].crp_nbits = dlen * 8;
1249         if (bn2crparam(dsa->p, &kop.crk_param[1]))
1250                 goto err;
1251         if (bn2crparam(dsa->q, &kop.crk_param[2]))
1252                 goto err;
1253         if (bn2crparam(dsa->g, &kop.crk_param[3]))
1254                 goto err;
1255         if (bn2crparam(dsa->priv_key, &kop.crk_param[4]))
1256                 goto err;
1257         kop.crk_iparams = 5;
1258
1259         if (cryptodev_asym(&kop, BN_num_bytes(dsa->q), r,
1260             BN_num_bytes(dsa->q), s) == 0) {
1261                 dsaret = DSA_SIG_new();
1262                 dsaret->r = r;
1263                 dsaret->s = s;
1264         } else {
1265                 const DSA_METHOD *meth = DSA_OpenSSL();
1266                 BN_free(r);
1267                 BN_free(s);
1268                 dsaret = (meth->dsa_do_sign)(dgst, dlen, dsa);
1269         }
1270 err:
1271         kop.crk_param[0].crp_p = NULL;
1272         zapparams(&kop);
1273         return (dsaret);
1274 }
1275
1276 static int
1277 cryptodev_dsa_verify(const unsigned char *dgst, int dlen,
1278     DSA_SIG *sig, DSA *dsa)
1279 {
1280         struct crypt_kop kop;
1281         int dsaret = 1;
1282
1283         memset(&kop, 0, sizeof kop);
1284         kop.crk_op = CRK_DSA_VERIFY;
1285
1286         /* inputs: dgst dsa->p dsa->q dsa->g dsa->pub_key sig->r sig->s */
1287         kop.crk_param[0].crp_p = (caddr_t)dgst;
1288         kop.crk_param[0].crp_nbits = dlen * 8;
1289         if (bn2crparam(dsa->p, &kop.crk_param[1]))
1290                 goto err;
1291         if (bn2crparam(dsa->q, &kop.crk_param[2]))
1292                 goto err;
1293         if (bn2crparam(dsa->g, &kop.crk_param[3]))
1294                 goto err;
1295         if (bn2crparam(dsa->pub_key, &kop.crk_param[4]))
1296                 goto err;
1297         if (bn2crparam(sig->r, &kop.crk_param[5]))
1298                 goto err;
1299         if (bn2crparam(sig->s, &kop.crk_param[6]))
1300                 goto err;
1301         kop.crk_iparams = 7;
1302
1303         if (cryptodev_asym(&kop, 0, NULL, 0, NULL) == 0) {
1304 /*OCF success value is 0, if not zero, change dsaret to fail*/
1305                 if(0 != kop.crk_status) dsaret  = 0;
1306         } else {
1307                 const DSA_METHOD *meth = DSA_OpenSSL();
1308
1309                 dsaret = (meth->dsa_do_verify)(dgst, dlen, sig, dsa);
1310         }
1311 err:
1312         kop.crk_param[0].crp_p = NULL;
1313         zapparams(&kop);
1314         return (dsaret);
1315 }
1316
1317 static DSA_METHOD cryptodev_dsa = {
1318         "cryptodev DSA method",
1319         NULL,
1320         NULL,                           /* dsa_sign_setup */
1321         NULL,
1322         NULL,                           /* dsa_mod_exp */
1323         NULL,
1324         NULL,                           /* init */
1325         NULL,                           /* finish */
1326         0,      /* flags */
1327         NULL    /* app_data */
1328 };
1329
1330 static int
1331 cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
1332     const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
1333     BN_MONT_CTX *m_ctx)
1334 {
1335         return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx));
1336 }
1337
1338 static int
1339 cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh)
1340 {
1341         struct crypt_kop kop;
1342         int dhret = 1;
1343         int fd, keylen;
1344
1345         if ((fd = get_asym_dev_crypto()) < 0) {
1346                 const DH_METHOD *meth = DH_OpenSSL();
1347
1348                 return ((meth->compute_key)(key, pub_key, dh));
1349         }
1350
1351         keylen = BN_num_bits(dh->p);
1352
1353         memset(&kop, 0, sizeof kop);
1354         kop.crk_op = CRK_DH_COMPUTE_KEY;
1355
1356         /* inputs: dh->priv_key pub_key dh->p key */
1357         if (bn2crparam(dh->priv_key, &kop.crk_param[0]))
1358                 goto err;
1359         if (bn2crparam(pub_key, &kop.crk_param[1]))
1360                 goto err;
1361         if (bn2crparam(dh->p, &kop.crk_param[2]))
1362                 goto err;
1363         kop.crk_iparams = 3;
1364
1365         kop.crk_param[3].crp_p = (caddr_t) key;
1366         kop.crk_param[3].crp_nbits = keylen * 8;
1367         kop.crk_oparams = 1;
1368
1369         if (ioctl(fd, CIOCKEY, &kop) == -1) {
1370                 const DH_METHOD *meth = DH_OpenSSL();
1371
1372                 dhret = (meth->compute_key)(key, pub_key, dh);
1373         }
1374 err:
1375         kop.crk_param[3].crp_p = NULL;
1376         zapparams(&kop);
1377         return (dhret);
1378 }
1379
1380 static DH_METHOD cryptodev_dh = {
1381         "cryptodev DH method",
1382         NULL,                           /* cryptodev_dh_generate_key */
1383         NULL,
1384         NULL,
1385         NULL,
1386         NULL,
1387         0,      /* flags */
1388         NULL    /* app_data */
1389 };
1390
1391 /*
1392  * ctrl right now is just a wrapper that doesn't do much
1393  * but I expect we'll want some options soon.
1394  */
1395 static int
1396 cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void))
1397 {
1398 #ifdef HAVE_SYSLOG_R
1399         struct syslog_data sd = SYSLOG_DATA_INIT;
1400 #endif
1401
1402         switch (cmd) {
1403         default:
1404 #ifdef HAVE_SYSLOG_R
1405                 syslog_r(LOG_ERR, &sd,
1406                     "cryptodev_ctrl: unknown command %d", cmd);
1407 #else
1408                 syslog(LOG_ERR, "cryptodev_ctrl: unknown command %d", cmd);
1409 #endif
1410                 break;
1411         }
1412         return (1);
1413 }
1414
1415 void
1416 ENGINE_load_cryptodev(void)
1417 {
1418         ENGINE *engine = ENGINE_new();
1419         int fd;
1420
1421         if (engine == NULL)
1422                 return;
1423         if ((fd = get_dev_crypto()) < 0) {
1424                 ENGINE_free(engine);
1425                 return;
1426         }
1427
1428         /*
1429          * find out what asymmetric crypto algorithms we support
1430          */
1431         if (ioctl(fd, CIOCASYMFEAT, &cryptodev_asymfeat) == -1) {
1432                 put_dev_crypto(fd);
1433                 ENGINE_free(engine);
1434                 return;
1435         }
1436         put_dev_crypto(fd);
1437
1438         if (!ENGINE_set_id(engine, "cryptodev") ||
1439             !ENGINE_set_name(engine, "BSD cryptodev engine") ||
1440             !ENGINE_set_ciphers(engine, cryptodev_engine_ciphers) ||
1441             !ENGINE_set_digests(engine, cryptodev_engine_digests) ||
1442             !ENGINE_set_ctrl_function(engine, cryptodev_ctrl) ||
1443             !ENGINE_set_cmd_defns(engine, cryptodev_defns)) {
1444                 ENGINE_free(engine);
1445                 return;
1446         }
1447
1448         if (ENGINE_set_RSA(engine, &cryptodev_rsa)) {
1449                 const RSA_METHOD *rsa_meth = RSA_PKCS1_SSLeay();
1450
1451                 cryptodev_rsa.bn_mod_exp = rsa_meth->bn_mod_exp;
1452                 cryptodev_rsa.rsa_mod_exp = rsa_meth->rsa_mod_exp;
1453                 cryptodev_rsa.rsa_pub_enc = rsa_meth->rsa_pub_enc;
1454                 cryptodev_rsa.rsa_pub_dec = rsa_meth->rsa_pub_dec;
1455                 cryptodev_rsa.rsa_priv_enc = rsa_meth->rsa_priv_enc;
1456                 cryptodev_rsa.rsa_priv_dec = rsa_meth->rsa_priv_dec;
1457                 if (cryptodev_asymfeat & CRF_MOD_EXP) {
1458                         cryptodev_rsa.bn_mod_exp = cryptodev_bn_mod_exp;
1459                         if (cryptodev_asymfeat & CRF_MOD_EXP_CRT)
1460                                 cryptodev_rsa.rsa_mod_exp =
1461                                     cryptodev_rsa_mod_exp;
1462                         else
1463                                 cryptodev_rsa.rsa_mod_exp =
1464                                     cryptodev_rsa_nocrt_mod_exp;
1465                 }
1466         }
1467
1468         if (ENGINE_set_DSA(engine, &cryptodev_dsa)) {
1469                 const DSA_METHOD *meth = DSA_OpenSSL();
1470
1471                 memcpy(&cryptodev_dsa, meth, sizeof(DSA_METHOD));
1472                 if (cryptodev_asymfeat & CRF_DSA_SIGN)
1473                         cryptodev_dsa.dsa_do_sign = cryptodev_dsa_do_sign;
1474                 if (cryptodev_asymfeat & CRF_MOD_EXP) {
1475                         cryptodev_dsa.bn_mod_exp = cryptodev_dsa_bn_mod_exp;
1476                         cryptodev_dsa.dsa_mod_exp = cryptodev_dsa_dsa_mod_exp;
1477                 }
1478                 if (cryptodev_asymfeat & CRF_DSA_VERIFY)
1479                         cryptodev_dsa.dsa_do_verify = cryptodev_dsa_verify;
1480         }
1481
1482         if (ENGINE_set_DH(engine, &cryptodev_dh)){
1483                 const DH_METHOD *dh_meth = DH_OpenSSL();
1484
1485                 cryptodev_dh.generate_key = dh_meth->generate_key;
1486                 cryptodev_dh.compute_key = dh_meth->compute_key;
1487                 cryptodev_dh.bn_mod_exp = dh_meth->bn_mod_exp;
1488                 if (cryptodev_asymfeat & CRF_MOD_EXP) {
1489                         cryptodev_dh.bn_mod_exp = cryptodev_mod_exp_dh;
1490                         if (cryptodev_asymfeat & CRF_DH_COMPUTE_KEY)
1491                                 cryptodev_dh.compute_key =
1492                                     cryptodev_dh_compute_key;
1493                 }
1494         }
1495
1496         ENGINE_add(engine);
1497         ENGINE_free(engine);
1498         ERR_clear_error();
1499 }
1500
1501 #endif /* HAVE_CRYPTODEV */