adding new GNUNET_HELPER_ API for communication with (SUID) helper binaries via stdin...
[oweals/gnunet.git] / src / util / crypto_hash.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19
20      SHA-512 code by Jean-Luc Cooke <jlcooke@certainkey.com>
21
22      Copyright (c) Jean-Luc Cooke <jlcooke@certainkey.com>
23      Copyright (c) Andrew McDonald <andrew@mcdonald.org.uk>
24      Copyright (c) 2003 Kyle McMartin <kyle@debian.org>
25 */
26
27 /**
28  * @file util/crypto_hash.c
29  * @brief SHA-512 GNUNET_CRYPTO_hash related functions
30  * @author Christian Grothoff
31  */
32
33 #include "platform.h"
34 #include "gnunet_common.h"
35 #include "gnunet_crypto_lib.h"
36 #include "gnunet_disk_lib.h"
37 #include <gcrypt.h>
38
39 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
40
41 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
42
43 /**
44  * Hash block of given size.
45  *
46  * @param block the data to GNUNET_CRYPTO_hash, length is given as a second argument
47  * @param size the length of the data to GNUNET_CRYPTO_hash
48  * @param ret pointer to where to write the hashcode
49  */
50 void
51 GNUNET_CRYPTO_hash (const void *block, size_t size, GNUNET_HashCode * ret)
52 {
53   gcry_md_hash_buffer (GCRY_MD_SHA512, ret, block, size);
54 }
55
56
57 /**
58  * Context used when hashing a file.
59  */
60 struct GNUNET_CRYPTO_FileHashContext
61 {
62
63   /**
64    * Function to call upon completion.
65    */
66   GNUNET_CRYPTO_HashCompletedCallback callback;
67
68   /**
69    * Closure for callback.
70    */
71   void *callback_cls;
72
73   /**
74    * IO buffer.
75    */
76   unsigned char *buffer;
77
78   /**
79    * Name of the file we are hashing.
80    */
81   char *filename;
82
83   /**
84    * File descriptor.
85    */
86   struct GNUNET_DISK_FileHandle *fh;
87
88   /**
89    * Cummulated hash.
90    */
91   gcry_md_hd_t md;
92
93   /**
94    * Size of the file.
95    */
96   uint64_t fsize;
97
98   /**
99    * Current offset.
100    */
101   uint64_t offset;
102
103   /**
104    * Current task for hashing.
105    */
106   GNUNET_SCHEDULER_TaskIdentifier task;
107
108   /**
109    * Priority we use.
110    */
111   enum GNUNET_SCHEDULER_Priority priority;
112
113   /**
114    * Blocksize.
115    */
116   size_t bsize;
117
118 };
119
120
121 /**
122  * Report result of hash computation to callback
123  * and free associated resources.
124  */
125 static void
126 file_hash_finish (struct GNUNET_CRYPTO_FileHashContext *fhc,
127                   const GNUNET_HashCode * res)
128 {
129   fhc->callback (fhc->callback_cls, res);
130   GNUNET_free (fhc->filename);
131   if (!GNUNET_DISK_handle_invalid (fhc->fh))
132     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fhc->fh));
133   gcry_md_close (fhc->md);
134   GNUNET_free (fhc);            /* also frees fhc->buffer */
135 }
136
137
138 /**
139  * File hashing task.
140  *
141  * @param cls closure
142  * @param tc context
143  */
144 static void
145 file_hash_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
146 {
147   struct GNUNET_CRYPTO_FileHashContext *fhc = cls;
148   GNUNET_HashCode *res;
149   size_t delta;
150
151   fhc->task = GNUNET_SCHEDULER_NO_TASK;
152   GNUNET_assert (fhc->offset <= fhc->fsize);
153   delta = fhc->bsize;
154   if (fhc->fsize - fhc->offset < delta)
155     delta = fhc->fsize - fhc->offset;
156   if (delta != GNUNET_DISK_file_read (fhc->fh, fhc->buffer, delta))
157   {
158     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "read", fhc->filename);
159     file_hash_finish (fhc, NULL);
160     return;
161   }
162   gcry_md_write (fhc->md, fhc->buffer, delta);
163   fhc->offset += delta;
164   if (fhc->offset == fhc->fsize)
165   {
166     res = (GNUNET_HashCode *) gcry_md_read (fhc->md, GCRY_MD_SHA512);
167     file_hash_finish (fhc, res);
168     return;
169   }
170   fhc->task = GNUNET_SCHEDULER_add_with_priority (fhc->priority,
171                                                   &file_hash_task, fhc);
172 }
173
174
175 /**
176  * Compute the hash of an entire file.
177  *
178  * @param priority scheduling priority to use
179  * @param filename name of file to hash
180  * @param blocksize number of bytes to process in one task
181  * @param callback function to call upon completion
182  * @param callback_cls closure for callback
183  * @return NULL on (immediate) errror
184  */
185 struct GNUNET_CRYPTO_FileHashContext *
186 GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority,
187                          const char *filename, size_t blocksize,
188                          GNUNET_CRYPTO_HashCompletedCallback callback,
189                          void *callback_cls)
190 {
191   struct GNUNET_CRYPTO_FileHashContext *fhc;
192
193   GNUNET_assert (blocksize > 0);
194   fhc =
195       GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_FileHashContext) + blocksize);
196   fhc->callback = callback;
197   fhc->callback_cls = callback_cls;
198   fhc->buffer = (unsigned char *) &fhc[1];
199   fhc->filename = GNUNET_strdup (filename);
200   if (GPG_ERR_NO_ERROR != gcry_md_open (&fhc->md, GCRY_MD_SHA512, 0))
201   {
202     GNUNET_break (0);
203     GNUNET_free (fhc);
204     return NULL;
205   }
206   fhc->bsize = blocksize;
207   if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fhc->fsize, GNUNET_NO))
208   {
209     GNUNET_free (fhc->filename);
210     GNUNET_free (fhc);
211     return NULL;
212   }
213   fhc->fh =
214       GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
215                              GNUNET_DISK_PERM_NONE);
216   if (!fhc->fh)
217   {
218     GNUNET_free (fhc->filename);
219     GNUNET_free (fhc);
220     return NULL;
221   }
222   fhc->priority = priority;
223   fhc->task =
224       GNUNET_SCHEDULER_add_with_priority (priority, &file_hash_task, fhc);
225   return fhc;
226 }
227
228
229 /**
230  * Cancel a file hashing operation.
231  *
232  * @param fhc operation to cancel (callback must not yet have been invoked)
233  */
234 void
235 GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc)
236 {
237   GNUNET_SCHEDULER_cancel (fhc->task);
238   GNUNET_free (fhc->filename);
239   GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fhc->fh));
240   GNUNET_free (fhc);
241 }
242
243
244
245 /* ***************** binary-ASCII encoding *************** */
246
247 static unsigned int
248 getValue__ (unsigned char a)
249 {
250   if ((a >= '0') && (a <= '9'))
251     return a - '0';
252   if ((a >= 'A') && (a <= 'V'))
253     return (a - 'A' + 10);
254   return -1;
255 }
256
257 /**
258  * Convert GNUNET_CRYPTO_hash to ASCII encoding.  The ASCII encoding is rather
259  * GNUnet specific.  It was chosen such that it only uses characters
260  * in [0-9A-V], can be produced without complex arithmetics and uses a
261  * small number of characters.  The GNUnet encoding uses 103
262  * characters plus a null terminator.
263  *
264  * @param block the hash code
265  * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
266  *  safely cast to char*, a '\\0' termination is set).
267  */
268 void
269 GNUNET_CRYPTO_hash_to_enc (const GNUNET_HashCode * block,
270                            struct GNUNET_CRYPTO_HashAsciiEncoded *result)
271 {
272   /**
273    * 32 characters for encoding (GNUNET_CRYPTO_hash => 32 characters)
274    */
275   static char *encTable__ = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
276   unsigned int wpos;
277   unsigned int rpos;
278   unsigned int bits;
279   unsigned int vbit;
280
281   GNUNET_assert (block != NULL);
282   GNUNET_assert (result != NULL);
283   vbit = 0;
284   wpos = 0;
285   rpos = 0;
286   bits = 0;
287   while ((rpos < sizeof (GNUNET_HashCode)) || (vbit > 0))
288   {
289     if ((rpos < sizeof (GNUNET_HashCode)) && (vbit < 5))
290     {
291       bits = (bits << 8) | ((unsigned char *) block)[rpos++];   /* eat 8 more bits */
292       vbit += 8;
293     }
294     if (vbit < 5)
295     {
296       bits <<= (5 - vbit);      /* zero-padding */
297       GNUNET_assert (vbit == 2);        /* padding by 3: 512+3 mod 5 == 0 */
298       vbit = 5;
299     }
300     GNUNET_assert (wpos < sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
301     result->encoding[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
302     vbit -= 5;
303   }
304   GNUNET_assert (wpos == sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
305   GNUNET_assert (vbit == 0);
306   result->encoding[wpos] = '\0';
307 }
308
309 /**
310  * Convert ASCII encoding back to GNUNET_CRYPTO_hash
311  *
312  * @param enc the encoding
313  * @param result where to store the GNUNET_CRYPTO_hash code
314  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
315  */
316 int
317 GNUNET_CRYPTO_hash_from_string (const char *enc, GNUNET_HashCode * result)
318 {
319   unsigned int rpos;
320   unsigned int wpos;
321   unsigned int bits;
322   unsigned int vbit;
323
324   if (strlen (enc) != sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1)
325     return GNUNET_SYSERR;
326
327   vbit = 2;                     /* padding! */
328   wpos = sizeof (GNUNET_HashCode);
329   rpos = sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1;
330   bits = getValue__ (enc[--rpos]) >> 3;
331   while (wpos > 0)
332   {
333     GNUNET_assert (rpos > 0);
334     bits = (getValue__ (enc[--rpos]) << vbit) | bits;
335     vbit += 5;
336     if (vbit >= 8)
337     {
338       ((unsigned char *) result)[--wpos] = (unsigned char) bits;
339       bits >>= 8;
340       vbit -= 8;
341     }
342   }
343   GNUNET_assert (rpos == 0);
344   GNUNET_assert (vbit == 0);
345   return GNUNET_OK;
346 }
347
348 /**
349  * Compute the distance between 2 hashcodes.  The computation must be
350  * fast, not involve bits[0] or bits[4] (they're used elsewhere), and be
351  * somewhat consistent. And of course, the result should be a positive
352  * number.
353  *
354  * @param a some hash code
355  * @param b some hash code
356  * @return a positive number which is a measure for
357  *  hashcode proximity.
358  */
359 unsigned int
360 GNUNET_CRYPTO_hash_distance_u32 (const GNUNET_HashCode * a,
361                                  const GNUNET_HashCode * b)
362 {
363   unsigned int x1 = (a->bits[1] - b->bits[1]) >> 16;
364   unsigned int x2 = (b->bits[1] - a->bits[1]) >> 16;
365
366   return (x1 * x2);
367 }
368
369 void
370 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
371                                   GNUNET_HashCode * result)
372 {
373   int i;
374
375   for (i = (sizeof (GNUNET_HashCode) / sizeof (uint32_t)) - 1; i >= 0; i--)
376     result->bits[i] = GNUNET_CRYPTO_random_u32 (mode, UINT32_MAX);
377 }
378
379 void
380 GNUNET_CRYPTO_hash_difference (const GNUNET_HashCode * a,
381                                const GNUNET_HashCode * b,
382                                GNUNET_HashCode * result)
383 {
384   int i;
385
386   for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
387     result->bits[i] = b->bits[i] - a->bits[i];
388 }
389
390 void
391 GNUNET_CRYPTO_hash_sum (const GNUNET_HashCode * a,
392                         const GNUNET_HashCode * delta, GNUNET_HashCode * result)
393 {
394   int i;
395
396   for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
397     result->bits[i] = delta->bits[i] + a->bits[i];
398 }
399
400
401 void
402 GNUNET_CRYPTO_hash_xor (const GNUNET_HashCode * a, const GNUNET_HashCode * b,
403                         GNUNET_HashCode * result)
404 {
405   int i;
406
407   for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
408     result->bits[i] = a->bits[i] ^ b->bits[i];
409 }
410
411
412 /**
413  * Convert a hashcode into a key.
414  */
415 void
416 GNUNET_CRYPTO_hash_to_aes_key (const GNUNET_HashCode * hc,
417                                struct GNUNET_CRYPTO_AesSessionKey *skey,
418                                struct GNUNET_CRYPTO_AesInitializationVector *iv)
419 {
420   GNUNET_assert (sizeof (GNUNET_HashCode) >=
421                  GNUNET_CRYPTO_AES_KEY_LENGTH +
422                  sizeof (struct GNUNET_CRYPTO_AesInitializationVector));
423   memcpy (skey, hc, GNUNET_CRYPTO_AES_KEY_LENGTH);
424   skey->crc32 =
425       htonl (GNUNET_CRYPTO_crc32_n (skey, GNUNET_CRYPTO_AES_KEY_LENGTH));
426   memcpy (iv, &((char *) hc)[GNUNET_CRYPTO_AES_KEY_LENGTH],
427           sizeof (struct GNUNET_CRYPTO_AesInitializationVector));
428 }
429
430
431 /**
432  * Obtain a bit from a hashcode.
433  * @param code the GNUNET_CRYPTO_hash to index bit-wise
434  * @param bit index into the hashcode, [0...511]
435  * @return Bit \a bit from hashcode \a code, -1 for invalid index
436  */
437 int
438 GNUNET_CRYPTO_hash_get_bit (const GNUNET_HashCode * code, unsigned int bit)
439 {
440   GNUNET_assert (bit < 8 * sizeof (GNUNET_HashCode));
441   return (((unsigned char *) code)[bit >> 3] & (1 << (bit & 7))) > 0;
442 }
443
444 /**
445  * Determine how many low order bits match in two
446  * GNUNET_HashCodes.  i.e. - 010011 and 011111 share
447  * the first two lowest order bits, and therefore the
448  * return value is two (NOT XOR distance, nor how many
449  * bits match absolutely!).
450  *
451  * @param first the first hashcode
452  * @param second the hashcode to compare first to
453  *
454  * @return the number of bits that match
455  */
456 unsigned int
457 GNUNET_CRYPTO_hash_matching_bits (const GNUNET_HashCode * first,
458                                   const GNUNET_HashCode * second)
459 {
460   unsigned int i;
461
462   for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
463     if (GNUNET_CRYPTO_hash_get_bit (first, i) !=
464         GNUNET_CRYPTO_hash_get_bit (second, i))
465       return i;
466   return sizeof (GNUNET_HashCode) * 8;
467 }
468
469
470 /**
471  * Compare function for HashCodes, producing a total ordering
472  * of all hashcodes.
473  * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
474  */
475 int
476 GNUNET_CRYPTO_hash_cmp (const GNUNET_HashCode * h1, const GNUNET_HashCode * h2)
477 {
478   unsigned int *i1;
479   unsigned int *i2;
480   int i;
481
482   i1 = (unsigned int *) h1;
483   i2 = (unsigned int *) h2;
484   for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
485   {
486     if (i1[i] > i2[i])
487       return 1;
488     if (i1[i] < i2[i])
489       return -1;
490   }
491   return 0;
492 }
493
494
495 /**
496  * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
497  * in the XOR metric (Kademlia).
498  * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
499  */
500 int
501 GNUNET_CRYPTO_hash_xorcmp (const GNUNET_HashCode * h1,
502                            const GNUNET_HashCode * h2,
503                            const GNUNET_HashCode * target)
504 {
505   int i;
506   unsigned int d1;
507   unsigned int d2;
508
509   for (i = sizeof (GNUNET_HashCode) / sizeof (unsigned int) - 1; i >= 0; i--)
510   {
511     d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i];
512     d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i];
513     if (d1 > d2)
514       return 1;
515     else if (d1 < d2)
516       return -1;
517   }
518   return 0;
519 }
520
521
522 /**
523  * @brief Derive an authentication key
524  * @param key authentication key
525  * @param rkey root key
526  * @param salt salt
527  * @param salt_len size of the salt
528  * @param ... pair of void * & size_t for context chunks, terminated by NULL
529  */
530 void
531 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
532                                const struct GNUNET_CRYPTO_AesSessionKey *rkey,
533                                const void *salt, size_t salt_len, ...)
534 {
535   va_list argp;
536
537   va_start (argp, salt_len);
538   GNUNET_CRYPTO_hmac_derive_key_v (key, rkey, salt, salt_len, argp);
539   va_end (argp);
540 }
541
542
543 /**
544  * @brief Derive an authentication key
545  * @param key authentication key
546  * @param rkey root key
547  * @param salt salt
548  * @param salt_len size of the salt
549  * @param argp pair of void * & size_t for context chunks, terminated by NULL
550  */
551 void
552 GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
553                                  const struct GNUNET_CRYPTO_AesSessionKey *rkey,
554                                  const void *salt, size_t salt_len,
555                                  va_list argp)
556 {
557   GNUNET_CRYPTO_kdf_v (key->key, sizeof (key->key), salt, salt_len, rkey->key,
558                        sizeof (rkey->key), argp);
559 }
560
561
562 /**
563  * Calculate HMAC of a message (RFC 2104)
564  *
565  * @param key secret key
566  * @param plaintext input plaintext
567  * @param plaintext_len length of plaintext
568  * @param hmac where to store the hmac
569  */
570 void
571 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
572                     const void *plaintext, size_t plaintext_len,
573                     GNUNET_HashCode * hmac)
574 {
575   gcry_md_hd_t md;
576   const unsigned char *mc;
577
578   GNUNET_assert (GPG_ERR_NO_ERROR ==
579                  gcry_md_open (&md, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC));
580   gcry_md_setkey (md, key->key, sizeof (key->key));
581   gcry_md_write (md, plaintext, plaintext_len);
582   mc = gcry_md_read (md, GCRY_MD_SHA512);
583   if (mc != NULL)
584     memcpy (hmac->bits, mc, sizeof (hmac->bits));
585   gcry_md_close (md);
586 }
587
588
589 /* end of crypto_hash.c */