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