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