use NULL value in load_path_suffix to NOT load any files
[oweals/gnunet.git] / src / util / gnunet-ecc.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2012, 2013 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19  */
20
21 /**
22  * @file util/gnunet-ecc.c
23  * @brief tool to manipulate EDDSA key files
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_testing_lib.h"
29 #include <gcrypt.h>
30
31 /**
32  * Number of characters a Base32-encoded public key requires.
33  */
34 #define KEY_STR_LEN sizeof(struct GNUNET_CRYPTO_EddsaPublicKey) * 8 / 5 + 1
35
36 /**
37  * Flag for listing public key.
38  */
39 static int list_keys;
40
41 /**
42  * Flag for listing public key.
43  */
44 static unsigned int list_keys_count;
45
46 /**
47  * Flag for printing public key.
48  */
49 static int print_public_key;
50
51 /**
52  * Flag for printing private key.
53  */
54 static int print_private_key;
55
56 /**
57  * Flag for printing public key in hex.
58  */
59 static int print_public_key_hex;
60
61 /**
62  * Flag for printing the output of random example operations.
63  */
64 static int print_examples_flag;
65
66 /**
67  * Option set to create a bunch of keys at once.
68  */
69 static unsigned int make_keys;
70
71
72 /**
73  * Create a flat file with a large number of key pairs for testing.
74  *
75  * @param fn File name to store the keys.
76  * @param prefix Desired prefix for the public keys, NULL if any key is OK.
77  */
78 static void
79 create_keys (const char *fn, const char *prefix)
80 {
81   FILE *f;
82   struct GNUNET_CRYPTO_EddsaPrivateKey *pk;
83   struct GNUNET_CRYPTO_EddsaPublicKey target_pub;
84   static char vanity[KEY_STR_LEN + 1];
85   size_t len;
86   size_t n;
87   size_t rest;
88   unsigned char mask;
89   unsigned target_byte;
90   char *s;
91
92   if (NULL == (f = fopen (fn, "w+")))
93   {
94     fprintf (stderr, _ ("Failed to open `%s': %s\n"), fn, strerror (errno));
95     return;
96   }
97   if (NULL != prefix)
98   {
99     len = GNUNET_strlcpy (vanity, prefix, sizeof(vanity));
100     n = len * 5 / 8;
101     rest = len * 5 % 8;
102
103     memset (&vanity[len], '0', KEY_STR_LEN - len);
104     vanity[KEY_STR_LEN] = '\0';
105     GNUNET_assert (GNUNET_OK ==
106                    GNUNET_CRYPTO_eddsa_public_key_from_string (vanity,
107                                                                KEY_STR_LEN,
108                                                                &target_pub));
109     if (0 != rest)
110     {
111       /**
112        * Documentation by example:
113        * vanity = "A"
114        * len = 1
115        * n = 5/8 = 0 (bytes)
116        * rest = 5%8 = 5 (bits)
117        * mask = ~(2**(8 - 5) - 1) = ~(2**3 - 1) = ~(8 - 1) = ~b111 = b11111000
118        */mask = ~((int) pow (2, 8 - rest) - 1);
119       target_byte = ((unsigned char *) &target_pub)[n] & mask;
120     }
121     else
122     {
123       /* Just so old (debian) versions of GCC calm down with the warnings. */
124       mask = target_byte = 0;
125     }
126     s = GNUNET_CRYPTO_eddsa_public_key_to_string (&target_pub);
127     fprintf (stderr,
128              _ ("Generating %u keys like %s, please wait"),
129              make_keys,
130              s);
131     GNUNET_free (s);
132     fprintf (stderr, "\nattempt %s [%u, %X]\n", vanity, (unsigned int) n, mask);
133   }
134   else
135   {
136     fprintf (stderr, _ ("Generating %u keys, please wait"), make_keys);
137     /* Just so old (debian) versions of GCC calm down with the warnings. */
138     n = rest = target_byte = mask = 0;
139   }
140
141   while (0 < make_keys--)
142   {
143     fprintf (stderr, ".");
144     if (NULL == (pk = GNUNET_CRYPTO_eddsa_key_create ()))
145     {
146       GNUNET_break (0);
147       break;
148     }
149     if (NULL != prefix)
150     {
151       struct GNUNET_CRYPTO_EddsaPublicKey newkey;
152
153       GNUNET_CRYPTO_eddsa_key_get_public (pk, &newkey);
154       if (0 != memcmp (&target_pub, &newkey, n))
155       {
156         make_keys++;
157         continue;
158       }
159       if (0 != rest)
160       {
161         unsigned char new_byte;
162
163         new_byte = ((unsigned char *) &newkey)[n] & mask;
164         if (target_byte != new_byte)
165         {
166           make_keys++;
167           continue;
168         }
169       }
170     }
171     if (GNUNET_TESTING_HOSTKEYFILESIZE !=
172         fwrite (pk, 1, GNUNET_TESTING_HOSTKEYFILESIZE, f))
173     {
174       fprintf (stderr,
175                _ ("\nFailed to write to `%s': %s\n"),
176                fn,
177                strerror (errno));
178       GNUNET_free (pk);
179       break;
180     }
181     GNUNET_free (pk);
182   }
183   if (UINT_MAX == make_keys)
184     fprintf (stderr, _ ("\nFinished!\n"));
185   else
186     fprintf (stderr, _ ("\nError, %u keys not generated\n"), make_keys);
187   fclose (f);
188 }
189
190
191 static void
192 print_hex (const char *msg, const void *buf, size_t size)
193 {
194   printf ("%s: ", msg);
195   for (size_t i = 0; i < size; i++)
196   {
197     printf ("%02hhx", ((const uint8_t *) buf)[i]);
198   }
199   printf ("\n");
200 }
201
202
203 static void
204 print_examples_ecdh ()
205 {
206   struct GNUNET_CRYPTO_EcdhePrivateKey *dh_priv1;
207   struct GNUNET_CRYPTO_EcdhePublicKey *dh_pub1;
208   struct GNUNET_CRYPTO_EcdhePrivateKey *dh_priv2;
209   struct GNUNET_CRYPTO_EcdhePublicKey *dh_pub2;
210   struct GNUNET_HashCode hash;
211   char buf[128];
212
213   dh_pub1 = GNUNET_new (struct GNUNET_CRYPTO_EcdhePublicKey);
214   dh_priv1 = GNUNET_CRYPTO_ecdhe_key_create ();
215   dh_pub2 = GNUNET_new (struct GNUNET_CRYPTO_EcdhePublicKey);
216   dh_priv2 = GNUNET_CRYPTO_ecdhe_key_create ();
217   GNUNET_CRYPTO_ecdhe_key_get_public (dh_priv1, dh_pub1);
218   GNUNET_CRYPTO_ecdhe_key_get_public (dh_priv2, dh_pub2);
219
220   GNUNET_assert (NULL !=
221                  GNUNET_STRINGS_data_to_string (dh_priv1, 32, buf, 128));
222   printf ("ECDHE key 1:\n");
223   printf ("private: %s\n", buf);
224   print_hex ("private(hex)", dh_priv1, sizeof *dh_priv1);
225   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_pub1, 32, buf, 128));
226   printf ("public: %s\n", buf);
227   print_hex ("public(hex)", dh_pub1, sizeof *dh_pub1);
228
229   GNUNET_assert (NULL !=
230                  GNUNET_STRINGS_data_to_string (dh_priv2, 32, buf, 128));
231   printf ("ECDHE key 2:\n");
232   printf ("private: %s\n", buf);
233   print_hex ("private(hex)", dh_priv2, sizeof *dh_priv2);
234   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_pub2, 32, buf, 128));
235   printf ("public: %s\n", buf);
236   print_hex ("public(hex)", dh_pub2, sizeof *dh_pub2);
237
238   GNUNET_assert (GNUNET_OK ==
239                  GNUNET_CRYPTO_ecc_ecdh (dh_priv1, dh_pub2, &hash));
240   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (&hash, 64, buf, 128));
241   printf ("ECDH shared secret: %s\n", buf);
242
243   GNUNET_free (dh_priv1);
244   GNUNET_free (dh_priv2);
245   GNUNET_free (dh_pub1);
246   GNUNET_free (dh_pub2);
247 }
248
249
250 /**
251  * Print some random example operations to stdout.
252  */
253 static void
254 print_examples ()
255 {
256   print_examples_ecdh ();
257   // print_examples_ecdsa ();
258   // print_examples_eddsa ();
259 }
260
261
262 static void
263 print_key (const char *filename)
264 {
265   struct GNUNET_DISK_FileHandle *fd;
266   struct GNUNET_CRYPTO_EddsaPrivateKey private_key;
267   struct GNUNET_CRYPTO_EddsaPublicKey public_key;
268   char *hostkeys_data;
269   char *hostkey_str;
270   uint64_t fs;
271   unsigned int total_hostkeys;
272   unsigned int c;
273   ssize_t sret;
274
275   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
276   {
277     fprintf (stderr, _ ("Hostkeys file `%s' not found\n"), filename);
278     return;
279   }
280
281   /* Check hostkey file size, read entire thing into memory */
282   if (GNUNET_OK !=
283       GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
284     fs = 0;
285   if (0 == fs)
286   {
287     fprintf (stderr, _ ("Hostkeys file `%s' is empty\n"), filename);
288     return;   /* File is empty */
289   }
290   if (0 != (fs % GNUNET_TESTING_HOSTKEYFILESIZE))
291   {
292     fprintf (stderr, _ ("Incorrect hostkey file format: %s\n"), filename);
293     return;
294   }
295   fd = GNUNET_DISK_file_open (filename,
296                               GNUNET_DISK_OPEN_READ,
297                               GNUNET_DISK_PERM_NONE);
298   if (NULL == fd)
299   {
300     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", filename);
301     return;
302   }
303   hostkeys_data = GNUNET_malloc (fs);
304   sret = GNUNET_DISK_file_read (fd, hostkeys_data, fs);
305   if ((sret < 0) || (fs != (size_t) sret))
306   {
307     fprintf (stderr, _ ("Could not read hostkey file: %s\n"), filename);
308     GNUNET_free (hostkeys_data);
309     GNUNET_DISK_file_close (fd);
310     return;
311   }
312   GNUNET_DISK_file_close (fd);
313
314   if (NULL == hostkeys_data)
315     return;
316   total_hostkeys = fs / GNUNET_TESTING_HOSTKEYFILESIZE;
317   for (c = 0; (c < total_hostkeys) && (c < list_keys_count); c++)
318   {
319     GNUNET_memcpy (&private_key,
320                    hostkeys_data + (c * GNUNET_TESTING_HOSTKEYFILESIZE),
321                    GNUNET_TESTING_HOSTKEYFILESIZE);
322     GNUNET_CRYPTO_eddsa_key_get_public (&private_key, &public_key);
323     hostkey_str = GNUNET_CRYPTO_eddsa_public_key_to_string (&public_key);
324     if (NULL != hostkey_str)
325     {
326       fprintf (stderr, "%4u: %s\n", c, hostkey_str);
327       GNUNET_free (hostkey_str);
328     }
329     else
330       fprintf (stderr, "%4u: %s\n", c, "invalid");
331   }
332   GNUNET_free (hostkeys_data);
333 }
334
335
336 /**
337  * Main function that will be run by the scheduler.
338  *
339  * @param cls closure, NULL
340  * @param args remaining command-line arguments
341  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
342  * @param cfg configuration
343  */
344 static void
345 run (void *cls,
346      char *const *args,
347      const char *cfgfile,
348      const struct GNUNET_CONFIGURATION_Handle *cfg)
349 {
350   (void) cls;
351   (void) cfgfile;
352   (void) cfg;
353
354   if (print_examples_flag)
355   {
356     print_examples ();
357     return;
358   }
359   if (NULL == args[0])
360   {
361     fprintf (stderr, "%s", _ ("No hostkey file specified on command line\n"));
362     return;
363   }
364   if (list_keys)
365   {
366     print_key (args[0]);
367     return;
368   }
369   if (make_keys > 0)
370   {
371     create_keys (args[0], args[1]);
372     return;
373   }
374   if (print_public_key || print_public_key_hex || print_private_key)
375   {
376     char *str;
377     struct GNUNET_DISK_FileHandle *keyfile;
378     struct GNUNET_CRYPTO_EddsaPrivateKey pk;
379     struct GNUNET_CRYPTO_EddsaPublicKey pub;
380
381     keyfile = GNUNET_DISK_file_open (args[0],
382                                      GNUNET_DISK_OPEN_READ,
383                                      GNUNET_DISK_PERM_NONE);
384     if (NULL == keyfile)
385       return;
386     while (sizeof(pk) == GNUNET_DISK_file_read (keyfile, &pk, sizeof(pk)))
387     {
388       GNUNET_CRYPTO_eddsa_key_get_public (&pk, &pub);
389       if (print_public_key_hex)
390       {
391         print_hex ("HEX:", &pub, sizeof(pub));
392       }
393       else if (print_public_key)
394       {
395         str = GNUNET_CRYPTO_eddsa_public_key_to_string (&pub);
396         fprintf (stdout, "%s\n", str);
397         GNUNET_free (str);
398       }
399       else if (print_private_key)
400       {
401         str = GNUNET_CRYPTO_eddsa_private_key_to_string (&pk);
402         fprintf (stdout, "%s\n", str);
403         GNUNET_free (str);
404       }
405     }
406     GNUNET_DISK_file_close (keyfile);
407   }
408 }
409
410
411 /**
412  * Program to manipulate ECC key files.
413  *
414  * @param argc number of arguments from the command line
415  * @param argv command line arguments
416  * @return 0 ok, 1 on error
417  */
418 int
419 main (int argc, char *const *argv)
420 {
421   struct GNUNET_GETOPT_CommandLineOption options[] =
422   { GNUNET_GETOPT_option_flag ('i',
423                                "iterate",
424                                gettext_noop (
425                                  "list keys included in a file (for testing)"),
426                                &list_keys),
427     GNUNET_GETOPT_option_uint (
428       'e',
429       "end=",
430       "COUNT",
431       gettext_noop ("number of keys to list included in a file (for testing)"),
432       &list_keys_count),
433     GNUNET_GETOPT_option_uint (
434       'g',
435       "generate-keys",
436       "COUNT",
437       gettext_noop ("create COUNT public-private key pairs (for testing)"),
438       &make_keys),
439     GNUNET_GETOPT_option_flag ('p',
440                                "print-public-key",
441                                gettext_noop (
442                                  "print the public key in ASCII format"),
443                                &print_public_key),
444     GNUNET_GETOPT_option_flag ('P',
445                                "print-private-key",
446                                gettext_noop (
447                                  "print the private key in ASCII format"),
448                                &print_private_key),
449     GNUNET_GETOPT_option_flag ('x',
450                                "print-hex",
451                                gettext_noop (
452                                  "print the public key in HEX format"),
453                                &print_public_key_hex),
454     GNUNET_GETOPT_option_flag (
455       'E',
456       "examples",
457       gettext_noop (
458         "print examples of ECC operations (used for compatibility testing)"),
459       &print_examples_flag),
460     GNUNET_GETOPT_OPTION_END };
461   int ret;
462
463   list_keys_count = UINT32_MAX;
464   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
465     return 2;
466
467   ret = (GNUNET_OK ==
468          GNUNET_PROGRAM_run (argc,
469                              argv,
470                              "gnunet-ecc [OPTIONS] keyfile [VANITY_PREFIX]",
471                              gettext_noop (
472                                "Manipulate GNUnet private ECC key files"),
473                              options,
474                              &run,
475                              NULL))
476         ? 0
477         : 1;
478   GNUNET_free ((void *) argv);
479   return ret;
480 }
481
482
483 /* end of gnunet-ecc.c */