Copyright consolidation 02/10
[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         return 0;
314
315     if (!ENGINE_set_id(e, engine_hwcrhk_id) ||
316         !ENGINE_set_name(e, engine_hwcrhk_name) ||
317 #  ifndef OPENSSL_NO_RSA
318         !ENGINE_set_RSA(e, &hwcrhk_rsa) ||
319 #  endif
320 #  ifndef OPENSSL_NO_DH
321         !ENGINE_set_DH(e, &hwcrhk_dh) ||
322 #  endif
323         !ENGINE_set_RAND(e, &hwcrhk_rand) ||
324         !ENGINE_set_destroy_function(e, hwcrhk_destroy) ||
325         !ENGINE_set_init_function(e, hwcrhk_init) ||
326         !ENGINE_set_finish_function(e, hwcrhk_finish) ||
327         !ENGINE_set_ctrl_function(e, hwcrhk_ctrl) ||
328         !ENGINE_set_load_privkey_function(e, hwcrhk_load_privkey) ||
329         !ENGINE_set_load_pubkey_function(e, hwcrhk_load_pubkey) ||
330         !ENGINE_set_cmd_defns(e, hwcrhk_cmd_defns))
331         return 0;
332
333 #  ifndef OPENSSL_NO_RSA
334     /*
335      * We know that the "PKCS1_OpenSSL()" functions hook properly to the
336      * cswift-specific mod_exp and mod_exp_crt so we use those functions. NB:
337      * We don't use ENGINE_openssl() or anything "more generic" because
338      * something like the RSAref code may not hook properly, and if you own
339      * one of these cards then you have the right to do RSA operations on it
340      * anyway!
341      */
342     meth1 = RSA_PKCS1_OpenSSL();
343     hwcrhk_rsa.rsa_pub_enc = meth1->rsa_pub_enc;
344     hwcrhk_rsa.rsa_pub_dec = meth1->rsa_pub_dec;
345     hwcrhk_rsa.rsa_priv_enc = meth1->rsa_priv_enc;
346     hwcrhk_rsa.rsa_priv_dec = meth1->rsa_priv_dec;
347 #  endif
348
349 #  ifndef OPENSSL_NO_DH
350     /* Much the same for Diffie-Hellman */
351     meth2 = DH_OpenSSL();
352     hwcrhk_dh.generate_key = meth2->generate_key;
353     hwcrhk_dh.compute_key = meth2->compute_key;
354 #  endif
355
356     /* Ensure the hwcrhk error handling is set up */
357     ERR_load_HWCRHK_strings();
358
359     return 1;
360 }
361
362 #  ifdef OPENSSL_NO_DYNAMIC_ENGINE
363 static ENGINE *engine_chil(void)
364 {
365     ENGINE *ret = ENGINE_new();
366     if (ret == NULL)
367         return NULL;
368     if (!bind_helper(ret)) {
369         ENGINE_free(ret);
370         return NULL;
371     }
372     return ret;
373 }
374
375 void ENGINE_load_chil(void)
376 {
377     /* Copied from eng_[openssl|dyn].c */
378     ENGINE *toadd = engine_chil();
379     if (!toadd)
380         return;
381     ENGINE_add(toadd);
382     ENGINE_free(toadd);
383     ERR_clear_error();
384 }
385 #  endif
386
387 /*
388  * This is a process-global DSO handle used for loading and unloading the
389  * HWCryptoHook library. NB: This is only set (or unset) during an init() or
390  * finish() call (reference counts permitting) and they're operating with
391  * global locks, so this should be thread-safe implicitly.
392  */
393 static DSO *hwcrhk_dso = NULL;
394 static HWCryptoHook_ContextHandle hwcrhk_context = 0;
395 #  ifndef OPENSSL_NO_RSA
396 /* Index for KM handle.  Not really used yet. */
397 static int hndidx_rsa = -1;
398 #  endif
399
400 /*
401  * These are the function pointers that are (un)set when the library has
402  * successfully (un)loaded.
403  */
404 static HWCryptoHook_Init_t *p_hwcrhk_Init = NULL;
405 static HWCryptoHook_Finish_t *p_hwcrhk_Finish = NULL;
406 static HWCryptoHook_ModExp_t *p_hwcrhk_ModExp = NULL;
407 #  ifndef OPENSSL_NO_RSA
408 static HWCryptoHook_RSA_t *p_hwcrhk_RSA = NULL;
409 #  endif
410 static HWCryptoHook_RandomBytes_t *p_hwcrhk_RandomBytes = NULL;
411 #  ifndef OPENSSL_NO_RSA
412 static HWCryptoHook_RSALoadKey_t *p_hwcrhk_RSALoadKey = NULL;
413 static HWCryptoHook_RSAGetPublicKey_t *p_hwcrhk_RSAGetPublicKey = NULL;
414 static HWCryptoHook_RSAUnloadKey_t *p_hwcrhk_RSAUnloadKey = NULL;
415 #  endif
416 static HWCryptoHook_ModExpCRT_t *p_hwcrhk_ModExpCRT = NULL;
417
418 /* Used in the DSO operations. */
419 static const char *HWCRHK_LIBNAME = NULL;
420 static void free_HWCRHK_LIBNAME(void)
421 {
422     OPENSSL_free(HWCRHK_LIBNAME);
423     HWCRHK_LIBNAME = NULL;
424 }
425
426 static const char *get_HWCRHK_LIBNAME(void)
427 {
428     if (HWCRHK_LIBNAME)
429         return HWCRHK_LIBNAME;
430     return "nfhwcrhk";
431 }
432
433 static long set_HWCRHK_LIBNAME(const char *name)
434 {
435     free_HWCRHK_LIBNAME();
436     return (((HWCRHK_LIBNAME = OPENSSL_strdup(name)) != NULL) ? 1 : 0);
437 }
438
439 static const char *n_hwcrhk_Init = "HWCryptoHook_Init";
440 static const char *n_hwcrhk_Finish = "HWCryptoHook_Finish";
441 static const char *n_hwcrhk_ModExp = "HWCryptoHook_ModExp";
442 #  ifndef OPENSSL_NO_RSA
443 static const char *n_hwcrhk_RSA = "HWCryptoHook_RSA";
444 #  endif
445 static const char *n_hwcrhk_RandomBytes = "HWCryptoHook_RandomBytes";
446 #  ifndef OPENSSL_NO_RSA
447 static const char *n_hwcrhk_RSALoadKey = "HWCryptoHook_RSALoadKey";
448 static const char *n_hwcrhk_RSAGetPublicKey = "HWCryptoHook_RSAGetPublicKey";
449 static const char *n_hwcrhk_RSAUnloadKey = "HWCryptoHook_RSAUnloadKey";
450 #  endif
451 static const char *n_hwcrhk_ModExpCRT = "HWCryptoHook_ModExpCRT";
452
453 /*
454  * HWCryptoHook library functions and mechanics - these are used by the
455  * higher-level functions further down. NB: As and where there's no error
456  * checking, take a look lower down where these functions are called, the
457  * checking and error handling is probably down there.
458  */
459
460 /* utility function to obtain a context */
461 static int get_context(HWCryptoHook_ContextHandle * hac,
462                        HWCryptoHook_CallerContext * cac)
463 {
464     char tempbuf[1024];
465     HWCryptoHook_ErrMsgBuf rmsg;
466
467     rmsg.buf = tempbuf;
468     rmsg.size = sizeof(tempbuf);
469
470     *hac = p_hwcrhk_Init(&hwcrhk_globals, sizeof(hwcrhk_globals), &rmsg, cac);
471     if (!*hac)
472         return 0;
473     return 1;
474 }
475
476 /* similarly to release one. */
477 static void release_context(HWCryptoHook_ContextHandle hac)
478 {
479     p_hwcrhk_Finish(hac);
480 }
481
482 /* Destructor (complements the "ENGINE_chil()" constructor) */
483 static int hwcrhk_destroy(ENGINE *e)
484 {
485     free_HWCRHK_LIBNAME();
486     ERR_unload_HWCRHK_strings();
487     CRYPTO_THREAD_lock_free(chil_lock);
488     return 1;
489 }
490
491 /* (de)initialisation functions. */
492 static int hwcrhk_init(ENGINE *e)
493 {
494     HWCryptoHook_Init_t *p1;
495     HWCryptoHook_Finish_t *p2;
496     HWCryptoHook_ModExp_t *p3;
497 #  ifndef OPENSSL_NO_RSA
498     HWCryptoHook_RSA_t *p4;
499     HWCryptoHook_RSALoadKey_t *p5;
500     HWCryptoHook_RSAGetPublicKey_t *p6;
501     HWCryptoHook_RSAUnloadKey_t *p7;
502 #  endif
503     HWCryptoHook_RandomBytes_t *p8;
504     HWCryptoHook_ModExpCRT_t *p9;
505
506     if (hwcrhk_dso != NULL) {
507         HWCRHKerr(HWCRHK_F_HWCRHK_INIT, HWCRHK_R_ALREADY_LOADED);
508         goto err;
509     }
510     /* Attempt to load libnfhwcrhk.so/nfhwcrhk.dll/whatever. */
511     hwcrhk_dso = DSO_load(NULL, get_HWCRHK_LIBNAME(), NULL, 0);
512     if (hwcrhk_dso == NULL) {
513         HWCRHKerr(HWCRHK_F_HWCRHK_INIT, HWCRHK_R_DSO_FAILURE);
514         goto err;
515     }
516
517 #define BINDIT(t, name) (t *)DSO_bind_func(hwcrhk_dso, name)
518     if ((p1 = BINDIT(HWCryptoHook_Init_t, n_hwcrhk_Init)) == NULL
519         || (p2 = BINDIT(HWCryptoHook_Finish_t, n_hwcrhk_Finish)) == NULL
520         || (p3 = BINDIT(HWCryptoHook_ModExp_t, n_hwcrhk_ModExp)) == NULL
521 #  ifndef OPENSSL_NO_RSA
522         || (p4 = BINDIT(HWCryptoHook_RSA_t, n_hwcrhk_RSA)) == NULL
523         || (p5 = BINDIT(HWCryptoHook_RSALoadKey_t, n_hwcrhk_RSALoadKey)) == NULL
524         || (p6 = BINDIT(HWCryptoHook_RSAGetPublicKey_t, n_hwcrhk_RSAGetPublicKey)) == NULL
525         || (p7 = BINDIT(HWCryptoHook_RSAUnloadKey_t, n_hwcrhk_RSAUnloadKey)) == NULL
526 #  endif
527         || (p8 = BINDIT(HWCryptoHook_RandomBytes_t, n_hwcrhk_RandomBytes)) == NULL
528         || (p9 = BINDIT(HWCryptoHook_ModExpCRT_t, n_hwcrhk_ModExpCRT)) == NULL) {
529         HWCRHKerr(HWCRHK_F_HWCRHK_INIT, HWCRHK_R_DSO_FAILURE);
530         goto err;
531     }
532     /* Copy the pointers */
533     p_hwcrhk_Init = p1;
534     p_hwcrhk_Finish = p2;
535     p_hwcrhk_ModExp = p3;
536 #  ifndef OPENSSL_NO_RSA
537     p_hwcrhk_RSA = p4;
538     p_hwcrhk_RSALoadKey = p5;
539     p_hwcrhk_RSAGetPublicKey = p6;
540     p_hwcrhk_RSAUnloadKey = p7;
541 #  endif
542     p_hwcrhk_RandomBytes = p8;
543     p_hwcrhk_ModExpCRT = p9;
544
545     /*
546      * Check if the application decided to support dynamic locks, and if it
547      * does, use them.
548      */
549     if (disable_mutex_callbacks == 0) {
550         hwcrhk_globals.mutex_init = hwcrhk_mutex_init;
551         hwcrhk_globals.mutex_acquire = hwcrhk_mutex_lock;
552         hwcrhk_globals.mutex_release = hwcrhk_mutex_unlock;
553         hwcrhk_globals.mutex_destroy = hwcrhk_mutex_destroy;
554     }
555
556     /*
557      * Try and get a context - if not, we may have a DSO but no accelerator!
558      */
559     if (!get_context(&hwcrhk_context, &password_context)) {
560         HWCRHKerr(HWCRHK_F_HWCRHK_INIT, HWCRHK_R_UNIT_FAILURE);
561         goto err;
562     }
563     /* Everything's fine. */
564 #  ifndef OPENSSL_NO_RSA
565     if (hndidx_rsa == -1)
566         hndidx_rsa = RSA_get_ex_new_index(0,
567                                           "nFast HWCryptoHook RSA key handle",
568                                           NULL, NULL, NULL);
569 #  endif
570     return 1;
571  err:
572     DSO_free(hwcrhk_dso);
573     hwcrhk_dso = NULL;
574     p_hwcrhk_Init = NULL;
575     p_hwcrhk_Finish = NULL;
576     p_hwcrhk_ModExp = NULL;
577 #  ifndef OPENSSL_NO_RSA
578     p_hwcrhk_RSA = NULL;
579     p_hwcrhk_RSALoadKey = NULL;
580     p_hwcrhk_RSAGetPublicKey = NULL;
581     p_hwcrhk_RSAUnloadKey = NULL;
582 #  endif
583     p_hwcrhk_ModExpCRT = NULL;
584     p_hwcrhk_RandomBytes = NULL;
585     return 0;
586 }
587
588 static int hwcrhk_finish(ENGINE *e)
589 {
590     int to_return = 1;
591     free_HWCRHK_LIBNAME();
592     if (hwcrhk_dso == NULL) {
593         HWCRHKerr(HWCRHK_F_HWCRHK_FINISH, HWCRHK_R_NOT_LOADED);
594         to_return = 0;
595         goto err;
596     }
597     release_context(hwcrhk_context);
598     if (!DSO_free(hwcrhk_dso)) {
599         HWCRHKerr(HWCRHK_F_HWCRHK_FINISH, HWCRHK_R_DSO_FAILURE);
600         to_return = 0;
601         goto err;
602     }
603  err:
604     BIO_free(logstream);
605     hwcrhk_dso = NULL;
606     p_hwcrhk_Init = NULL;
607     p_hwcrhk_Finish = NULL;
608     p_hwcrhk_ModExp = NULL;
609 #  ifndef OPENSSL_NO_RSA
610     p_hwcrhk_RSA = NULL;
611     p_hwcrhk_RSALoadKey = NULL;
612     p_hwcrhk_RSAGetPublicKey = NULL;
613     p_hwcrhk_RSAUnloadKey = NULL;
614 #  endif
615     p_hwcrhk_ModExpCRT = NULL;
616     p_hwcrhk_RandomBytes = NULL;
617     return to_return;
618 }
619
620 static int hwcrhk_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
621 {
622     int to_return = 1;
623
624     switch (cmd) {
625     case HWCRHK_CMD_SO_PATH:
626         if (hwcrhk_dso) {
627             HWCRHKerr(HWCRHK_F_HWCRHK_CTRL, HWCRHK_R_ALREADY_LOADED);
628             return 0;
629         }
630         if (p == NULL) {
631             HWCRHKerr(HWCRHK_F_HWCRHK_CTRL, ERR_R_PASSED_NULL_PARAMETER);
632             return 0;
633         }
634         return set_HWCRHK_LIBNAME((const char *)p);
635     case ENGINE_CTRL_SET_LOGSTREAM:
636         {
637             BIO *bio = (BIO *)p;
638
639             CRYPTO_THREAD_write_lock(chil_lock);
640             BIO_free(logstream);
641             logstream = NULL;
642             if (BIO_up_ref(bio)
643                 logstream = bio;
644             else
645                 HWCRHKerr(HWCRHK_F_HWCRHK_CTRL, HWCRHK_R_BIO_WAS_FREED);
646         }
647         CRYPTO_THREAD_unlock(chil_lock);
648         break;
649     case ENGINE_CTRL_SET_PASSWORD_CALLBACK:
650         CRYPTO_THREAD_write_lock(chil_lock);
651         password_context.password_callback = (pem_password_cb *)f;
652         CRYPTO_THREAD_unlock(chil_lock);
653         break;
654     case ENGINE_CTRL_SET_USER_INTERFACE:
655     case HWCRHK_CMD_SET_USER_INTERFACE:
656         CRYPTO_THREAD_write_lock(chil_lock);
657         password_context.ui_method = (UI_METHOD *)p;
658         CRYPTO_THREAD_unlock(chil_lock);
659         break;
660     case ENGINE_CTRL_SET_CALLBACK_DATA:
661     case HWCRHK_CMD_SET_CALLBACK_DATA:
662         CRYPTO_THREAD_write_lock(chil_lock);
663         password_context.callback_data = p;
664         CRYPTO_THREAD_unlock(chil_lock);
665         break;
666         /*
667          * this enables or disables the "SimpleForkCheck" flag used in the
668          * initialisation structure.
669          */
670     case ENGINE_CTRL_CHIL_SET_FORKCHECK:
671     case HWCRHK_CMD_FORK_CHECK:
672         CRYPTO_THREAD_write_lock(chil_lock);
673         if (i)
674             hwcrhk_globals.flags |= HWCryptoHook_InitFlags_SimpleForkCheck;
675         else
676             hwcrhk_globals.flags &= ~HWCryptoHook_InitFlags_SimpleForkCheck;
677         CRYPTO_THREAD_unlock(chil_lock);
678         break;
679         /*
680          * This will prevent the initialisation function from "installing"
681          * the mutex-handling callbacks, even if they are available from
682          * within the library (or were provided to the library from the
683          * calling application). This is to remove any baggage for
684          * applications not using multithreading.
685          */
686     case ENGINE_CTRL_CHIL_NO_LOCKING:
687         CRYPTO_THREAD_write_lock(chil_lock);
688         disable_mutex_callbacks = 1;
689         CRYPTO_THREAD_unlock(chil_lock);
690         break;
691     case HWCRHK_CMD_THREAD_LOCKING:
692         CRYPTO_THREAD_write_lock(chil_lock);
693         disable_mutex_callbacks = ((i == 0) ? 0 : 1);
694         CRYPTO_THREAD_unlock(chil_lock);
695         break;
696
697         /* The command isn't understood by this engine */
698     default:
699         HWCRHKerr(HWCRHK_F_HWCRHK_CTRL,
700                   HWCRHK_R_CTRL_COMMAND_NOT_IMPLEMENTED);
701         to_return = 0;
702         break;
703     }
704
705     return to_return;
706 }
707
708 static EVP_PKEY *hwcrhk_load_privkey(ENGINE *eng, const char *key_id,
709                                      UI_METHOD *ui_method,
710                                      void *callback_data)
711 {
712 #  ifndef OPENSSL_NO_RSA
713     RSA *rtmp = NULL;
714 #  endif
715     EVP_PKEY *res = NULL;
716 #  ifndef OPENSSL_NO_RSA
717     HWCryptoHook_MPI e, n;
718     HWCryptoHook_RSAKeyHandle *hptr;
719 #  endif
720 #  if !defined(OPENSSL_NO_RSA)
721     char tempbuf[1024];
722     HWCryptoHook_ErrMsgBuf rmsg;
723     HWCryptoHook_PassphraseContext ppctx;
724 #  endif
725
726 #  if !defined(OPENSSL_NO_RSA)
727     rmsg.buf = tempbuf;
728     rmsg.size = sizeof(tempbuf);
729 #  endif
730
731     if (!hwcrhk_context) {
732         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, HWCRHK_R_NOT_INITIALISED);
733         goto err;
734     }
735 #  ifndef OPENSSL_NO_RSA
736     hptr = OPENSSL_malloc(sizeof(*hptr));
737     if (hptr == NULL) {
738         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, ERR_R_MALLOC_FAILURE);
739         goto err;
740     }
741     ppctx.ui_method = ui_method;
742     ppctx.callback_data = callback_data;
743     if (p_hwcrhk_RSALoadKey(hwcrhk_context, key_id, hptr, &rmsg, &ppctx)) {
744         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, HWCRHK_R_CHIL_ERROR);
745         ERR_add_error_data(1, rmsg.buf);
746         goto err;
747     }
748     if (!*hptr) {
749         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, HWCRHK_R_NO_KEY);
750         goto err;
751     }
752 #  endif
753 #  ifndef OPENSSL_NO_RSA
754     rtmp = RSA_new_method(eng);
755     RSA_set_ex_data(rtmp, hndidx_rsa, (char *)hptr);
756     rtmp->e = BN_new();
757     rtmp->n = BN_new();
758     rtmp->flags |= RSA_FLAG_EXT_PKEY;
759     MPI2BN(rtmp->e, e);
760     MPI2BN(rtmp->n, n);
761     if (p_hwcrhk_RSAGetPublicKey(*hptr, &n, &e, &rmsg)
762         != HWCRYPTOHOOK_ERROR_MPISIZE) {
763         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, HWCRHK_R_CHIL_ERROR);
764         ERR_add_error_data(1, rmsg.buf);
765         goto err;
766     }
767
768     bn_expand2(rtmp->e, e.size / sizeof(BN_ULONG));
769     bn_expand2(rtmp->n, n.size / sizeof(BN_ULONG));
770     MPI2BN(rtmp->e, e);
771     MPI2BN(rtmp->n, n);
772
773     if (p_hwcrhk_RSAGetPublicKey(*hptr, &n, &e, &rmsg)) {
774         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, HWCRHK_R_CHIL_ERROR);
775         ERR_add_error_data(1, rmsg.buf);
776         goto err;
777     }
778     rtmp->e->top = e.size / sizeof(BN_ULONG);
779     bn_fix_top(rtmp->e);
780     rtmp->n->top = n.size / sizeof(BN_ULONG);
781     bn_fix_top(rtmp->n);
782
783     res = EVP_PKEY_new();
784     if (res == NULL) {
785         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, HWCRHK_R_CHIL_ERROR);
786         goto err;
787     }
788     EVP_PKEY_assign_RSA(res, rtmp);
789 #  endif
790
791     if (res == NULL)
792         HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY,
793                   HWCRHK_R_PRIVATE_KEY_ALGORITHMS_DISABLED);
794
795     return res;
796  err:
797 #  ifndef OPENSSL_NO_RSA
798     RSA_free(rtmp);
799 #  endif
800     return NULL;
801 }
802
803 static EVP_PKEY *hwcrhk_load_pubkey(ENGINE *eng, const char *key_id,
804                                     UI_METHOD *ui_method, void *callback_data)
805 {
806     EVP_PKEY *res = NULL;
807
808 #  ifndef OPENSSL_NO_RSA
809     res = hwcrhk_load_privkey(eng, key_id, ui_method, callback_data);
810 #  endif
811
812     if (res)
813         switch (res->type) {
814 #  ifndef OPENSSL_NO_RSA
815         case EVP_PKEY_RSA:
816             {
817                 RSA *rsa = NULL;
818
819                 CRYPTO_THREAD_write_lock(chil_lock);
820                 rsa = res->pkey.rsa;
821                 res->pkey.rsa = RSA_new();
822                 res->pkey.rsa->n = rsa->n;
823                 res->pkey.rsa->e = rsa->e;
824                 rsa->n = NULL;
825                 rsa->e = NULL;
826                 CRYPTO_THREAD_unlock(chil_lock);
827                 RSA_free(rsa);
828             }
829             break;
830 #  endif
831         default:
832             HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PUBKEY,
833                       HWCRHK_R_CTRL_COMMAND_NOT_IMPLEMENTED);
834             goto err;
835         }
836
837     return res;
838  err:
839     EVP_PKEY_free(res);
840     return NULL;
841 }
842
843 /* A little mod_exp */
844 static int hwcrhk_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
845                           const BIGNUM *m, BN_CTX *ctx)
846 {
847     char tempbuf[1024];
848     HWCryptoHook_ErrMsgBuf rmsg;
849     /*
850      * Since HWCryptoHook_MPI is pretty compatible with BIGNUM's, we use them
851      * directly, plus a little macro magic.  We only thing we need to make
852      * sure of is that enough space is allocated.
853      */
854     HWCryptoHook_MPI m_a, m_p, m_n, m_r;
855     int to_return, ret;
856
857     to_return = 0;              /* expect failure */
858     rmsg.buf = tempbuf;
859     rmsg.size = sizeof(tempbuf);
860
861     if (!hwcrhk_context) {
862         HWCRHKerr(HWCRHK_F_HWCRHK_MOD_EXP, HWCRHK_R_NOT_INITIALISED);
863         goto err;
864     }
865     /* Prepare the params */
866     bn_expand2(r, m->top);      /* Check for error !! */
867     BN2MPI(m_a, a);
868     BN2MPI(m_p, p);
869     BN2MPI(m_n, m);
870     MPI2BN(r, m_r);
871
872     /* Perform the operation */
873     ret = p_hwcrhk_ModExp(hwcrhk_context, m_a, m_p, m_n, &m_r, &rmsg);
874
875     /* Convert the response */
876     r->top = m_r.size / sizeof(BN_ULONG);
877     bn_fix_top(r);
878
879     if (ret < 0) {
880         /*
881          * FIXME: When this error is returned, HWCryptoHook is telling us
882          * that falling back to software computation might be a good thing.
883          */
884         if (ret == HWCRYPTOHOOK_ERROR_FALLBACK) {
885             HWCRHKerr(HWCRHK_F_HWCRHK_MOD_EXP, HWCRHK_R_REQUEST_FALLBACK);
886         } else {
887             HWCRHKerr(HWCRHK_F_HWCRHK_MOD_EXP, HWCRHK_R_REQUEST_FAILED);
888         }
889         ERR_add_error_data(1, rmsg.buf);
890         goto err;
891     }
892
893     to_return = 1;
894  err:
895     return to_return;
896 }
897
898 #  ifndef OPENSSL_NO_RSA
899 static int hwcrhk_rsa_mod_exp(BIGNUM *r, const BIGNUM *I, RSA *rsa,
900                               BN_CTX *ctx)
901 {
902     char tempbuf[1024];
903     HWCryptoHook_ErrMsgBuf rmsg;
904     HWCryptoHook_RSAKeyHandle *hptr;
905     int to_return = 0, ret;
906
907     rmsg.buf = tempbuf;
908     rmsg.size = sizeof(tempbuf);
909
910     if (!hwcrhk_context) {
911         HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP, HWCRHK_R_NOT_INITIALISED);
912         goto err;
913     }
914
915     /*
916      * This provides support for nForce keys.  Since that's opaque data all
917      * we do is provide a handle to the proper key and let HWCryptoHook take
918      * care of the rest.
919      */
920     if ((hptr =
921          (HWCryptoHook_RSAKeyHandle *) RSA_get_ex_data(rsa, hndidx_rsa))
922         != NULL) {
923         HWCryptoHook_MPI m_a, m_r;
924
925         if (!rsa->n) {
926             HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP,
927                       HWCRHK_R_MISSING_KEY_COMPONENTS);
928             goto err;
929         }
930
931         /* Prepare the params */
932         bn_expand2(r, rsa->n->top); /* Check for error !! */
933         BN2MPI(m_a, I);
934         MPI2BN(r, m_r);
935
936         /* Perform the operation */
937         ret = p_hwcrhk_RSA(m_a, *hptr, &m_r, &rmsg);
938
939         /* Convert the response */
940         r->top = m_r.size / sizeof(BN_ULONG);
941         bn_fix_top(r);
942
943         if (ret < 0) {
944             /*
945              * FIXME: When this error is returned, HWCryptoHook is telling us
946              * that falling back to software computation might be a good
947              * thing.
948              */
949             if (ret == HWCRYPTOHOOK_ERROR_FALLBACK) {
950                 HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP,
951                           HWCRHK_R_REQUEST_FALLBACK);
952             } else {
953                 HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP,
954                           HWCRHK_R_REQUEST_FAILED);
955             }
956             ERR_add_error_data(1, rmsg.buf);
957             goto err;
958         }
959     } else {
960         HWCryptoHook_MPI m_a, m_p, m_q, m_dmp1, m_dmq1, m_iqmp, m_r;
961
962         if (!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) {
963             HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP,
964                       HWCRHK_R_MISSING_KEY_COMPONENTS);
965             goto err;
966         }
967
968         /* Prepare the params */
969         bn_expand2(r, rsa->n->top); /* Check for error !! */
970         BN2MPI(m_a, I);
971         BN2MPI(m_p, rsa->p);
972         BN2MPI(m_q, rsa->q);
973         BN2MPI(m_dmp1, rsa->dmp1);
974         BN2MPI(m_dmq1, rsa->dmq1);
975         BN2MPI(m_iqmp, rsa->iqmp);
976         MPI2BN(r, m_r);
977
978         /* Perform the operation */
979         ret = p_hwcrhk_ModExpCRT(hwcrhk_context, m_a, m_p, m_q,
980                                  m_dmp1, m_dmq1, m_iqmp, &m_r, &rmsg);
981
982         /* Convert the response */
983         r->top = m_r.size / sizeof(BN_ULONG);
984         bn_fix_top(r);
985
986         if (ret < 0) {
987             /*
988              * FIXME: When this error is returned, HWCryptoHook is telling us
989              * that falling back to software computation might be a good
990              * thing.
991              */
992             if (ret == HWCRYPTOHOOK_ERROR_FALLBACK) {
993                 HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP,
994                           HWCRHK_R_REQUEST_FALLBACK);
995             } else {
996                 HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP,
997                           HWCRHK_R_REQUEST_FAILED);
998             }
999             ERR_add_error_data(1, rmsg.buf);
1000             goto err;
1001         }
1002     }
1003     /*
1004      * If we're here, we must be here with some semblance of success :-)
1005      */
1006     to_return = 1;
1007  err:
1008     return to_return;
1009 }
1010 #  endif
1011
1012 #  ifndef OPENSSL_NO_RSA
1013 /* This function is aliased to mod_exp (with the mont stuff dropped). */
1014 static int hwcrhk_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
1015                                const BIGNUM *m, BN_CTX *ctx,
1016                                BN_MONT_CTX *m_ctx)
1017 {
1018     return hwcrhk_mod_exp(r, a, p, m, ctx);
1019 }
1020
1021 static int hwcrhk_rsa_finish(RSA *rsa)
1022 {
1023     HWCryptoHook_RSAKeyHandle *hptr;
1024
1025     hptr = RSA_get_ex_data(rsa, hndidx_rsa);
1026     if (hptr) {
1027         p_hwcrhk_RSAUnloadKey(*hptr, NULL);
1028         OPENSSL_free(hptr);
1029         RSA_set_ex_data(rsa, hndidx_rsa, NULL);
1030     }
1031     return 1;
1032 }
1033
1034 #  endif
1035
1036 #  ifndef OPENSSL_NO_DH
1037 /* This function is aliased to mod_exp (with the dh and mont dropped). */
1038 static int hwcrhk_mod_exp_dh(const DH *dh, BIGNUM *r,
1039                              const BIGNUM *a, const BIGNUM *p,
1040                              const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
1041 {
1042     return hwcrhk_mod_exp(r, a, p, m, ctx);
1043 }
1044 #  endif
1045
1046 /* Random bytes are good */
1047 static int hwcrhk_rand_bytes(unsigned char *buf, int num)
1048 {
1049     char tempbuf[1024];
1050     HWCryptoHook_ErrMsgBuf rmsg;
1051     int to_return = 0;          /* assume failure */
1052     int ret;
1053
1054     rmsg.buf = tempbuf;
1055     rmsg.size = sizeof(tempbuf);
1056
1057     if (!hwcrhk_context) {
1058         HWCRHKerr(HWCRHK_F_HWCRHK_RAND_BYTES, HWCRHK_R_NOT_INITIALISED);
1059         goto err;
1060     }
1061
1062     ret = p_hwcrhk_RandomBytes(hwcrhk_context, buf, num, &rmsg);
1063     if (ret < 0) {
1064         /*
1065          * FIXME: When this error is returned, HWCryptoHook is telling us
1066          * that falling back to software computation might be a good thing.
1067          */
1068         if (ret == HWCRYPTOHOOK_ERROR_FALLBACK) {
1069             HWCRHKerr(HWCRHK_F_HWCRHK_RAND_BYTES, HWCRHK_R_REQUEST_FALLBACK);
1070         } else {
1071             HWCRHKerr(HWCRHK_F_HWCRHK_RAND_BYTES, HWCRHK_R_REQUEST_FAILED);
1072         }
1073         ERR_add_error_data(1, rmsg.buf);
1074         goto err;
1075     }
1076     to_return = 1;
1077  err:
1078     return to_return;
1079 }
1080
1081 static int hwcrhk_rand_status(void)
1082 {
1083     return 1;
1084 }
1085
1086 /*
1087  * Mutex calls: since the HWCryptoHook model closely follows the POSIX model
1088  * these just wrap the POSIX functions and add some logging.
1089  */
1090
1091 static int hwcrhk_mutex_init(HWCryptoHook_Mutex * mt,
1092                              HWCryptoHook_CallerContext * cactx)
1093 {
1094     mt->lock = CRYPTO_THREAD_lock_new();
1095     if (mt->lock == NULL)
1096         return 1;               /* failure */
1097     return 0;                   /* success */
1098 }
1099
1100 static int hwcrhk_mutex_lock(HWCryptoHook_Mutex * mt)
1101 {
1102     CRYPTO_THREAD_write_lock(mt->lock);
1103     return 0;
1104 }
1105
1106 static void hwcrhk_mutex_unlock(HWCryptoHook_Mutex * mt)
1107 {
1108     CRYPTO_THREAD_unlock(mt->lock);
1109 }
1110
1111 static void hwcrhk_mutex_destroy(HWCryptoHook_Mutex * mt)
1112 {
1113     CRYPTO_THREAD_lock_free(mt->lock);
1114 }
1115
1116 static int hwcrhk_get_pass(const char *prompt_info,
1117                            int *len_io, char *buf,
1118                            HWCryptoHook_PassphraseContext * ppctx,
1119                            HWCryptoHook_CallerContext * cactx)
1120 {
1121     pem_password_cb *callback = NULL;
1122     void *callback_data = NULL;
1123     UI_METHOD *ui_method = NULL;
1124     /*
1125      * Despite what the documentation says prompt_info can be an empty
1126      * string.
1127      */
1128     if (prompt_info && !*prompt_info)
1129         prompt_info = NULL;
1130
1131     if (cactx) {
1132         if (cactx->ui_method)
1133             ui_method = cactx->ui_method;
1134         if (cactx->password_callback)
1135             callback = cactx->password_callback;
1136         if (cactx->callback_data)
1137             callback_data = cactx->callback_data;
1138     }
1139     if (ppctx) {
1140         if (ppctx->ui_method) {
1141             ui_method = ppctx->ui_method;
1142             callback = NULL;
1143         }
1144         if (ppctx->callback_data)
1145             callback_data = ppctx->callback_data;
1146     }
1147     if (callback == NULL && ui_method == NULL) {
1148         HWCRHKerr(HWCRHK_F_HWCRHK_GET_PASS, HWCRHK_R_NO_CALLBACK);
1149         return -1;
1150     }
1151
1152     if (ui_method) {
1153         UI *ui = UI_new_method(ui_method);
1154         if (ui) {
1155             int ok;
1156             char *prompt = UI_construct_prompt(ui,
1157                                                "pass phrase", prompt_info);
1158
1159             ok = UI_add_input_string(ui, prompt,
1160                                      UI_INPUT_FLAG_DEFAULT_PWD,
1161                                      buf, 0, (*len_io) - 1);
1162             UI_add_user_data(ui, callback_data);
1163             UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
1164
1165             if (ok >= 0)
1166                 do {
1167                     ok = UI_process(ui);
1168                 }
1169                 while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
1170
1171             if (ok >= 0)
1172                 *len_io = strlen(buf);
1173
1174             UI_free(ui);
1175             OPENSSL_free(prompt);
1176         }
1177     } else {
1178         *len_io = callback(buf, *len_io, 0, callback_data);
1179     }
1180     if (!*len_io)
1181         return -1;
1182     return 0;
1183 }
1184
1185 static int hwcrhk_insert_card(const char *prompt_info,
1186                               const char *wrong_info,
1187                               HWCryptoHook_PassphraseContext * ppctx,
1188                               HWCryptoHook_CallerContext * cactx)
1189 {
1190     int ok = -1;
1191     UI *ui;
1192     void *callback_data = NULL;
1193     UI_METHOD *ui_method = NULL;
1194
1195     if (cactx) {
1196         if (cactx->ui_method)
1197             ui_method = cactx->ui_method;
1198         if (cactx->callback_data)
1199             callback_data = cactx->callback_data;
1200     }
1201     if (ppctx) {
1202         if (ppctx->ui_method)
1203             ui_method = ppctx->ui_method;
1204         if (ppctx->callback_data)
1205             callback_data = ppctx->callback_data;
1206     }
1207     if (ui_method == NULL) {
1208         HWCRHKerr(HWCRHK_F_HWCRHK_INSERT_CARD, HWCRHK_R_NO_CALLBACK);
1209         return -1;
1210     }
1211
1212     ui = UI_new_method(ui_method);
1213
1214     if (ui) {
1215         char answer = '\0';
1216         char buf[BUFSIZ];
1217         /*
1218          * Despite what the documentation says wrong_info can be an empty
1219          * string.
1220          */
1221         if (wrong_info && *wrong_info)
1222             BIO_snprintf(buf, sizeof(buf) - 1,
1223                          "Current card: \"%s\"\n", wrong_info);
1224         else
1225             buf[0] = 0;
1226         ok = UI_dup_info_string(ui, buf);
1227         if (ok >= 0 && prompt_info) {
1228             BIO_snprintf(buf, sizeof(buf) - 1,
1229                          "Insert card \"%s\"", prompt_info);
1230             ok = UI_dup_input_boolean(ui, buf,
1231                                       "\n then hit <enter> or C<enter> to cancel\n",
1232                                       "\r\n", "Cc", UI_INPUT_FLAG_ECHO,
1233                                       &answer);
1234         }
1235         UI_add_user_data(ui, callback_data);
1236
1237         if (ok >= 0)
1238             ok = UI_process(ui);
1239         UI_free(ui);
1240
1241         if (ok == -2 || (ok >= 0 && answer == 'C'))
1242             ok = 1;
1243         else if (ok < 0)
1244             ok = -1;
1245         else
1246             ok = 0;
1247     }
1248     return ok;
1249 }
1250
1251 static void hwcrhk_log_message(void *logstr, const char *message)
1252 {
1253     BIO *lstream = NULL;
1254
1255     if (logstr)
1256         lstream = *(BIO **)logstr;
1257     if (lstream) {
1258         BIO_printf(lstream, "%s\n", message);
1259     }
1260 }
1261
1262 /*
1263  * This stuff is needed if this ENGINE is being compiled into a
1264  * self-contained shared-library.
1265  */
1266 #  ifndef OPENSSL_NO_DYNAMIC_ENGINE
1267 static int bind_fn(ENGINE *e, const char *id)
1268 {
1269     if (id && (strcmp(id, engine_hwcrhk_id) != 0) &&
1270         (strcmp(id, engine_hwcrhk_id_alt) != 0))
1271         return 0;
1272     if (!bind_helper(e))
1273         return 0;
1274     return 1;
1275 }
1276
1277 IMPLEMENT_DYNAMIC_CHECK_FN()
1278     IMPLEMENT_DYNAMIC_BIND_FN(bind_fn)
1279 #  endif                        /* OPENSSL_NO_DYNAMIC_ENGINE */
1280 # endif                         /* !OPENSSL_NO_HW_CHIL */
1281 #endif                          /* !OPENSSL_NO_HW */