1/* md.c  -  message digest dispatcher
2 * Copyright (C) 1998, 1999, 2002, 2003, 2006,
3 *               2008 Free Software Foundation, Inc.
4 *
5 * This file is part of Libgcrypt.
6 *
7 * Libgcrypt is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU Lesser general Public License as
9 * published by the Free Software Foundation; either version 2.1 of
10 * the License, or (at your option) any later version.
11 *
12 * Libgcrypt is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
19 */
20
21#include <config.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25#include <errno.h>
26
27#include "g10lib.h"
28#include "cipher.h"
29#include "ath.h"
30
31#include "rmd.h"
32
33/* A dummy extraspec so that we do not need to tests the extraspec
34   field from the module specification against NULL and instead
35   directly test the respective fields of extraspecs.  */
36static md_extra_spec_t dummy_extra_spec;
37
38
39/* This is the list of the digest implementations included in
40   libgcrypt.  */
41static struct digest_table_entry
42{
43  gcry_md_spec_t *digest;
44  md_extra_spec_t *extraspec;
45  unsigned int algorithm;
46  int fips_allowed;
47} digest_table[] =
48  {
49#if USE_CRC
50    /* We allow the CRC algorithms even in FIPS mode because they are
51       actually no cryptographic primitives.  */
52    { &_gcry_digest_spec_crc32,
53      &dummy_extra_spec,                 GCRY_MD_CRC32, 1 },
54    { &_gcry_digest_spec_crc32_rfc1510,
55      &dummy_extra_spec,                 GCRY_MD_CRC32_RFC1510, 1 },
56    { &_gcry_digest_spec_crc24_rfc2440,
57      &dummy_extra_spec,                 GCRY_MD_CRC24_RFC2440, 1 },
58#endif
59#if USE_MD4
60    { &_gcry_digest_spec_md4,
61      &dummy_extra_spec,                 GCRY_MD_MD4 },
62#endif
63#if USE_MD5
64    { &_gcry_digest_spec_md5,
65      &dummy_extra_spec,                 GCRY_MD_MD5, 1 },
66#endif
67#if USE_RMD160
68    { &_gcry_digest_spec_rmd160,
69      &dummy_extra_spec,                 GCRY_MD_RMD160 },
70#endif
71#if USE_SHA1
72    { &_gcry_digest_spec_sha1,
73      &_gcry_digest_extraspec_sha1,      GCRY_MD_SHA1, 1 },
74#endif
75#if USE_SHA256
76    { &_gcry_digest_spec_sha256,
77      &_gcry_digest_extraspec_sha256,    GCRY_MD_SHA256, 1 },
78    { &_gcry_digest_spec_sha224,
79      &_gcry_digest_extraspec_sha224,    GCRY_MD_SHA224, 1 },
80#endif
81#if USE_SHA512
82    { &_gcry_digest_spec_sha512,
83      &_gcry_digest_extraspec_sha512,    GCRY_MD_SHA512, 1 },
84    { &_gcry_digest_spec_sha384,
85      &_gcry_digest_extraspec_sha384,    GCRY_MD_SHA384, 1 },
86#endif
87#if USE_TIGER
88    { &_gcry_digest_spec_tiger,
89      &dummy_extra_spec,                 GCRY_MD_TIGER },
90    { &_gcry_digest_spec_tiger1,
91      &dummy_extra_spec,                 GCRY_MD_TIGER1 },
92    { &_gcry_digest_spec_tiger2,
93      &dummy_extra_spec,                 GCRY_MD_TIGER2 },
94#endif
95#if USE_WHIRLPOOL
96    { &_gcry_digest_spec_whirlpool,
97      &dummy_extra_spec,                 GCRY_MD_WHIRLPOOL },
98#endif
99    { NULL },
100  };
101
102/* List of registered digests.  */
103static gcry_module_t digests_registered;
104
105/* This is the lock protecting DIGESTS_REGISTERED.  */
106static ath_mutex_t digests_registered_lock = ATH_MUTEX_INITIALIZER;
107
108/* Flag to check whether the default ciphers have already been
109   registered.  */
110static int default_digests_registered;
111
112typedef struct gcry_md_list
113{
114  gcry_md_spec_t *digest;
115  gcry_module_t module;
116  struct gcry_md_list *next;
117  size_t actual_struct_size;     /* Allocated size of this structure. */
118  PROPERLY_ALIGNED_TYPE context;
119} GcryDigestEntry;
120
121/* this structure is put right after the gcry_md_hd_t buffer, so that
122 * only one memory block is needed. */
123struct gcry_md_context
124{
125  int  magic;
126  size_t actual_handle_size;     /* Allocated size of this handle. */
127  int  secure;
128  FILE  *debug;
129  int finalized;
130  GcryDigestEntry *list;
131  byte *macpads;
132  int macpads_Bsize;             /* Blocksize as used for the HMAC pads. */
133};
134
135
136#define CTX_MAGIC_NORMAL 0x11071961
137#define CTX_MAGIC_SECURE 0x16917011
138
139/* Convenient macro for registering the default digests.  */
140#define REGISTER_DEFAULT_DIGESTS                   \
141  do                                               \
142    {                                              \
143      ath_mutex_lock (&digests_registered_lock);   \
144      if (! default_digests_registered)            \
145        {                                          \
146          md_register_default ();                  \
147          default_digests_registered = 1;          \
148        }                                          \
149      ath_mutex_unlock (&digests_registered_lock); \
150    }                                              \
151  while (0)
152
153
154static const char * digest_algo_to_string( int algo );
155static gcry_err_code_t check_digest_algo (int algo);
156static gcry_err_code_t md_open (gcry_md_hd_t *h, int algo,
157                                int secure, int hmac);
158static gcry_err_code_t md_enable (gcry_md_hd_t hd, int algo);
159static gcry_err_code_t md_copy (gcry_md_hd_t a, gcry_md_hd_t *b);
160static void md_close (gcry_md_hd_t a);
161static void md_write (gcry_md_hd_t a, const void *inbuf, size_t inlen);
162static void md_final(gcry_md_hd_t a);
163static byte *md_read( gcry_md_hd_t a, int algo );
164static int md_get_algo( gcry_md_hd_t a );
165static int md_digest_length( int algo );
166static const byte *md_asn_oid( int algo, size_t *asnlen, size_t *mdlen );
167static void md_start_debug ( gcry_md_hd_t a, const char *suffix );
168static void md_stop_debug ( gcry_md_hd_t a );
169
170
171
172
173/* Internal function.  Register all the ciphers included in
174   CIPHER_TABLE.  Returns zero on success or an error code.  */
175static void
176md_register_default (void)
177{
178  gcry_err_code_t err = 0;
179  int i;
180
181  for (i = 0; !err && digest_table[i].digest; i++)
182    {
183      if ( fips_mode ())
184        {
185          if (!digest_table[i].fips_allowed)
186            continue;
187          if (digest_table[i].algorithm == GCRY_MD_MD5
188              && _gcry_enforced_fips_mode () )
189            continue;  /* Do not register in enforced fips mode.  */
190        }
191
192      err = _gcry_module_add (&digests_registered,
193                              digest_table[i].algorithm,
194                              (void *) digest_table[i].digest,
195                              (void *) digest_table[i].extraspec,
196                              NULL);
197    }
198
199  if (err)
200    BUG ();
201}
202
203/* Internal callback function.  */
204static int
205gcry_md_lookup_func_name (void *spec, void *data)
206{
207  gcry_md_spec_t *digest = (gcry_md_spec_t *) spec;
208  char *name = (char *) data;
209
210  return (! stricmp (digest->name, name));
211}
212
213/* Internal callback function.  Used via _gcry_module_lookup.  */
214static int
215gcry_md_lookup_func_oid (void *spec, void *data)
216{
217  gcry_md_spec_t *digest = (gcry_md_spec_t *) spec;
218  char *oid = (char *) data;
219  gcry_md_oid_spec_t *oid_specs = digest->oids;
220  int ret = 0, i;
221
222  if (oid_specs)
223    {
224      for (i = 0; oid_specs[i].oidstring && (! ret); i++)
225        if (! stricmp (oid, oid_specs[i].oidstring))
226          ret = 1;
227    }
228
229  return ret;
230}
231
232/* Internal function.  Lookup a digest entry by it's name.  */
233static gcry_module_t
234gcry_md_lookup_name (const char *name)
235{
236  gcry_module_t digest;
237
238  digest = _gcry_module_lookup (digests_registered, (void *) name,
239				gcry_md_lookup_func_name);
240
241  return digest;
242}
243
244/* Internal function.  Lookup a cipher entry by it's oid.  */
245static gcry_module_t
246gcry_md_lookup_oid (const char *oid)
247{
248  gcry_module_t digest;
249
250  digest = _gcry_module_lookup (digests_registered, (void *) oid,
251				gcry_md_lookup_func_oid);
252
253  return digest;
254}
255
256/* Register a new digest module whose specification can be found in
257   DIGEST.  On success, a new algorithm ID is stored in ALGORITHM_ID
258   and a pointer representhing this module is stored in MODULE.  */
259gcry_error_t
260_gcry_md_register (gcry_md_spec_t *digest,
261                   md_extra_spec_t *extraspec,
262                   unsigned int *algorithm_id,
263                   gcry_module_t *module)
264{
265  gcry_err_code_t err = 0;
266  gcry_module_t mod;
267
268  /* We do not support module loading in fips mode.  */
269  if (fips_mode ())
270    return gpg_error (GPG_ERR_NOT_SUPPORTED);
271
272  ath_mutex_lock (&digests_registered_lock);
273  err = _gcry_module_add (&digests_registered, 0,
274			  (void *) digest,
275			  (void *)(extraspec? extraspec : &dummy_extra_spec),
276                          &mod);
277  ath_mutex_unlock (&digests_registered_lock);
278
279  if (! err)
280    {
281      *module = mod;
282      *algorithm_id = mod->mod_id;
283    }
284
285  return gcry_error (err);
286}
287
288/* Unregister the digest identified by ID, which must have been
289   registered with gcry_digest_register.  */
290void
291gcry_md_unregister (gcry_module_t module)
292{
293  ath_mutex_lock (&digests_registered_lock);
294  _gcry_module_release (module);
295  ath_mutex_unlock (&digests_registered_lock);
296}
297
298
299static int
300search_oid (const char *oid, int *algorithm, gcry_md_oid_spec_t *oid_spec)
301{
302  gcry_module_t module;
303  int ret = 0;
304
305  if (oid && ((! strncmp (oid, "oid.", 4))
306	      || (! strncmp (oid, "OID.", 4))))
307    oid += 4;
308
309  module = gcry_md_lookup_oid (oid);
310  if (module)
311    {
312      gcry_md_spec_t *digest = module->spec;
313      int i;
314
315      for (i = 0; digest->oids[i].oidstring && !ret; i++)
316	if (! stricmp (oid, digest->oids[i].oidstring))
317	  {
318	    if (algorithm)
319	      *algorithm = module->mod_id;
320	    if (oid_spec)
321	      *oid_spec = digest->oids[i];
322	    ret = 1;
323	  }
324      _gcry_module_release (module);
325    }
326
327  return ret;
328}
329
330/****************
331 * Map a string to the digest algo
332 */
333int
334gcry_md_map_name (const char *string)
335{
336  gcry_module_t digest;
337  int ret, algorithm = 0;
338
339  if (! string)
340    return 0;
341
342  REGISTER_DEFAULT_DIGESTS;
343
344  /* If the string starts with a digit (optionally prefixed with
345     either "OID." or "oid."), we first look into our table of ASN.1
346     object identifiers to figure out the algorithm */
347
348  ath_mutex_lock (&digests_registered_lock);
349
350  ret = search_oid (string, &algorithm, NULL);
351  if (! ret)
352    {
353      /* Not found, search a matching digest name.  */
354      digest = gcry_md_lookup_name (string);
355      if (digest)
356	{
357	  algorithm = digest->mod_id;
358	  _gcry_module_release (digest);
359	}
360    }
361  ath_mutex_unlock (&digests_registered_lock);
362
363  return algorithm;
364}
365
366
367/****************
368 * Map a digest algo to a string
369 */
370static const char *
371digest_algo_to_string (int algorithm)
372{
373  const char *name = NULL;
374  gcry_module_t digest;
375
376  REGISTER_DEFAULT_DIGESTS;
377
378  ath_mutex_lock (&digests_registered_lock);
379  digest = _gcry_module_lookup_id (digests_registered, algorithm);
380  if (digest)
381    {
382      name = ((gcry_md_spec_t *) digest->spec)->name;
383      _gcry_module_release (digest);
384    }
385  ath_mutex_unlock (&digests_registered_lock);
386
387  return name;
388}
389
390/****************
391 * This function simply returns the name of the algorithm or some constant
392 * string when there is no algo.  It will never return NULL.
393 * Use	the macro gcry_md_test_algo() to check whether the algorithm
394 * is valid.
395 */
396const char *
397gcry_md_algo_name (int algorithm)
398{
399  const char *s = digest_algo_to_string (algorithm);
400  return s ? s : "?";
401}
402
403
404static gcry_err_code_t
405check_digest_algo (int algorithm)
406{
407  gcry_err_code_t rc = 0;
408  gcry_module_t digest;
409
410  REGISTER_DEFAULT_DIGESTS;
411
412  ath_mutex_lock (&digests_registered_lock);
413  digest = _gcry_module_lookup_id (digests_registered, algorithm);
414  if (digest)
415    _gcry_module_release (digest);
416  else
417    rc = GPG_ERR_DIGEST_ALGO;
418  ath_mutex_unlock (&digests_registered_lock);
419
420  return rc;
421}
422
423
424
425/****************
426 * Open a message digest handle for use with algorithm ALGO.
427 * More algorithms may be added by md_enable(). The initial algorithm
428 * may be 0.
429 */
430static gcry_err_code_t
431md_open (gcry_md_hd_t *h, int algo, int secure, int hmac)
432{
433  gcry_err_code_t err = GPG_ERR_NO_ERROR;
434  int bufsize = secure ? 512 : 1024;
435  struct gcry_md_context *ctx;
436  gcry_md_hd_t hd;
437  size_t n;
438
439  /* Allocate a memory area to hold the caller visible buffer with it's
440   * control information and the data required by this module. Set the
441   * context pointer at the beginning to this area.
442   * We have to use this strange scheme because we want to hide the
443   * internal data but have a variable sized buffer.
444   *
445   *	+---+------+---........------+-------------+
446   *	!ctx! bctl !  buffer	     ! private	   !
447   *	+---+------+---........------+-------------+
448   *	  !			      ^
449   *	  !---------------------------!
450   *
451   * We have to make sure that private is well aligned.
452   */
453  n = sizeof (struct gcry_md_handle) + bufsize;
454  n = ((n + sizeof (PROPERLY_ALIGNED_TYPE) - 1)
455       / sizeof (PROPERLY_ALIGNED_TYPE)) * sizeof (PROPERLY_ALIGNED_TYPE);
456
457  /* Allocate and set the Context pointer to the private data */
458  if (secure)
459    hd = gcry_malloc_secure (n + sizeof (struct gcry_md_context));
460  else
461    hd = gcry_malloc (n + sizeof (struct gcry_md_context));
462
463  if (! hd)
464    err = gpg_err_code_from_errno (errno);
465
466  if (! err)
467    {
468      hd->ctx = ctx = (struct gcry_md_context *) ((char *) hd + n);
469      /* Setup the globally visible data (bctl in the diagram).*/
470      hd->bufsize = n - sizeof (struct gcry_md_handle) + 1;
471      hd->bufpos = 0;
472
473      /* Initialize the private data. */
474      memset (hd->ctx, 0, sizeof *hd->ctx);
475      ctx->magic = secure ? CTX_MAGIC_SECURE : CTX_MAGIC_NORMAL;
476      ctx->actual_handle_size = n + sizeof (struct gcry_md_context);
477      ctx->secure = secure;
478
479      if (hmac)
480	{
481	  switch (algo)
482            {
483              case GCRY_MD_SHA384:
484              case GCRY_MD_SHA512:
485                ctx->macpads_Bsize = 128;
486                break;
487              default:
488                ctx->macpads_Bsize = 64;
489                break;
490            }
491          ctx->macpads = gcry_malloc_secure (2*(ctx->macpads_Bsize));
492	  if (!ctx->macpads)
493	    {
494	      err = gpg_err_code_from_errno (errno);
495	      md_close (hd);
496	    }
497	}
498    }
499
500  if (! err)
501    {
502      /* Hmmm, should we really do that? - yes [-wk] */
503      _gcry_fast_random_poll ();
504
505      if (algo)
506	{
507	  err = md_enable (hd, algo);
508	  if (err)
509	    md_close (hd);
510	}
511    }
512
513  if (! err)
514    *h = hd;
515
516  return err;
517}
518
519/* Create a message digest object for algorithm ALGO.  FLAGS may be
520   given as an bitwise OR of the gcry_md_flags values.  ALGO may be
521   given as 0 if the algorithms to be used are later set using
522   gcry_md_enable. H is guaranteed to be a valid handle or NULL on
523   error.  */
524gcry_error_t
525gcry_md_open (gcry_md_hd_t *h, int algo, unsigned int flags)
526{
527  gcry_err_code_t err = GPG_ERR_NO_ERROR;
528  gcry_md_hd_t hd;
529
530  if ((flags & ~(GCRY_MD_FLAG_SECURE | GCRY_MD_FLAG_HMAC)))
531    err = GPG_ERR_INV_ARG;
532  else
533    {
534      err = md_open (&hd, algo, (flags & GCRY_MD_FLAG_SECURE),
535		     (flags & GCRY_MD_FLAG_HMAC));
536    }
537
538  *h = err? NULL : hd;
539  return gcry_error (err);
540}
541
542
543
544static gcry_err_code_t
545md_enable (gcry_md_hd_t hd, int algorithm)
546{
547  struct gcry_md_context *h = hd->ctx;
548  gcry_md_spec_t *digest = NULL;
549  GcryDigestEntry *entry;
550  gcry_module_t module;
551  gcry_err_code_t err = 0;
552
553  for (entry = h->list; entry; entry = entry->next)
554    if (entry->module->mod_id == algorithm)
555      return err; /* already enabled */
556
557  REGISTER_DEFAULT_DIGESTS;
558
559  ath_mutex_lock (&digests_registered_lock);
560  module = _gcry_module_lookup_id (digests_registered, algorithm);
561  ath_mutex_unlock (&digests_registered_lock);
562  if (! module)
563    {
564      log_debug ("md_enable: algorithm %d not available\n", algorithm);
565      err = GPG_ERR_DIGEST_ALGO;
566    }
567 else
568    digest = (gcry_md_spec_t *) module->spec;
569
570
571  if (!err && algorithm == GCRY_MD_MD5 && fips_mode ())
572    {
573      _gcry_inactivate_fips_mode ("MD5 used");
574      if (_gcry_enforced_fips_mode () )
575        {
576          /* We should never get to here because we do not register
577             MD5 in enforced fips mode. But better throw an error.  */
578          err = GPG_ERR_DIGEST_ALGO;
579        }
580    }
581
582  if (!err)
583    {
584      size_t size = (sizeof (*entry)
585                     + digest->contextsize
586                     - sizeof (entry->context));
587
588      /* And allocate a new list entry. */
589      if (h->secure)
590	entry = gcry_malloc_secure (size);
591      else
592	entry = gcry_malloc (size);
593
594      if (! entry)
595	err = gpg_err_code_from_errno (errno);
596      else
597	{
598	  entry->digest = digest;
599	  entry->module = module;
600	  entry->next = h->list;
601          entry->actual_struct_size = size;
602	  h->list = entry;
603
604	  /* And init this instance. */
605	  entry->digest->init (&entry->context.c);
606	}
607    }
608
609  if (err)
610    {
611      if (module)
612	{
613	   ath_mutex_lock (&digests_registered_lock);
614	   _gcry_module_release (module);
615	   ath_mutex_unlock (&digests_registered_lock);
616	}
617    }
618
619  return err;
620}
621
622
623gcry_error_t
624gcry_md_enable (gcry_md_hd_t hd, int algorithm)
625{
626  return gcry_error (md_enable (hd, algorithm));
627}
628
629static gcry_err_code_t
630md_copy (gcry_md_hd_t ahd, gcry_md_hd_t *b_hd)
631{
632  gcry_err_code_t err = GPG_ERR_NO_ERROR;
633  struct gcry_md_context *a = ahd->ctx;
634  struct gcry_md_context *b;
635  GcryDigestEntry *ar, *br;
636  gcry_md_hd_t bhd;
637  size_t n;
638
639  if (ahd->bufpos)
640    md_write (ahd, NULL, 0);
641
642  n = (char *) ahd->ctx - (char *) ahd;
643  if (a->secure)
644    bhd = gcry_malloc_secure (n + sizeof (struct gcry_md_context));
645  else
646    bhd = gcry_malloc (n + sizeof (struct gcry_md_context));
647
648  if (! bhd)
649    err = gpg_err_code_from_errno (errno);
650
651  if (! err)
652    {
653      bhd->ctx = b = (struct gcry_md_context *) ((char *) bhd + n);
654      /* No need to copy the buffer due to the write above. */
655      gcry_assert (ahd->bufsize == (n - sizeof (struct gcry_md_handle) + 1));
656      bhd->bufsize = ahd->bufsize;
657      bhd->bufpos = 0;
658      gcry_assert (! ahd->bufpos);
659      memcpy (b, a, sizeof *a);
660      b->list = NULL;
661      b->debug = NULL;
662      if (a->macpads)
663	{
664	  b->macpads = gcry_malloc_secure (2*(a->macpads_Bsize));
665	  if (! b->macpads)
666	    {
667	      err = gpg_err_code_from_errno (errno);
668	      md_close (bhd);
669	    }
670	  else
671	    memcpy (b->macpads, a->macpads, (2*(a->macpads_Bsize)));
672	}
673    }
674
675  /* Copy the complete list of algorithms.  The copied list is
676     reversed, but that doesn't matter. */
677  if (!err)
678    {
679      for (ar = a->list; ar; ar = ar->next)
680        {
681          if (a->secure)
682            br = gcry_malloc_secure (sizeof *br
683                                     + ar->digest->contextsize
684                                     - sizeof(ar->context));
685          else
686            br = gcry_malloc (sizeof *br
687                              + ar->digest->contextsize
688                              - sizeof (ar->context));
689          if (!br)
690            {
691	      err = gpg_err_code_from_errno (errno);
692              md_close (bhd);
693              break;
694            }
695
696          memcpy (br, ar, (sizeof (*br) + ar->digest->contextsize
697                           - sizeof (ar->context)));
698          br->next = b->list;
699          b->list = br;
700
701          /* Add a reference to the module.  */
702          ath_mutex_lock (&digests_registered_lock);
703          _gcry_module_use (br->module);
704          ath_mutex_unlock (&digests_registered_lock);
705        }
706    }
707
708  if (a->debug && !err)
709    md_start_debug (bhd, "unknown");
710
711  if (!err)
712    *b_hd = bhd;
713
714  return err;
715}
716
717gcry_error_t
718gcry_md_copy (gcry_md_hd_t *handle, gcry_md_hd_t hd)
719{
720  gcry_err_code_t err;
721
722  err = md_copy (hd, handle);
723  if (err)
724    *handle = NULL;
725  return gcry_error (err);
726}
727
728/*
729 * Reset all contexts and discard any buffered stuff.  This may be used
730 * instead of a md_close(); md_open().
731 */
732void
733gcry_md_reset (gcry_md_hd_t a)
734{
735  GcryDigestEntry *r;
736
737  /* Note: We allow this even in fips non operational mode.  */
738
739  a->bufpos = a->ctx->finalized = 0;
740
741  for (r = a->ctx->list; r; r = r->next)
742    {
743      memset (r->context.c, 0, r->digest->contextsize);
744      (*r->digest->init) (&r->context.c);
745    }
746  if (a->ctx->macpads)
747    md_write (a, a->ctx->macpads, a->ctx->macpads_Bsize); /* inner pad */
748}
749
750static void
751md_close (gcry_md_hd_t a)
752{
753  GcryDigestEntry *r, *r2;
754
755  if (! a)
756    return;
757  if (a->ctx->debug)
758    md_stop_debug (a);
759  for (r = a->ctx->list; r; r = r2)
760    {
761      r2 = r->next;
762      ath_mutex_lock (&digests_registered_lock);
763      _gcry_module_release (r->module);
764      ath_mutex_unlock (&digests_registered_lock);
765      wipememory (r, r->actual_struct_size);
766      gcry_free (r);
767    }
768
769  if (a->ctx->macpads)
770    {
771      wipememory (a->ctx->macpads, 2*(a->ctx->macpads_Bsize));
772      gcry_free(a->ctx->macpads);
773    }
774
775  wipememory (a, a->ctx->actual_handle_size);
776  gcry_free(a);
777}
778
779void
780gcry_md_close (gcry_md_hd_t hd)
781{
782  /* Note: We allow this even in fips non operational mode.  */
783  md_close (hd);
784}
785
786static void
787md_write (gcry_md_hd_t a, const void *inbuf, size_t inlen)
788{
789  GcryDigestEntry *r;
790
791  if (a->ctx->debug)
792    {
793      if (a->bufpos && fwrite (a->buf, a->bufpos, 1, a->ctx->debug) != 1)
794	BUG();
795      if (inlen && fwrite (inbuf, inlen, 1, a->ctx->debug) != 1)
796	BUG();
797    }
798
799  for (r = a->ctx->list; r; r = r->next)
800    {
801      if (a->bufpos)
802	(*r->digest->write) (&r->context.c, a->buf, a->bufpos);
803      (*r->digest->write) (&r->context.c, inbuf, inlen);
804    }
805  a->bufpos = 0;
806}
807
808void
809gcry_md_write (gcry_md_hd_t hd, const void *inbuf, size_t inlen)
810{
811  md_write (hd, inbuf, inlen);
812}
813
814static void
815md_final (gcry_md_hd_t a)
816{
817  GcryDigestEntry *r;
818
819  if (a->ctx->finalized)
820    return;
821
822  if (a->bufpos)
823    md_write (a, NULL, 0);
824
825  for (r = a->ctx->list; r; r = r->next)
826    (*r->digest->final) (&r->context.c);
827
828  a->ctx->finalized = 1;
829
830  if (a->ctx->macpads)
831    {
832      /* Finish the hmac. */
833      int algo = md_get_algo (a);
834      byte *p = md_read (a, algo);
835      size_t dlen = md_digest_length (algo);
836      gcry_md_hd_t om;
837      gcry_err_code_t err = md_open (&om, algo, a->ctx->secure, 0);
838
839      if (err)
840	_gcry_fatal_error (err, NULL);
841      md_write (om,
842                (a->ctx->macpads)+(a->ctx->macpads_Bsize),
843                a->ctx->macpads_Bsize);
844      md_write (om, p, dlen);
845      md_final (om);
846      /* Replace our digest with the mac (they have the same size). */
847      memcpy (p, md_read (om, algo), dlen);
848      md_close (om);
849    }
850}
851
852static gcry_err_code_t
853prepare_macpads (gcry_md_hd_t hd, const unsigned char *key, size_t keylen)
854{
855  int i;
856  int algo = md_get_algo (hd);
857  unsigned char *helpkey = NULL;
858  unsigned char *ipad, *opad;
859
860  if (!algo)
861    return GPG_ERR_DIGEST_ALGO; /* Might happen if no algo is enabled.  */
862
863  if ( keylen > hd->ctx->macpads_Bsize )
864    {
865      helpkey = gcry_malloc_secure (md_digest_length (algo));
866      if (!helpkey)
867        return gpg_err_code_from_errno (errno);
868      gcry_md_hash_buffer (algo, helpkey, key, keylen);
869      key = helpkey;
870      keylen = md_digest_length (algo);
871      gcry_assert ( keylen <= hd->ctx->macpads_Bsize );
872    }
873
874  memset ( hd->ctx->macpads, 0, 2*(hd->ctx->macpads_Bsize) );
875  ipad = hd->ctx->macpads;
876  opad = (hd->ctx->macpads)+(hd->ctx->macpads_Bsize);
877  memcpy ( ipad, key, keylen );
878  memcpy ( opad, key, keylen );
879  for (i=0; i < hd->ctx->macpads_Bsize; i++ )
880    {
881      ipad[i] ^= 0x36;
882      opad[i] ^= 0x5c;
883    }
884  gcry_free (helpkey);
885
886  return GPG_ERR_NO_ERROR;
887}
888
889gcry_error_t
890gcry_md_ctl (gcry_md_hd_t hd, int cmd, void *buffer, size_t buflen)
891{
892  gcry_err_code_t rc = 0;
893
894  switch (cmd)
895    {
896    case GCRYCTL_FINALIZE:
897      md_final (hd);
898      break;
899    case GCRYCTL_SET_KEY:
900      rc = gcry_err_code (gcry_md_setkey (hd, buffer, buflen));
901      break;
902    case GCRYCTL_START_DUMP:
903      md_start_debug (hd, buffer);
904      break;
905    case GCRYCTL_STOP_DUMP:
906      md_stop_debug ( hd );
907      break;
908    default:
909      rc = GPG_ERR_INV_OP;
910    }
911  return gcry_error (rc);
912}
913
914gcry_error_t
915gcry_md_setkey (gcry_md_hd_t hd, const void *key, size_t keylen)
916{
917  gcry_err_code_t rc = GPG_ERR_NO_ERROR;
918
919  if (!hd->ctx->macpads)
920    rc = GPG_ERR_CONFLICT;
921  else
922    {
923      rc = prepare_macpads (hd, key, keylen);
924      if (! rc)
925	gcry_md_reset (hd);
926    }
927
928  return gcry_error (rc);
929}
930
931/* The new debug interface.  If SUFFIX is a string it creates an debug
932   file for the context HD.  IF suffix is NULL, the file is closed and
933   debugging is stopped.  */
934void
935gcry_md_debug (gcry_md_hd_t hd, const char *suffix)
936{
937  if (suffix)
938    md_start_debug (hd, suffix);
939  else
940    md_stop_debug (hd);
941}
942
943
944
945/****************
946 * if ALGO is null get the digest for the used algo (which should be only one)
947 */
948static byte *
949md_read( gcry_md_hd_t a, int algo )
950{
951  GcryDigestEntry *r = a->ctx->list;
952
953  if (! algo)
954    {
955      /* Return the first algorithm */
956      if (r)
957        {
958          if (r->next)
959            log_debug ("more than one algorithm in md_read(0)\n");
960          return r->digest->read (&r->context.c);
961        }
962    }
963  else
964    {
965      for (r = a->ctx->list; r; r = r->next)
966	if (r->module->mod_id == algo)
967	  return r->digest->read (&r->context.c);
968    }
969  BUG();
970  return NULL;
971}
972
973/*
974 * Read out the complete digest, this function implictly finalizes
975 * the hash.
976 */
977byte *
978gcry_md_read (gcry_md_hd_t hd, int algo)
979{
980  /* This function is expected to always return a digest, thus we
981     can't return an error which we actually should do in
982     non-operational state.  */
983  gcry_md_ctl (hd, GCRYCTL_FINALIZE, NULL, 0);
984  return md_read (hd, algo);
985}
986
987
988/*
989 * Read out an intermediate digest.  Not yet functional.
990 */
991gcry_err_code_t
992gcry_md_get (gcry_md_hd_t hd, int algo, byte *buffer, int buflen)
993{
994  (void)hd;
995  (void)algo;
996  (void)buffer;
997  (void)buflen;
998
999  /*md_digest ... */
1000  fips_signal_error ("unimplemented function called");
1001  return GPG_ERR_INTERNAL;
1002}
1003
1004
1005/*
1006 * Shortcut function to hash a buffer with a given algo. The only
1007 * guaranteed supported algorithms are RIPE-MD160 and SHA-1. The
1008 * supplied digest buffer must be large enough to store the resulting
1009 * hash.  No error is returned, the function will abort on an invalid
1010 * algo.  DISABLED_ALGOS are ignored here.  */
1011void
1012gcry_md_hash_buffer (int algo, void *digest,
1013                     const void *buffer, size_t length)
1014{
1015  if (algo == GCRY_MD_SHA1)
1016    _gcry_sha1_hash_buffer (digest, buffer, length);
1017  else if (algo == GCRY_MD_RMD160 && !fips_mode () )
1018    _gcry_rmd160_hash_buffer (digest, buffer, length);
1019  else
1020    {
1021      /* For the others we do not have a fast function, so we use the
1022	 normal functions. */
1023      gcry_md_hd_t h;
1024      gpg_err_code_t err;
1025
1026      if (algo == GCRY_MD_MD5 && fips_mode ())
1027        {
1028          _gcry_inactivate_fips_mode ("MD5 used");
1029          if (_gcry_enforced_fips_mode () )
1030            {
1031              /* We should never get to here because we do not register
1032                 MD5 in enforced fips mode.  */
1033              _gcry_fips_noreturn ();
1034            }
1035        }
1036
1037      err = md_open (&h, algo, 0, 0);
1038      if (err)
1039	log_bug ("gcry_md_open failed for algo %d: %s",
1040                 algo, gpg_strerror (gcry_error(err)));
1041      md_write (h, (byte *) buffer, length);
1042      md_final (h);
1043      memcpy (digest, md_read (h, algo), md_digest_length (algo));
1044      md_close (h);
1045    }
1046}
1047
1048static int
1049md_get_algo (gcry_md_hd_t a)
1050{
1051  GcryDigestEntry *r = a->ctx->list;
1052
1053  if (r && r->next)
1054    {
1055      fips_signal_error ("possible usage error");
1056      log_error ("WARNING: more than one algorithm in md_get_algo()\n");
1057    }
1058  return r ? r->module->mod_id : 0;
1059}
1060
1061int
1062gcry_md_get_algo (gcry_md_hd_t hd)
1063{
1064  return md_get_algo (hd);
1065}
1066
1067
1068/****************
1069 * Return the length of the digest
1070 */
1071static int
1072md_digest_length (int algorithm)
1073{
1074  gcry_module_t digest;
1075  int mdlen = 0;
1076
1077  REGISTER_DEFAULT_DIGESTS;
1078
1079  ath_mutex_lock (&digests_registered_lock);
1080  digest = _gcry_module_lookup_id (digests_registered, algorithm);
1081  if (digest)
1082    {
1083      mdlen = ((gcry_md_spec_t *) digest->spec)->mdlen;
1084      _gcry_module_release (digest);
1085    }
1086  ath_mutex_unlock (&digests_registered_lock);
1087
1088  return mdlen;
1089}
1090
1091/****************
1092 * Return the length of the digest in bytes.
1093 * This function will return 0 in case of errors.
1094 */
1095unsigned int
1096gcry_md_get_algo_dlen (int algorithm)
1097{
1098  return md_digest_length (algorithm);
1099}
1100
1101
1102/* Hmmm: add a mode to enumerate the OIDs
1103 *	to make g10/sig-check.c more portable */
1104static const byte *
1105md_asn_oid (int algorithm, size_t *asnlen, size_t *mdlen)
1106{
1107  const byte *asnoid = NULL;
1108  gcry_module_t digest;
1109
1110  REGISTER_DEFAULT_DIGESTS;
1111
1112  ath_mutex_lock (&digests_registered_lock);
1113  digest = _gcry_module_lookup_id (digests_registered, algorithm);
1114  if (digest)
1115    {
1116      if (asnlen)
1117	*asnlen = ((gcry_md_spec_t *) digest->spec)->asnlen;
1118      if (mdlen)
1119	*mdlen = ((gcry_md_spec_t *) digest->spec)->mdlen;
1120      asnoid = ((gcry_md_spec_t *) digest->spec)->asnoid;
1121      _gcry_module_release (digest);
1122    }
1123  else
1124    log_bug ("no ASN.1 OID for md algo %d\n", algorithm);
1125  ath_mutex_unlock (&digests_registered_lock);
1126
1127  return asnoid;
1128}
1129
1130
1131
1132/****************
1133 * Return information about the given cipher algorithm
1134 * WHAT select the kind of information returned:
1135 *  GCRYCTL_TEST_ALGO:
1136 *	Returns 0 when the specified algorithm is available for use.
1137 *	buffer and nbytes must be zero.
1138 *  GCRYCTL_GET_ASNOID:
1139 *	Return the ASNOID of the algorithm in buffer. if buffer is NULL, only
1140 *	the required length is returned.
1141 *
1142 * Note:  Because this function is in most cases used to return an
1143 * integer value, we can make it easier for the caller to just look at
1144 * the return value.  The caller will in all cases consult the value
1145 * and thereby detecting whether a error occurred or not (i.e. while checking
1146 * the block size)
1147 */
1148gcry_error_t
1149gcry_md_algo_info (int algo, int what, void *buffer, size_t *nbytes)
1150{
1151  gcry_err_code_t err = GPG_ERR_NO_ERROR;
1152
1153  switch (what)
1154    {
1155    case GCRYCTL_TEST_ALGO:
1156      if (buffer || nbytes)
1157	err = GPG_ERR_INV_ARG;
1158      else
1159	err = check_digest_algo (algo);
1160      break;
1161
1162    case GCRYCTL_GET_ASNOID:
1163      /* We need to check that the algo is available because
1164         md_asn_oid would otherwise raise an assertion. */
1165      err = check_digest_algo (algo);
1166      if (!err)
1167        {
1168          const char unsigned *asn;
1169          size_t asnlen;
1170
1171          asn = md_asn_oid (algo, &asnlen, NULL);
1172          if (buffer && (*nbytes >= asnlen))
1173	  {
1174	    memcpy (buffer, asn, asnlen);
1175	    *nbytes = asnlen;
1176	  }
1177          else if (!buffer && nbytes)
1178            *nbytes = asnlen;
1179          else
1180            {
1181              if (buffer)
1182                err = GPG_ERR_TOO_SHORT;
1183              else
1184                err = GPG_ERR_INV_ARG;
1185            }
1186        }
1187      break;
1188
1189  default:
1190    err = GPG_ERR_INV_OP;
1191  }
1192
1193  return gcry_error (err);
1194}
1195
1196
1197static void
1198md_start_debug ( gcry_md_hd_t md, const char *suffix )
1199{
1200  static int idx=0;
1201  char buf[50];
1202
1203  if (fips_mode ())
1204    return;
1205
1206  if ( md->ctx->debug )
1207    {
1208      log_debug("Oops: md debug already started\n");
1209      return;
1210    }
1211  idx++;
1212  snprintf (buf, DIM(buf)-1, "dbgmd-%05d.%.10s", idx, suffix );
1213  md->ctx->debug = fopen(buf, "w");
1214  if ( !md->ctx->debug )
1215    log_debug("md debug: can't open %s\n", buf );
1216}
1217
1218static void
1219md_stop_debug( gcry_md_hd_t md )
1220{
1221  if ( md->ctx->debug )
1222    {
1223      if ( md->bufpos )
1224        md_write ( md, NULL, 0 );
1225      fclose (md->ctx->debug);
1226      md->ctx->debug = NULL;
1227    }
1228
1229#ifdef HAVE_U64_TYPEDEF
1230  {  /* a kludge to pull in the __muldi3 for Solaris */
1231    volatile u32 a = (u32)(ulong)md;
1232    volatile u64 b = 42;
1233    volatile u64 c;
1234    c = a * b;
1235    (void)c;
1236  }
1237#endif
1238}
1239
1240
1241
1242/*
1243 * Return information about the digest handle.
1244 *  GCRYCTL_IS_SECURE:
1245 *	Returns 1 when the handle works on secured memory
1246 *	otherwise 0 is returned.  There is no error return.
1247 *  GCRYCTL_IS_ALGO_ENABLED:
1248 *     Returns 1 if the algo is enabled for that handle.
1249 *     The algo must be passed as the address of an int.
1250 */
1251gcry_error_t
1252gcry_md_info (gcry_md_hd_t h, int cmd, void *buffer, size_t *nbytes)
1253{
1254  gcry_err_code_t err = GPG_ERR_NO_ERROR;
1255
1256  switch (cmd)
1257    {
1258    case GCRYCTL_IS_SECURE:
1259      *nbytes = h->ctx->secure;
1260      break;
1261
1262    case GCRYCTL_IS_ALGO_ENABLED:
1263      {
1264	GcryDigestEntry *r;
1265	int algo;
1266
1267	if ( !buffer || (nbytes && (*nbytes != sizeof (int))))
1268	  err = GPG_ERR_INV_ARG;
1269	else
1270	  {
1271	    algo = *(int*)buffer;
1272
1273	    *nbytes = 0;
1274	    for(r=h->ctx->list; r; r = r->next ) {
1275	      if (r->module->mod_id == algo)
1276		{
1277		  *nbytes = 1;
1278		  break;
1279		}
1280	    }
1281	  }
1282	break;
1283      }
1284
1285  default:
1286    err = GPG_ERR_INV_OP;
1287  }
1288
1289  return gcry_error (err);
1290}
1291
1292
1293/* Explicitly initialize this module.  */
1294gcry_err_code_t
1295_gcry_md_init (void)
1296{
1297  gcry_err_code_t err = GPG_ERR_NO_ERROR;
1298
1299  REGISTER_DEFAULT_DIGESTS;
1300
1301  return err;
1302}
1303
1304
1305int
1306gcry_md_is_secure (gcry_md_hd_t a)
1307{
1308  size_t value;
1309
1310  if (gcry_md_info (a, GCRYCTL_IS_SECURE, NULL, &value))
1311    value = 1; /* It seems to be better to assume secure memory on
1312                  error. */
1313  return value;
1314}
1315
1316
1317int
1318gcry_md_is_enabled (gcry_md_hd_t a, int algo)
1319{
1320  size_t value;
1321
1322  value = sizeof algo;
1323  if (gcry_md_info (a, GCRYCTL_IS_ALGO_ENABLED, &algo, &value))
1324    value = 0;
1325  return value;
1326}
1327
1328/* Get a list consisting of the IDs of the loaded message digest
1329   modules.  If LIST is zero, write the number of loaded message
1330   digest modules to LIST_LENGTH and return.  If LIST is non-zero, the
1331   first *LIST_LENGTH algorithm IDs are stored in LIST, which must be
1332   of according size.  In case there are less message digest modules
1333   than *LIST_LENGTH, *LIST_LENGTH is updated to the correct
1334   number.  */
1335gcry_error_t
1336gcry_md_list (int *list, int *list_length)
1337{
1338  gcry_err_code_t err = GPG_ERR_NO_ERROR;
1339
1340  ath_mutex_lock (&digests_registered_lock);
1341  err = _gcry_module_list (digests_registered, list, list_length);
1342  ath_mutex_unlock (&digests_registered_lock);
1343
1344  return err;
1345}
1346
1347
1348/* Run the selftests for digest algorithm ALGO with optional reporting
1349   function REPORT.  */
1350gpg_error_t
1351_gcry_md_selftest (int algo, int extended, selftest_report_func_t report)
1352{
1353  gcry_module_t module = NULL;
1354  cipher_extra_spec_t *extraspec = NULL;
1355  gcry_err_code_t ec = 0;
1356
1357  REGISTER_DEFAULT_DIGESTS;
1358
1359  ath_mutex_lock (&digests_registered_lock);
1360  module = _gcry_module_lookup_id (digests_registered, algo);
1361  if (module && !(module->flags & FLAG_MODULE_DISABLED))
1362    extraspec = module->extraspec;
1363  ath_mutex_unlock (&digests_registered_lock);
1364  if (extraspec && extraspec->selftest)
1365    ec = extraspec->selftest (algo, extended, report);
1366  else
1367    {
1368      ec = GPG_ERR_DIGEST_ALGO;
1369      if (report)
1370        report ("digest", algo, "module",
1371                module && !(module->flags & FLAG_MODULE_DISABLED)?
1372                "no selftest available" :
1373                module? "algorithm disabled" : "algorithm not found");
1374    }
1375
1376  if (module)
1377    {
1378      ath_mutex_lock (&digests_registered_lock);
1379      _gcry_module_release (module);
1380      ath_mutex_unlock (&digests_registered_lock);
1381    }
1382  return gpg_error (ec);
1383}
1384