Remove another lock from e_chil
[openssl.git] / engines / e_chil.c
1 /*
2  * Written by Richard Levitte (richard@levitte.org), Geoff Thorpe
3  * (geoff@geoffthorpe.net) and Dr Stephen N Henson (steve@openssl.org) for
4  * the OpenSSL project 2000.
5  */
6 /* ====================================================================
7  * Copyright (c) 1999-2001 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    licensing@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59
60 #include <stdio.h>
61 #include <string.h>
62 #include <openssl/crypto.h>
63 #include <openssl/pem.h>
64 #include <openssl/dso.h>
65 #include <openssl/engine.h>
66 #include <openssl/ui.h>
67 #include <openssl/rand.h>
68 #ifndef OPENSSL_NO_RSA
69 # include <openssl/rsa.h>
70 #endif
71 #ifndef OPENSSL_NO_DH
72 # include <openssl/dh.h>
73 #endif
74 #include <openssl/bn.h>
75
76 #ifndef OPENSSL_NO_HW
77 # ifndef OPENSSL_NO_HW_CHIL
78
79 /*-
80  * Attribution notice: nCipher have said several times that it's OK for
81  * us to implement a general interface to their boxes, and recently declared
82  * their HWCryptoHook to be public, and therefore available for us to use.
83  * Thanks, nCipher.
84  *
85  * The hwcryptohook.h included here is from May 2000.
86  * [Richard Levitte]
87  */
88 #  ifdef FLAT_INC
89 #   include "hwcryptohook.h"
90 #  else
91 #   include "vendor_defns/hwcryptohook.h"
92 #  endif
93
94 #  define HWCRHK_LIB_NAME "CHIL engine"
95 #  include "e_chil_err.c"
96
97 static CRYPTO_RWLOCK *chil_lock;
98
99 static int hwcrhk_destroy(ENGINE *e);
100 static int hwcrhk_init(ENGINE *e);
101 static int hwcrhk_finish(ENGINE *e);
102 static int hwcrhk_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void));
103
104 /* Functions to handle mutexes */
105 static int hwcrhk_mutex_init(HWCryptoHook_Mutex *,
106                              HWCryptoHook_CallerContext *);
107 static int hwcrhk_mutex_lock(HWCryptoHook_Mutex *);
108 static void hwcrhk_mutex_unlock(HWCryptoHook_Mutex *);
109 static void hwcrhk_mutex_destroy(HWCryptoHook_Mutex *);
110
111 /* BIGNUM stuff */
112 static int hwcrhk_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
113                           const BIGNUM *m, BN_CTX *ctx);
114
115 #  ifndef OPENSSL_NO_RSA
116 /* RSA stuff */
117 static int hwcrhk_rsa_mod_exp(BIGNUM *r, const BIGNUM *I, RSA *rsa,
118                               BN_CTX *ctx);
119 /* This function is aliased to mod_exp (with the mont stuff dropped). */
120 static int hwcrhk_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
121                                const BIGNUM *m, BN_CTX *ctx,
122                                BN_MONT_CTX *m_ctx);
123 static int hwcrhk_rsa_finish(RSA *rsa);
124 #  endif
125
126 #  ifndef OPENSSL_NO_DH
127 /* DH stuff */
128 /* This function is alised to mod_exp (with the DH and mont dropped). */
129 static int hwcrhk_mod_exp_dh(const DH *dh, BIGNUM *r,
130                              const BIGNUM *a, const BIGNUM *p,
131                              const BIGNUM *m, BN_CTX *ctx,
132                              BN_MONT_CTX *m_ctx);
133 #  endif
134
135 /* RAND stuff */
136 static int hwcrhk_rand_bytes(unsigned char *buf, int num);
137 static int hwcrhk_rand_status(void);
138
139 /* KM stuff */
140 static EVP_PKEY *hwcrhk_load_privkey(ENGINE *eng, const char *key_id,
141                                      UI_METHOD *ui_method,
142                                      void *callback_data);
143 static EVP_PKEY *hwcrhk_load_pubkey(ENGINE *eng, const char *key_id,
144                                     UI_METHOD *ui_method,
145                                     void *callback_data);
146
147 /* Interaction stuff */
148 static int hwcrhk_insert_card(const char *prompt_info,
149                               const char *wrong_info,
150                               HWCryptoHook_PassphraseContext * ppctx,
151                               HWCryptoHook_CallerContext * cactx);
152 static int hwcrhk_get_pass(const char *prompt_info,
153                            int *len_io, char *buf,
154                            HWCryptoHook_PassphraseContext * ppctx,
155                            HWCryptoHook_CallerContext * cactx);
156 static void hwcrhk_log_message(void *logstr, const char *message);
157
158 /* The definitions for control commands specific to this engine */
159 #  define HWCRHK_CMD_SO_PATH              ENGINE_CMD_BASE
160 #  define HWCRHK_CMD_FORK_CHECK           (ENGINE_CMD_BASE + 1)
161 #  define HWCRHK_CMD_THREAD_LOCKING       (ENGINE_CMD_BASE + 2)
162 #  define HWCRHK_CMD_SET_USER_INTERFACE   (ENGINE_CMD_BASE + 3)
163 #  define HWCRHK_CMD_SET_CALLBACK_DATA    (ENGINE_CMD_BASE + 4)
164 static const ENGINE_CMD_DEFN hwcrhk_cmd_defns[] = {
165     {HWCRHK_CMD_SO_PATH,
166      "SO_PATH",
167      "Specifies the path to the 'hwcrhk' shared library",
168      ENGINE_CMD_FLAG_STRING},
169     {HWCRHK_CMD_FORK_CHECK,
170      "FORK_CHECK",
171      "Turns fork() checking on (non-zero) or off (zero)",
172      ENGINE_CMD_FLAG_NUMERIC},
173     {HWCRHK_CMD_THREAD_LOCKING,
174      "THREAD_LOCKING",
175      "Turns thread-safe locking on (zero) or off (non-zero)",
176      ENGINE_CMD_FLAG_NUMERIC},
177     {HWCRHK_CMD_SET_USER_INTERFACE,
178      "SET_USER_INTERFACE",
179      "Set the global user interface (internal)",
180      ENGINE_CMD_FLAG_INTERNAL},
181     {HWCRHK_CMD_SET_CALLBACK_DATA,
182      "SET_CALLBACK_DATA",
183      "Set the global user interface extra data (internal)",
184      ENGINE_CMD_FLAG_INTERNAL},
185     {0, NULL, NULL, 0}
186 };
187
188 #  ifndef OPENSSL_NO_RSA
189 /* Our internal RSA_METHOD that we provide pointers to */
190 static RSA_METHOD hwcrhk_rsa = {
191     "CHIL RSA method",
192     NULL,
193     NULL,
194     NULL,
195     NULL,
196     hwcrhk_rsa_mod_exp,
197     hwcrhk_mod_exp_mont,
198     NULL,
199     hwcrhk_rsa_finish,
200     0,
201     NULL,
202     NULL,
203     NULL,
204     NULL
205 };
206 #  endif
207
208 #  ifndef OPENSSL_NO_DH
209 /* Our internal DH_METHOD that we provide pointers to */
210 static DH_METHOD hwcrhk_dh = {
211     "CHIL DH method",
212     NULL,
213     NULL,
214     hwcrhk_mod_exp_dh,
215     NULL,
216     NULL,
217     0,
218     NULL,
219     NULL
220 };
221 #  endif
222
223 static RAND_METHOD hwcrhk_rand = {
224     /* "CHIL RAND method", */
225     NULL,
226     hwcrhk_rand_bytes,
227     NULL,
228     NULL,
229     hwcrhk_rand_bytes,
230     hwcrhk_rand_status,
231 };
232
233 /* Constants used when creating the ENGINE */
234 static const char *engine_hwcrhk_id = "chil";
235 static const char *engine_hwcrhk_name = "CHIL hardware engine support";
236 #  ifndef OPENSSL_NO_DYNAMIC_ENGINE
237 /* Compatibility hack, the dynamic library uses this form in the path */
238 static const char *engine_hwcrhk_id_alt = "ncipher";
239 #  endif
240
241 /* Internal stuff for HWCryptoHook */
242
243 /* Some structures needed for proper use of thread locks */
244 /*
245  * hwcryptohook.h has some typedefs that turn struct HWCryptoHook_MutexValue
246  * into HWCryptoHook_Mutex
247  */
248 struct HWCryptoHook_MutexValue {
249     int lockid;
250 };
251
252 /*
253  * hwcryptohook.h has some typedefs that turn struct
254  * HWCryptoHook_PassphraseContextValue into HWCryptoHook_PassphraseContext
255  */
256 struct HWCryptoHook_PassphraseContextValue {
257     UI_METHOD *ui_method;
258     void *callback_data;
259 };
260
261 /*
262  * hwcryptohook.h has some typedefs that turn struct
263  * HWCryptoHook_CallerContextValue into HWCryptoHook_CallerContext
264  */
265 struct HWCryptoHook_CallerContextValue {
266     pem_password_cb *password_callback; /* Deprecated! Only present for
267                                          * backward compatibility! */
268     UI_METHOD *ui_method;
269     void *callback_data;
270 };
271
272 /*
273  * The MPI structure in HWCryptoHook is pretty compatible with OpenSSL
274  * BIGNUM's, so lets define a couple of conversion macros
275  */
276 #  define BN2MPI(mp, bn) \
277     {mp.size = bn->top * sizeof(BN_ULONG); mp.buf = (unsigned char *)bn->d;}
278 #  define MPI2BN(bn, mp) \
279     {mp.size = bn->dmax * sizeof(BN_ULONG); mp.buf = (unsigned char *)bn->d;}
280
281 static BIO *logstream = NULL;
282 static int disable_mutex_callbacks = 0;
283
284 /*
285  * One might wonder why these are needed, since one can pass down at least a
286  * UI_METHOD and a pointer to callback data to the key-loading functions. The
287  * thing is that the ModExp and RSAImmed functions can load keys as well, if
288  * the data they get is in a special, nCipher-defined format (hint: if you
289  * look at the private exponent of the RSA data as a string, you'll see this
290  * string: "nCipher KM tool key id", followed by some bytes, followed a key
291  * identity string, followed by more bytes.  This happens when you use
292  * "embed" keys instead of "hwcrhk" keys).  Unfortunately, those functions do
293  * not take any passphrase or caller context, and our functions can't really
294  * take any callback data either.  Still, the "insert_card" and
295  * "get_passphrase" callbacks may be called down the line, and will need to
296  * know what user interface callbacks to call, and having callback data from
297  * the application may be a nice thing as well, so we need to keep track of
298  * that globally.
299  */
300 static HWCryptoHook_CallerContext password_context = { NULL, NULL, NULL };
301
302 /* Stuff to pass to the HWCryptoHook library */
303 static HWCryptoHook_InitInfo hwcrhk_globals = {
304     HWCryptoHook_InitFlags_SimpleForkCheck, /* Flags */
305     &logstream,                 /* logstream */
306     sizeof(BN_ULONG),           /* limbsize */
307     0,                          /* mslimb first: false for BNs */
308     -1,                         /* msbyte first: use native */
309     0,                          /* Max mutexes, 0 = no small limit */
310     0,                          /* Max simultaneous, 0 = default */
311
312     /*
313      * The next few are mutex stuff: we write wrapper functions around the OS
314      * mutex functions.  We initialise them to 0 here, and change that to
315      * actual function pointers in hwcrhk_init() if dynamic locks are
316      * supported (that is, if the application programmer has made sure of
317      * setting up callbacks bafore starting this engine) *and* if
318      * disable_mutex_callbacks hasn't been set by a call to
319      * ENGINE_ctrl(ENGINE_CTRL_CHIL_NO_LOCKING).
320      */
321     sizeof(HWCryptoHook_Mutex),
322     0,
323     0,
324     0,
325     0,
326
327     /*
328      * The next few are condvar stuff: we write wrapper functions round the
329      * OS functions.  Currently not implemented and not and absolute
330      * necessity even in threaded programs, therefore 0'ed.  Will hopefully
331      * be implemented some day, since it enhances the efficiency of
332      * HWCryptoHook.
333      */
334     0,                          /* sizeof(HWCryptoHook_CondVar), */
335     0,                          /* hwcrhk_cv_init, */
336     0,                          /* hwcrhk_cv_wait, */
337     0,                          /* hwcrhk_cv_signal, */
338     0,                          /* hwcrhk_cv_broadcast, */
339     0,                          /* hwcrhk_cv_destroy, */
340
341     hwcrhk_get_pass,            /* pass phrase */
342     hwcrhk_insert_card,         /* insert a card */
343     hwcrhk_log_message          /* Log message */
344 };
345
346 /* Now, to our own code */
347
348 /*
349  * This internal function is used by ENGINE_chil() and possibly by the
350  * "dynamic" ENGINE support too
351  */
352 static int bind_helper(ENGINE *e)
353 {
354 #  ifndef OPENSSL_NO_RSA
355     const RSA_METHOD *meth1;
356 #  endif
357 #  ifndef OPENSSL_NO_DH
358     const DH_METHOD *meth2;
359 #  endif
360
361     chil_lock = CRYPTO_THREAD_lock_new();
362     if (chil_lock == NULL)
363         return 0;
364
365     if (!ENGINE_set_id(e, engine_hwcrhk_id) ||
366         !ENGINE_set_name(e, engine_hwcrhk_name) ||
367 #  ifndef OPENSSL_NO_RSA
368         !ENGINE_set_RSA(e, &hwcrhk_rsa) ||
369 #  endif
370 #  ifndef OPENSSL_NO_DH
371         !ENGINE_set_DH(e, &hwcrhk_dh) ||
372 #  endif
373         !ENGINE_set_RAND(e, &hwcrhk_rand) ||
374         !ENGINE_set_destroy_function(e, hwcrhk_destroy) ||
375         !ENGINE_set_init_function(e, hwcrhk_init) ||
376         !ENGINE_set_finish_function(e, hwcrhk_finish) ||
377         !ENGINE_set_ctrl_function(e, hwcrhk_ctrl) ||
378         !ENGINE_set_load_privkey_function(e, hwcrhk_load_privkey) ||
379         !ENGINE_set_load_pubkey_function(e, hwcrhk_load_pubkey) ||
380         !ENGINE_set_cmd_defns(e, hwcrhk_cmd_defns))
381         return 0;
382
383 #  ifndef OPENSSL_NO_RSA
384     /*
385      * We know that the "PKCS1_OpenSSL()" functions hook properly to the
386      * cswift-specific mod_exp and mod_exp_crt so we use those functions. NB:
387      * We don't use ENGINE_openssl() or anything "more generic" because
388      * something like the RSAref code may not hook properly, and if you own
389      * one of these cards then you have the right to do RSA operations on it
390      * anyway!
391      */
392     meth1 = RSA_PKCS1_OpenSSL();
393     hwcrhk_rsa.rsa_pub_enc = meth1->rsa_pub_enc;
394     hwcrhk_rsa.rsa_pub_dec = meth1->rsa_pub_dec;
395     hwcrhk_rsa.rsa_priv_enc = meth1->rsa_priv_enc;
396     hwcrhk_rsa.rsa_priv_dec = meth1->rsa_priv_dec;
397 #  endif
398
399 #  ifndef OPENSSL_NO_DH
400     /* Much the same for Diffie-Hellman */
401     meth2 = DH_OpenSSL();
402     hwcrhk_dh.generate_key = meth2->generate_key;
403     hwcrhk_dh.compute_key = meth2->compute_key;
404 #  endif
405
406     /* Ensure the hwcrhk error handling is set up */
407     ERR_load_HWCRHK_strings();
408
409     return 1;
410 }
411
412 #  ifdef OPENSSL_NO_DYNAMIC_ENGINE
413 static ENGINE *engine_chil(void)
414 {
415     ENGINE *ret = ENGINE_new();
416     if (ret == NULL)
417         return NULL;
418     if (!bind_helper(ret)) {
419         ENGINE_free(ret);
420         return NULL;
421     }
422     return ret;
423 }
424
425 void ENGINE_load_chil(void)
426 {
427     /* Copied from eng_[openssl|dyn].c */
428     ENGINE *toadd = engine_chil();
429     if (!toadd)
430         return;
431     ENGINE_add(toadd);
432     ENGINE_free(toadd);
433     ERR_clear_error();
434 }
435 #  endif
436
437 /*
438  * This is a process-global DSO handle used for loading and unloading the
439  * HWCryptoHook library. NB: This is only set (or unset) during an init() or
440  * finish() call (reference counts permitting) and they're operating with
441  * global locks, so this should be thread-safe implicitly.
442  */
443 static DSO *hwcrhk_dso = NULL;
444 static HWCryptoHook_ContextHandle hwcrhk_context = 0;
445 #  ifndef OPENSSL_NO_RSA
446 /* Index for KM handle.  Not really used yet. */
447 static int hndidx_rsa = -1;
448 #  endif
449
450 /*
451  * These are the function pointers that are (un)set when the library has
452  * successfully (un)loaded.
453  */
454 static HWCryptoHook_Init_t *p_hwcrhk_Init = NULL;
455 static HWCryptoHook_Finish_t *p_hwcrhk_Finish = NULL;
456 static HWCryptoHook_ModExp_t *p_hwcrhk_ModExp = NULL;
457 #  ifndef OPENSSL_NO_RSA
458 static HWCryptoHook_RSA_t *p_hwcrhk_RSA = NULL;
459 #  endif
460 static HWCryptoHook_RandomBytes_t *p_hwcrhk_RandomBytes = NULL;
461 #  ifndef OPENSSL_NO_RSA
462 static HWCryptoHook_RSALoadKey_t *p_hwcrhk_RSALoadKey = NULL;
463 static HWCryptoHook_RSAGetPublicKey_t *p_hwcrhk_RSAGetPublicKey = NULL;
464 static HWCryptoHook_RSAUnloadKey_t *p_hwcrhk_RSAUnloadKey = NULL;
465 #  endif
466 static HWCryptoHook_ModExpCRT_t *p_hwcrhk_ModExpCRT = NULL;
467
468 /* Used in the DSO operations. */
469 static const char *HWCRHK_LIBNAME = NULL;
470 static void free_HWCRHK_LIBNAME(void)
471 {
472     OPENSSL_free(HWCRHK_LIBNAME);
473     HWCRHK_LIBNAME = NULL;
474 }
475
476 static const char *get_HWCRHK_LIBNAME(void)
477 {
478     if (HWCRHK_LIBNAME)
479         return HWCRHK_LIBNAME;
480     return "nfhwcrhk";
481 }
482
483 static long set_HWCRHK_LIBNAME(const char *name)
484 {
485     free_HWCRHK_LIBNAME();
486     return (((HWCRHK_LIBNAME = OPENSSL_strdup(name)) != NULL) ? 1 : 0);
487 }
488
489 static const char *n_hwcrhk_Init = "HWCryptoHook_Init";
490 static const char *n_hwcrhk_Finish = "HWCryptoHook_Finish";
491 static const char *n_hwcrhk_ModExp = "HWCryptoHook_ModExp";
492 #  ifndef OPENSSL_NO_RSA
493 static const char *n_hwcrhk_RSA = "HWCryptoHook_RSA";
494 #  endif
495 static const char *n_hwcrhk_RandomBytes = "HWCryptoHook_RandomBytes";
496 #  ifndef OPENSSL_NO_RSA
497 static const char *n_hwcrhk_RSALoadKey = "HWCryptoHook_RSALoadKey";
498 static const char *n_hwcrhk_RSAGetPublicKey = "HWCryptoHook_RSAGetPublicKey";
499 static const char *n_hwcrhk_RSAUnloadKey = "HWCryptoHook_RSAUnloadKey";
500 #  endif
501 static const char *n_hwcrhk_ModExpCRT = "HWCryptoHook_ModExpCRT";
502
503 /*
504  * HWCryptoHook library functions and mechanics - these are used by the
505  * higher-level functions further down. NB: As and where there's no error
506  * checking, take a look lower down where these functions are called, the
507  * checking and error handling is probably down there.
508  */
509
510 /* utility function to obtain a context */
511 static int get_context(HWCryptoHook_ContextHandle * hac,
512                        HWCryptoHook_CallerContext * cac)
513 {
514     char tempbuf[1024];
515     HWCryptoHook_ErrMsgBuf rmsg;
516
517     rmsg.buf = tempbuf;
518     rmsg.size = sizeof(tempbuf);
519
520     *hac = p_hwcrhk_Init(&hwcrhk_globals, sizeof(hwcrhk_globals), &rmsg, cac);
521     if (!*hac)
522         return 0;
523     return 1;
524 }
525
526 /* similarly to release one. */
527 static void release_context(HWCryptoHook_ContextHandle hac)
528 {
529     p_hwcrhk_Finish(hac);
530 }
531
532 /* Destructor (complements the "ENGINE_chil()" constructor) */
533 static int hwcrhk_destroy(ENGINE *e)
534 {
535     free_HWCRHK_LIBNAME();
536     ERR_unload_HWCRHK_strings();
537     CRYPTO_THREAD_lock_free(chil_lock);
538     return 1;
539 }
540
541 /* (de)initialisation functions. */
542 static int hwcrhk_init(ENGINE *e)
543 {
544     HWCryptoHook_Init_t *p1;
545     HWCryptoHook_Finish_t *p2;
546     HWCryptoHook_ModExp_t *p3;
547 #  ifndef OPENSSL_NO_RSA
548     HWCryptoHook_RSA_t *p4;
549     HWCryptoHook_RSALoadKey_t *p5;
550     HWCryptoHook_RSAGetPublicKey_t *p6;
551     HWCryptoHook_RSAUnloadKey_t *p7;
552 #  endif
553     HWCryptoHook_RandomBytes_t *p8;
554     HWCryptoHook_ModExpCRT_t *p9;
555
556     if (hwcrhk_dso != NULL) {
557         HWCRHKerr(HWCRHK_F_HWCRHK_INIT, HWCRHK_R_ALREADY_LOADED);
558         goto err;
559     }
560     /* Attempt to load libnfhwcrhk.so/nfhwcrhk.dll/whatever. */
561     hwcrhk_dso = DSO_load(NULL, get_HWCRHK_LIBNAME(), NULL, 0);
562     if (hwcrhk_dso == NULL) {
563         HWCRHKerr(HWCRHK_F_HWCRHK_INIT, HWCRHK_R_DSO_FAILURE);
564         goto err;
565     }
566
567 #define BINDIT(t, name) (t *)DSO_bind_func(hwcrhk_dso, name)
568     if ((p1 = BINDIT(HWCryptoHook_Init_t, n_hwcrhk_Init)) == NULL
569         || (p2 = BINDIT(HWCryptoHook_Finish_t, n_hwcrhk_Finish)) == NULL
570         || (p3 = BINDIT(HWCryptoHook_ModExp_t, n_hwcrhk_ModExp)) == NULL
571 #  ifndef OPENSSL_NO_RSA
572         || (p4 = BINDIT(HWCryptoHook_RSA_t, n_hwcrhk_RSA)) == NULL
573         || (p5 = BINDIT(HWCryptoHook_RSALoadKey_t, n_hwcrhk_RSALoadKey)) == NULL
574         || (p6 = BINDIT(HWCryptoHook_RSAGetPublicKey_t, n_hwcrhk_RSAGetPublicKey)) == NULL
575         || (p7 = BINDIT(HWCryptoHook_RSAUnloadKey_t, n_hwcrhk_RSAUnloadKey)) == NULL
576 #  endif
577         || (p8 = BINDIT(HWCryptoHook_RandomBytes_t, n_hwcrhk_RandomBytes)) == NULL
578         || (p9 = BINDIT(HWCryptoHook_ModExpCRT_t, n_hwcrhk_ModExpCRT)) == NULL) {
579         HWCRHKerr(HWCRHK_F_HWCRHK_INIT, HWCRHK_R_DSO_FAILURE);
580         goto err;
581     }
582     /* Copy the pointers */
583     p_hwcrhk_Init = p1;
584     p_hwcrhk_Finish = p2;
585     p_hwcrhk_ModExp = p3;
586 #  ifndef OPENSSL_NO_RSA
587     p_hwcrhk_RSA = p4;
588     p_hwcrhk_RSALoadKey = p5;
589     p_hwcrhk_RSAGetPublicKey = p6;
590     p_hwcrhk_RSAUnloadKey = p7;
591 #  endif
592     p_hwcrhk_RandomBytes = p8;
593     p_hwcrhk_ModExpCRT = p9;
594
595     /*
596      * Check if the application decided to support dynamic locks, and if it
597      * does, use them.
598      */
599     if (disable_mutex_callbacks == 0) {
600         if (CRYPTO_get_dynlock_create_callback() != NULL &&
601             CRYPTO_get_dynlock_lock_callback() != NULL &&
602             CRYPTO_get_dynlock_destroy_callback() != NULL) {
603             hwcrhk_globals.mutex_init = hwcrhk_mutex_init;
604             hwcrhk_globals.mutex_acquire = hwcrhk_mutex_lock;
605             hwcrhk_globals.mutex_release = hwcrhk_mutex_unlock;
606             hwcrhk_globals.mutex_destroy = hwcrhk_mutex_destroy;
607         }
608     }
609
610     /*
611      * Try and get a context - if not, we may have a DSO but no accelerator!
612      */
613     if (!get_context(&hwcrhk_context, &password_context)) {
614         HWCRHKerr(HWCRHK_F_HWCRHK_INIT, HWCRHK_R_UNIT_FAILURE);
615         goto err;
616     }
617     /* Everything's fine. */
618 #  ifndef OPENSSL_NO_RSA
619     if (hndidx_rsa == -1)
620         hndidx_rsa = RSA_get_ex_new_index(0,
621                                           "nFast HWCryptoHook RSA key handle",
622                                           NULL, NULL, NULL);
623 #  endif
624     return 1;
625  err:
626     DSO_free(hwcrhk_dso);
627     hwcrhk_dso = NULL;
628     p_hwcrhk_Init = NULL;
629     p_hwcrhk_Finish = NULL;
630     p_hwcrhk_ModExp = NULL;
631 #  ifndef OPENSSL_NO_RSA
632     p_hwcrhk_RSA = NULL;
633     p_hwcrhk_RSALoadKey = NULL;
634     p_hwcrhk_RSAGetPublicKey = NULL;
635     p_hwcrhk_RSAUnloadKey = NULL;
636 #  endif
637     p_hwcrhk_ModExpCRT = NULL;
638     p_hwcrhk_RandomBytes = NULL;
639     return 0;
640 }
641
642 static int hwcrhk_finish(ENGINE *e)
643 {
644     int to_return = 1;
645     free_HWCRHK_LIBNAME();
646     if (hwcrhk_dso == NULL) {
647         HWCRHKerr(HWCRHK_F_HWCRHK_FINISH, HWCRHK_R_NOT_LOADED);
648         to_return = 0;
649         goto err;
650     }
651     release_context(hwcrhk_context);
652     if (!DSO_free(hwcrhk_dso)) {
653         HWCRHKerr(HWCRHK_F_HWCRHK_FINISH, HWCRHK_R_DSO_FAILURE);
654         to_return = 0;
655         goto err;
656     }
657  err:
658     BIO_free(logstream);
659     hwcrhk_dso = NULL;
660     p_hwcrhk_Init = NULL;
661     p_hwcrhk_Finish = NULL;
662     p_hwcrhk_ModExp = NULL;
663 #  ifndef OPENSSL_NO_RSA
664     p_hwcrhk_RSA = NULL;
665     p_hwcrhk_RSALoadKey = NULL;
666     p_hwcrhk_RSAGetPublicKey = NULL;
667     p_hwcrhk_RSAUnloadKey = NULL;
668 #  endif
669     p_hwcrhk_ModExpCRT = NULL;
670     p_hwcrhk_RandomBytes = NULL;
671     return to_return;
672 }
673
674 static int hwcrhk_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
675 {
676     int to_return = 1;
677
678     switch (cmd) {
679     case HWCRHK_CMD_SO_PATH:
680         if (hwcrhk_dso) {
681             HWCRHKerr(HWCRHK_F_HWCRHK_CTRL, HWCRHK_R_ALREADY_LOADED);
682             return 0;
683         }
684         if (p == NULL) {
685             HWCRHKerr(HWCRHK_F_HWCRHK_CTRL, ERR_R_PASSED_NULL_PARAMETER);
686             return 0;
687         }
688         return set_HWCRHK_LIBNAME((const char *)p);
689     case ENGINE_CTRL_SET_LOGSTREAM:
690         {
691             BIO *bio = (BIO *)p;
692
693             CRYPTO_THREAD_write_lock(chil_lock);
694             BIO_free(logstream);
695             logstream = NULL;
696             if (BIO_up_ref(bio)
697                 logstream = bio;
698             else
699                 HWCRHKerr(HWCRHK_F_HWCRHK_CTRL, HWCRHK_R_BIO_WAS_FREED);
700         }
701         CRYPTO_THREAD_unlock(chil_lock);
702         break;
703     case ENGINE_CTRL_SET_PASSWORD_CALLBACK:
704         CRYPTO_THREAD_write_lock(chil_lock);
705         password_context.password_callback = (pem_password_cb *)f;
706         CRYPTO_THREAD_unlock(chil_lock);
707         break;
708     case ENGINE_CTRL_SET_USER_INTERFACE:
709     case HWCRHK_CMD_SET_USER_INTERFACE:
710         CRYPTO_THREAD_write_lock(chil_lock);
711         password_context.ui_method = (UI_METHOD *)p;
712         CRYPTO_THREAD_unlock(chil_lock);
713         break;
714     case ENGINE_CTRL_SET_CALLBACK_DATA:
715     case HWCRHK_CMD_SET_CALLBACK_DATA:
716         CRYPTO_THREAD_write_lock(chil_lock);
717         password_context.callback_data = p;
718         CRYPTO_THREAD_unlock(chil_lock);
719         break;
720         /*
721          * this enables or disables the "SimpleForkCheck" flag used in the
722          * initialisation structure.
723          */
724     case ENGINE_CTRL_CHIL_SET_FORKCHECK:
725     case HWCRHK_CMD_FORK_CHECK:
726         CRYPTO_THREAD_write_lock(chil_lock);
727         if (i)
728             hwcrhk_globals.flags |= HWCryptoHook_InitFlags_SimpleForkCheck;
729         else
730             hwcrhk_globals.flags &= ~HWCryptoHook_InitFlags_SimpleForkCheck;
731         CRYPTO_THREAD_unlock(chil_lock);
732         break;
733         /*
734          * This will prevent the initialisation function from "installing"
735          * the mutex-handling callbacks, even if they are available from
736          * within the library (or were provided to the library from the
737          * calling application). This is to remove any baggage for
738          * applications not using multithreading.
739          */
740     case ENGINE_CTRL_CHIL_NO_LOCKING:
741         CRYPTO_THREAD_write_lock(chil_lock);
742         disable_mutex_callbacks = 1;
743         CRYPTO_THREAD_unlock(chil_lock);
744         break;
745     case HWCRHK_CMD_THREAD_LOCKING:
746         CRYPTO_THREAD_write_lock(chil_lock);
747         disable_mutex_callbacks = ((i == 0) ? 0 : 1);
748         CRYPTO_THREAD_unlock(chil_lock);
749         break;
750
751         /* The command isn't understood by this engine */
752     default:
753         HWCRHKerr(HWCRHK_F_HWCRHK_CTRL,
754                   HWCRHK_R_CTRL_COMMAND_NOT_IMPLEMENTED);
755         to_return = 0;
756         break;
757     }
758
759     return to_return;
760 }
761
762 static EVP_PKEY *hwcrhk_load_privkey(ENGINE *eng, const char *key_id,
763                                      UI_METHOD *ui_method,
764                                      void *callback_data)
765 {
766 #  ifndef OPENSSL_NO_RSA
767     RSA *rtmp = NULL;
768 #  endif
769     EVP_PKEY *res = NULL;
770 #  ifndef OPENSSL_NO_RSA
771     HWCryptoHook_MPI e, n;
772     HWCryptoHook_RSAKeyHandle *hptr;
773 #  endif
774 #  if !defined(OPENSSL_NO_RSA)
775     char tempbuf[1024];
776     HWCryptoHook_ErrMsgBuf rmsg;
777     HWCryptoHook_PassphraseContext ppctx;
778 #  endif
779
780 #  if !defined(OPENSSL_NO_RSA)
781     rmsg.buf = tempbuf;
782     rmsg.size = sizeof(tempbuf);
783 #  endif
784
785     if (!hwcrhk_context) {
786         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, HWCRHK_R_NOT_INITIALISED);
787         goto err;
788     }
789 #  ifndef OPENSSL_NO_RSA
790     hptr = OPENSSL_malloc(sizeof(*hptr));
791     if (hptr == NULL) {
792         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, ERR_R_MALLOC_FAILURE);
793         goto err;
794     }
795     ppctx.ui_method = ui_method;
796     ppctx.callback_data = callback_data;
797     if (p_hwcrhk_RSALoadKey(hwcrhk_context, key_id, hptr, &rmsg, &ppctx)) {
798         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, HWCRHK_R_CHIL_ERROR);
799         ERR_add_error_data(1, rmsg.buf);
800         goto err;
801     }
802     if (!*hptr) {
803         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, HWCRHK_R_NO_KEY);
804         goto err;
805     }
806 #  endif
807 #  ifndef OPENSSL_NO_RSA
808     rtmp = RSA_new_method(eng);
809     RSA_set_ex_data(rtmp, hndidx_rsa, (char *)hptr);
810     rtmp->e = BN_new();
811     rtmp->n = BN_new();
812     rtmp->flags |= RSA_FLAG_EXT_PKEY;
813     MPI2BN(rtmp->e, e);
814     MPI2BN(rtmp->n, n);
815     if (p_hwcrhk_RSAGetPublicKey(*hptr, &n, &e, &rmsg)
816         != HWCRYPTOHOOK_ERROR_MPISIZE) {
817         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, HWCRHK_R_CHIL_ERROR);
818         ERR_add_error_data(1, rmsg.buf);
819         goto err;
820     }
821
822     bn_expand2(rtmp->e, e.size / sizeof(BN_ULONG));
823     bn_expand2(rtmp->n, n.size / sizeof(BN_ULONG));
824     MPI2BN(rtmp->e, e);
825     MPI2BN(rtmp->n, n);
826
827     if (p_hwcrhk_RSAGetPublicKey(*hptr, &n, &e, &rmsg)) {
828         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, HWCRHK_R_CHIL_ERROR);
829         ERR_add_error_data(1, rmsg.buf);
830         goto err;
831     }
832     rtmp->e->top = e.size / sizeof(BN_ULONG);
833     bn_fix_top(rtmp->e);
834     rtmp->n->top = n.size / sizeof(BN_ULONG);
835     bn_fix_top(rtmp->n);
836
837     res = EVP_PKEY_new();
838     if (res == NULL) {
839         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, HWCRHK_R_CHIL_ERROR);
840         goto err;
841     }
842     EVP_PKEY_assign_RSA(res, rtmp);
843 #  endif
844
845     if (res == NULL)
846         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY,
847                   HWCRHK_R_PRIVATE_KEY_ALGORITHMS_DISABLED);
848
849     return res;
850  err:
851 #  ifndef OPENSSL_NO_RSA
852     RSA_free(rtmp);
853 #  endif
854     return NULL;
855 }
856
857 static EVP_PKEY *hwcrhk_load_pubkey(ENGINE *eng, const char *key_id,
858                                     UI_METHOD *ui_method, void *callback_data)
859 {
860     EVP_PKEY *res = NULL;
861
862 #  ifndef OPENSSL_NO_RSA
863     res = hwcrhk_load_privkey(eng, key_id, ui_method, callback_data);
864 #  endif
865
866     if (res)
867         switch (res->type) {
868 #  ifndef OPENSSL_NO_RSA
869         case EVP_PKEY_RSA:
870             {
871                 RSA *rsa = NULL;
872
873                 CRYPTO_THREAD_write_lock(chil_lock);
874                 rsa = res->pkey.rsa;
875                 res->pkey.rsa = RSA_new();
876                 res->pkey.rsa->n = rsa->n;
877                 res->pkey.rsa->e = rsa->e;
878                 rsa->n = NULL;
879                 rsa->e = NULL;
880                 CRYPTO_THREAD_unlock(chil_lock);
881                 RSA_free(rsa);
882             }
883             break;
884 #  endif
885         default:
886             HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PUBKEY,
887                       HWCRHK_R_CTRL_COMMAND_NOT_IMPLEMENTED);
888             goto err;
889         }
890
891     return res;
892  err:
893     EVP_PKEY_free(res);
894     return NULL;
895 }
896
897 /* A little mod_exp */
898 static int hwcrhk_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
899                           const BIGNUM *m, BN_CTX *ctx)
900 {
901     char tempbuf[1024];
902     HWCryptoHook_ErrMsgBuf rmsg;
903     /*
904      * Since HWCryptoHook_MPI is pretty compatible with BIGNUM's, we use them
905      * directly, plus a little macro magic.  We only thing we need to make
906      * sure of is that enough space is allocated.
907      */
908     HWCryptoHook_MPI m_a, m_p, m_n, m_r;
909     int to_return, ret;
910
911     to_return = 0;              /* expect failure */
912     rmsg.buf = tempbuf;
913     rmsg.size = sizeof(tempbuf);
914
915     if (!hwcrhk_context) {
916         HWCRHKerr(HWCRHK_F_HWCRHK_MOD_EXP, HWCRHK_R_NOT_INITIALISED);
917         goto err;
918     }
919     /* Prepare the params */
920     bn_expand2(r, m->top);      /* Check for error !! */
921     BN2MPI(m_a, a);
922     BN2MPI(m_p, p);
923     BN2MPI(m_n, m);
924     MPI2BN(r, m_r);
925
926     /* Perform the operation */
927     ret = p_hwcrhk_ModExp(hwcrhk_context, m_a, m_p, m_n, &m_r, &rmsg);
928
929     /* Convert the response */
930     r->top = m_r.size / sizeof(BN_ULONG);
931     bn_fix_top(r);
932
933     if (ret < 0) {
934         /*
935          * FIXME: When this error is returned, HWCryptoHook is telling us
936          * that falling back to software computation might be a good thing.
937          */
938         if (ret == HWCRYPTOHOOK_ERROR_FALLBACK) {
939             HWCRHKerr(HWCRHK_F_HWCRHK_MOD_EXP, HWCRHK_R_REQUEST_FALLBACK);
940         } else {
941             HWCRHKerr(HWCRHK_F_HWCRHK_MOD_EXP, HWCRHK_R_REQUEST_FAILED);
942         }
943         ERR_add_error_data(1, rmsg.buf);
944         goto err;
945     }
946
947     to_return = 1;
948  err:
949     return to_return;
950 }
951
952 #  ifndef OPENSSL_NO_RSA
953 static int hwcrhk_rsa_mod_exp(BIGNUM *r, const BIGNUM *I, RSA *rsa,
954                               BN_CTX *ctx)
955 {
956     char tempbuf[1024];
957     HWCryptoHook_ErrMsgBuf rmsg;
958     HWCryptoHook_RSAKeyHandle *hptr;
959     int to_return = 0, ret;
960
961     rmsg.buf = tempbuf;
962     rmsg.size = sizeof(tempbuf);
963
964     if (!hwcrhk_context) {
965         HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP, HWCRHK_R_NOT_INITIALISED);
966         goto err;
967     }
968
969     /*
970      * This provides support for nForce keys.  Since that's opaque data all
971      * we do is provide a handle to the proper key and let HWCryptoHook take
972      * care of the rest.
973      */
974     if ((hptr =
975          (HWCryptoHook_RSAKeyHandle *) RSA_get_ex_data(rsa, hndidx_rsa))
976         != NULL) {
977         HWCryptoHook_MPI m_a, m_r;
978
979         if (!rsa->n) {
980             HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP,
981                       HWCRHK_R_MISSING_KEY_COMPONENTS);
982             goto err;
983         }
984
985         /* Prepare the params */
986         bn_expand2(r, rsa->n->top); /* Check for error !! */
987         BN2MPI(m_a, I);
988         MPI2BN(r, m_r);
989
990         /* Perform the operation */
991         ret = p_hwcrhk_RSA(m_a, *hptr, &m_r, &rmsg);
992
993         /* Convert the response */
994         r->top = m_r.size / sizeof(BN_ULONG);
995         bn_fix_top(r);
996
997         if (ret < 0) {
998             /*
999              * FIXME: When this error is returned, HWCryptoHook is telling us
1000              * that falling back to software computation might be a good
1001              * thing.
1002              */
1003             if (ret == HWCRYPTOHOOK_ERROR_FALLBACK) {
1004                 HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP,
1005                           HWCRHK_R_REQUEST_FALLBACK);
1006             } else {
1007                 HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP,
1008                           HWCRHK_R_REQUEST_FAILED);
1009             }
1010             ERR_add_error_data(1, rmsg.buf);
1011             goto err;
1012         }
1013     } else {
1014         HWCryptoHook_MPI m_a, m_p, m_q, m_dmp1, m_dmq1, m_iqmp, m_r;
1015
1016         if (!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) {
1017             HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP,
1018                       HWCRHK_R_MISSING_KEY_COMPONENTS);
1019             goto err;
1020         }
1021
1022         /* Prepare the params */
1023         bn_expand2(r, rsa->n->top); /* Check for error !! */
1024         BN2MPI(m_a, I);
1025         BN2MPI(m_p, rsa->p);
1026         BN2MPI(m_q, rsa->q);
1027         BN2MPI(m_dmp1, rsa->dmp1);
1028         BN2MPI(m_dmq1, rsa->dmq1);
1029         BN2MPI(m_iqmp, rsa->iqmp);
1030         MPI2BN(r, m_r);
1031
1032         /* Perform the operation */
1033         ret = p_hwcrhk_ModExpCRT(hwcrhk_context, m_a, m_p, m_q,
1034                                  m_dmp1, m_dmq1, m_iqmp, &m_r, &rmsg);
1035
1036         /* Convert the response */
1037         r->top = m_r.size / sizeof(BN_ULONG);
1038         bn_fix_top(r);
1039
1040         if (ret < 0) {
1041             /*
1042              * FIXME: When this error is returned, HWCryptoHook is telling us
1043              * that falling back to software computation might be a good
1044              * thing.
1045              */
1046             if (ret == HWCRYPTOHOOK_ERROR_FALLBACK) {
1047                 HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP,
1048                           HWCRHK_R_REQUEST_FALLBACK);
1049             } else {
1050                 HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP,
1051                           HWCRHK_R_REQUEST_FAILED);
1052             }
1053             ERR_add_error_data(1, rmsg.buf);
1054             goto err;
1055         }
1056     }
1057     /*
1058      * If we're here, we must be here with some semblance of success :-)
1059      */
1060     to_return = 1;
1061  err:
1062     return to_return;
1063 }
1064 #  endif
1065
1066 #  ifndef OPENSSL_NO_RSA
1067 /* This function is aliased to mod_exp (with the mont stuff dropped). */
1068 static int hwcrhk_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
1069                                const BIGNUM *m, BN_CTX *ctx,
1070                                BN_MONT_CTX *m_ctx)
1071 {
1072     return hwcrhk_mod_exp(r, a, p, m, ctx);
1073 }
1074
1075 static int hwcrhk_rsa_finish(RSA *rsa)
1076 {
1077     HWCryptoHook_RSAKeyHandle *hptr;
1078
1079     hptr = RSA_get_ex_data(rsa, hndidx_rsa);
1080     if (hptr) {
1081         p_hwcrhk_RSAUnloadKey(*hptr, NULL);
1082         OPENSSL_free(hptr);
1083         RSA_set_ex_data(rsa, hndidx_rsa, NULL);
1084     }
1085     return 1;
1086 }
1087
1088 #  endif
1089
1090 #  ifndef OPENSSL_NO_DH
1091 /* This function is aliased to mod_exp (with the dh and mont dropped). */
1092 static int hwcrhk_mod_exp_dh(const DH *dh, BIGNUM *r,
1093                              const BIGNUM *a, const BIGNUM *p,
1094                              const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
1095 {
1096     return hwcrhk_mod_exp(r, a, p, m, ctx);
1097 }
1098 #  endif
1099
1100 /* Random bytes are good */
1101 static int hwcrhk_rand_bytes(unsigned char *buf, int num)
1102 {
1103     char tempbuf[1024];
1104     HWCryptoHook_ErrMsgBuf rmsg;
1105     int to_return = 0;          /* assume failure */
1106     int ret;
1107
1108     rmsg.buf = tempbuf;
1109     rmsg.size = sizeof(tempbuf);
1110
1111     if (!hwcrhk_context) {
1112         HWCRHKerr(HWCRHK_F_HWCRHK_RAND_BYTES, HWCRHK_R_NOT_INITIALISED);
1113         goto err;
1114     }
1115
1116     ret = p_hwcrhk_RandomBytes(hwcrhk_context, buf, num, &rmsg);
1117     if (ret < 0) {
1118         /*
1119          * FIXME: When this error is returned, HWCryptoHook is telling us
1120          * that falling back to software computation might be a good thing.
1121          */
1122         if (ret == HWCRYPTOHOOK_ERROR_FALLBACK) {
1123             HWCRHKerr(HWCRHK_F_HWCRHK_RAND_BYTES, HWCRHK_R_REQUEST_FALLBACK);
1124         } else {
1125             HWCRHKerr(HWCRHK_F_HWCRHK_RAND_BYTES, HWCRHK_R_REQUEST_FAILED);
1126         }
1127         ERR_add_error_data(1, rmsg.buf);
1128         goto err;
1129     }
1130     to_return = 1;
1131  err:
1132     return to_return;
1133 }
1134
1135 static int hwcrhk_rand_status(void)
1136 {
1137     return 1;
1138 }
1139
1140 /*
1141  * Mutex calls: since the HWCryptoHook model closely follows the POSIX model
1142  * these just wrap the POSIX functions and add some logging.
1143  */
1144
1145 static int hwcrhk_mutex_init(HWCryptoHook_Mutex * mt,
1146                              HWCryptoHook_CallerContext * cactx)
1147 {
1148     mt->lockid = CRYPTO_get_new_dynlockid();
1149     if (mt->lockid == 0)
1150         return 1;               /* failure */
1151     return 0;                   /* success */
1152 }
1153
1154 static int hwcrhk_mutex_lock(HWCryptoHook_Mutex * mt)
1155 {
1156     CRYPTO_w_lock(mt->lockid);
1157     return 0;
1158 }
1159
1160 static void hwcrhk_mutex_unlock(HWCryptoHook_Mutex * mt)
1161 {
1162     CRYPTO_w_unlock(mt->lockid);
1163 }
1164
1165 static void hwcrhk_mutex_destroy(HWCryptoHook_Mutex * mt)
1166 {
1167     CRYPTO_destroy_dynlockid(mt->lockid);
1168 }
1169
1170 static int hwcrhk_get_pass(const char *prompt_info,
1171                            int *len_io, char *buf,
1172                            HWCryptoHook_PassphraseContext * ppctx,
1173                            HWCryptoHook_CallerContext * cactx)
1174 {
1175     pem_password_cb *callback = NULL;
1176     void *callback_data = NULL;
1177     UI_METHOD *ui_method = NULL;
1178     /*
1179      * Despite what the documentation says prompt_info can be an empty
1180      * string.
1181      */
1182     if (prompt_info && !*prompt_info)
1183         prompt_info = NULL;
1184
1185     if (cactx) {
1186         if (cactx->ui_method)
1187             ui_method = cactx->ui_method;
1188         if (cactx->password_callback)
1189             callback = cactx->password_callback;
1190         if (cactx->callback_data)
1191             callback_data = cactx->callback_data;
1192     }
1193     if (ppctx) {
1194         if (ppctx->ui_method) {
1195             ui_method = ppctx->ui_method;
1196             callback = NULL;
1197         }
1198         if (ppctx->callback_data)
1199             callback_data = ppctx->callback_data;
1200     }
1201     if (callback == NULL && ui_method == NULL) {
1202         HWCRHKerr(HWCRHK_F_HWCRHK_GET_PASS, HWCRHK_R_NO_CALLBACK);
1203         return -1;
1204     }
1205
1206     if (ui_method) {
1207         UI *ui = UI_new_method(ui_method);
1208         if (ui) {
1209             int ok;
1210             char *prompt = UI_construct_prompt(ui,
1211                                                "pass phrase", prompt_info);
1212
1213             ok = UI_add_input_string(ui, prompt,
1214                                      UI_INPUT_FLAG_DEFAULT_PWD,
1215                                      buf, 0, (*len_io) - 1);
1216             UI_add_user_data(ui, callback_data);
1217             UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
1218
1219             if (ok >= 0)
1220                 do {
1221                     ok = UI_process(ui);
1222                 }
1223                 while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
1224
1225             if (ok >= 0)
1226                 *len_io = strlen(buf);
1227
1228             UI_free(ui);
1229             OPENSSL_free(prompt);
1230         }
1231     } else {
1232         *len_io = callback(buf, *len_io, 0, callback_data);
1233     }
1234     if (!*len_io)
1235         return -1;
1236     return 0;
1237 }
1238
1239 static int hwcrhk_insert_card(const char *prompt_info,
1240                               const char *wrong_info,
1241                               HWCryptoHook_PassphraseContext * ppctx,
1242                               HWCryptoHook_CallerContext * cactx)
1243 {
1244     int ok = -1;
1245     UI *ui;
1246     void *callback_data = NULL;
1247     UI_METHOD *ui_method = NULL;
1248
1249     if (cactx) {
1250         if (cactx->ui_method)
1251             ui_method = cactx->ui_method;
1252         if (cactx->callback_data)
1253             callback_data = cactx->callback_data;
1254     }
1255     if (ppctx) {
1256         if (ppctx->ui_method)
1257             ui_method = ppctx->ui_method;
1258         if (ppctx->callback_data)
1259             callback_data = ppctx->callback_data;
1260     }
1261     if (ui_method == NULL) {
1262         HWCRHKerr(HWCRHK_F_HWCRHK_INSERT_CARD, HWCRHK_R_NO_CALLBACK);
1263         return -1;
1264     }
1265
1266     ui = UI_new_method(ui_method);
1267
1268     if (ui) {
1269         char answer;
1270         char buf[BUFSIZ];
1271         /*
1272          * Despite what the documentation says wrong_info can be an empty
1273          * string.
1274          */
1275         if (wrong_info && *wrong_info)
1276             BIO_snprintf(buf, sizeof(buf) - 1,
1277                          "Current card: \"%s\"\n", wrong_info);
1278         else
1279             buf[0] = 0;
1280         ok = UI_dup_info_string(ui, buf);
1281         if (ok >= 0 && prompt_info) {
1282             BIO_snprintf(buf, sizeof(buf) - 1,
1283                          "Insert card \"%s\"", prompt_info);
1284             ok = UI_dup_input_boolean(ui, buf,
1285                                       "\n then hit <enter> or C<enter> to cancel\n",
1286                                       "\r\n", "Cc", UI_INPUT_FLAG_ECHO,
1287                                       &answer);
1288         }
1289         UI_add_user_data(ui, callback_data);
1290
1291         if (ok >= 0)
1292             ok = UI_process(ui);
1293         UI_free(ui);
1294
1295         if (ok == -2 || (ok >= 0 && answer == 'C'))
1296             ok = 1;
1297         else if (ok < 0)
1298             ok = -1;
1299         else
1300             ok = 0;
1301     }
1302     return ok;
1303 }
1304
1305 static void hwcrhk_log_message(void *logstr, const char *message)
1306 {
1307     BIO *lstream = NULL;
1308
1309     if (logstr)
1310         lstream = *(BIO **)logstr;
1311     if (lstream) {
1312         BIO_printf(lstream, "%s\n", message);
1313     }
1314 }
1315
1316 /*
1317  * This stuff is needed if this ENGINE is being compiled into a
1318  * self-contained shared-library.
1319  */
1320 #  ifndef OPENSSL_NO_DYNAMIC_ENGINE
1321 static int bind_fn(ENGINE *e, const char *id)
1322 {
1323     if (id && (strcmp(id, engine_hwcrhk_id) != 0) &&
1324         (strcmp(id, engine_hwcrhk_id_alt) != 0))
1325         return 0;
1326     if (!bind_helper(e))
1327         return 0;
1328     return 1;
1329 }
1330
1331 IMPLEMENT_DYNAMIC_CHECK_FN()
1332     IMPLEMENT_DYNAMIC_BIND_FN(bind_fn)
1333 #  endif                        /* OPENSSL_NO_DYNAMIC_ENGINE */
1334 # endif                         /* !OPENSSL_NO_HW_CHIL */
1335 #endif                          /* !OPENSSL_NO_HW */