tolerate additional IPv4 address now available for gnunet.org
[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     strncpy (vanity, prefix, KEY_STR_LEN);
100     len = GNUNET_MIN (strlen (prefix), KEY_STR_LEN);
101     n = len * 5 / 8;
102     rest = len * 5 % 8;
103
104     memset (&vanity[len], '0', KEY_STR_LEN - len);
105     vanity[KEY_STR_LEN] = '\0';
106     GNUNET_assert (GNUNET_OK ==
107                    GNUNET_CRYPTO_eddsa_public_key_from_string (vanity,
108                                                                KEY_STR_LEN,
109                                                                &target_pub));
110     if (0 != rest)
111     {
112       /**
113        * Documentation by example:
114        * vanity = "A"
115        * len = 1
116        * n = 5/8 = 0 (bytes)
117        * rest = 5%8 = 5 (bits)
118        * mask = ~(2**(8 - 5) - 1) = ~(2**3 - 1) = ~(8 - 1) = ~b111 = b11111000
119        */
120       mask = ~ ((int)pow (2, 8 - rest) - 1);
121       target_byte = ((unsigned char *) &target_pub)[n] & mask;
122     }
123     else
124     {
125       /* Just so old (debian) versions of GCC calm down with the warnings. */
126       mask = target_byte = 0;
127     }
128     s = GNUNET_CRYPTO_eddsa_public_key_to_string (&target_pub);
129     fprintf (stderr,
130              _("Generating %u keys like %s, please wait"),
131              make_keys,
132              s);
133     GNUNET_free (s);
134     fprintf (stderr,
135              "\nattempt %s [%u, %X]\n",
136              vanity,
137              (unsigned int) n,
138              mask);
139   }
140   else
141   {
142     fprintf (stderr,
143              _("Generating %u keys, please wait"),
144              make_keys);
145     /* Just so old (debian) versions of GCC calm down with the warnings. */
146     n = rest = target_byte = mask = 0;
147   }
148
149   while (0 < make_keys--)
150   {
151     fprintf (stderr, ".");
152     if (NULL == (pk = GNUNET_CRYPTO_eddsa_key_create ()))
153     {
154        GNUNET_break (0);
155        break;
156     }
157     if (NULL != prefix)
158     {
159       struct GNUNET_CRYPTO_EddsaPublicKey newkey;
160
161       GNUNET_CRYPTO_eddsa_key_get_public (pk, &newkey);
162       if (0 != memcmp (&target_pub, &newkey, n))
163       {
164         make_keys++;
165         continue;
166       }
167       if (0 != rest)
168       {
169         unsigned char new_byte;
170
171         new_byte = ((unsigned char *) &newkey)[n] & mask;
172         if (target_byte != new_byte)
173         {
174           make_keys++;
175           continue;
176         }
177       }
178     }
179     if (GNUNET_TESTING_HOSTKEYFILESIZE !=
180         fwrite (pk, 1,
181                 GNUNET_TESTING_HOSTKEYFILESIZE, f))
182     {
183       fprintf (stderr,
184                _("\nFailed to write to `%s': %s\n"),
185                fn,
186                STRERROR (errno));
187       GNUNET_free (pk);
188       break;
189     }
190     GNUNET_free (pk);
191   }
192   if (UINT_MAX == make_keys)
193     fprintf (stderr,
194              _("\nFinished!\n"));
195   else
196     fprintf (stderr,
197              _("\nError, %u keys not generated\n"),
198              make_keys);
199   fclose (f);
200 }
201
202
203 static void
204 print_hex (const char *msg,
205            const void *buf,
206            size_t size)
207 {
208   printf ("%s: ", msg);
209   for (size_t i = 0; i < size; i++)
210   {
211     printf ("%02hhx", ((const uint8_t *)buf)[i]);
212   }
213   printf ("\n");
214 }
215
216
217 static void
218 print_examples_ecdh ()
219 {
220   struct GNUNET_CRYPTO_EcdhePrivateKey *dh_priv1;
221   struct GNUNET_CRYPTO_EcdhePublicKey *dh_pub1;
222   struct GNUNET_CRYPTO_EcdhePrivateKey *dh_priv2;
223   struct GNUNET_CRYPTO_EcdhePublicKey *dh_pub2;
224   struct GNUNET_HashCode hash;
225   char buf[128];
226
227   dh_pub1 = GNUNET_new (struct GNUNET_CRYPTO_EcdhePublicKey);
228   dh_priv1 = GNUNET_CRYPTO_ecdhe_key_create ();
229   dh_pub2 = GNUNET_new (struct GNUNET_CRYPTO_EcdhePublicKey);
230   dh_priv2 = GNUNET_CRYPTO_ecdhe_key_create ();
231   GNUNET_CRYPTO_ecdhe_key_get_public (dh_priv1, dh_pub1);
232   GNUNET_CRYPTO_ecdhe_key_get_public (dh_priv2, dh_pub2);
233
234   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_priv1, 32, buf, 128));
235   printf ("ECDHE key 1:\n");
236   printf ("private: %s\n", buf);
237   print_hex ("private(hex)", dh_priv1, sizeof *dh_priv1);
238   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_pub1, 32, buf, 128));
239   printf ("public: %s\n", buf);
240   print_hex ("public(hex)", dh_pub1, sizeof *dh_pub1);
241
242   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_priv2, 32, buf, 128));
243   printf ("ECDHE key 2:\n");
244   printf ("private: %s\n", buf);
245   print_hex ("private(hex)", dh_priv2, sizeof *dh_priv2);
246   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_pub2, 32, buf, 128));
247   printf ("public: %s\n", buf);
248   print_hex ("public(hex)", dh_pub2, sizeof *dh_pub2);
249
250   GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_ecc_ecdh (dh_priv1, dh_pub2, &hash));
251   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (&hash, 64, buf, 128));
252   printf ("ECDH shared secret: %s\n", buf);
253
254   GNUNET_free (dh_priv1);
255   GNUNET_free (dh_priv2);
256   GNUNET_free (dh_pub1);
257   GNUNET_free (dh_pub2);
258 }
259
260
261 /**
262  * Print some random example operations to stdout.
263  */
264 static void
265 print_examples ()
266 {
267   print_examples_ecdh ();
268   // print_examples_ecdsa ();
269   // print_examples_eddsa ();
270 }
271
272
273 static void
274 print_key (const char *filename)
275 {
276   struct GNUNET_DISK_FileHandle *fd;
277   struct GNUNET_CRYPTO_EddsaPrivateKey private_key;
278   struct GNUNET_CRYPTO_EddsaPublicKey public_key;
279   char *hostkeys_data;
280   char *hostkey_str;
281   uint64_t fs;
282   unsigned int total_hostkeys;
283   unsigned int c;
284   ssize_t sret;
285
286   if (GNUNET_YES !=
287       GNUNET_DISK_file_test (filename))
288   {
289     fprintf (stderr,
290              _("Hostkeys file `%s' not found\n"),
291              filename);
292     return;
293   }
294
295   /* Check hostkey file size, read entire thing into memory */
296   if (GNUNET_OK !=
297       GNUNET_DISK_file_size (filename,
298                              &fs,
299                              GNUNET_YES,
300                              GNUNET_YES))
301     fs = 0;
302   if (0 == fs)
303   {
304     fprintf (stderr,
305              _("Hostkeys file `%s' is empty\n"),
306              filename);
307     return;       /* File is empty */
308   }
309   if (0 != (fs % GNUNET_TESTING_HOSTKEYFILESIZE))
310   {
311     fprintf (stderr,
312              _("Incorrect hostkey file format: %s\n"),
313              filename);
314     return;
315   }
316   fd = GNUNET_DISK_file_open (filename,
317                               GNUNET_DISK_OPEN_READ,
318                               GNUNET_DISK_PERM_NONE);
319   if (NULL == fd)
320   {
321     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
322                               "open",
323                               filename);
324     return;
325   }
326   hostkeys_data = GNUNET_malloc (fs);
327   sret = GNUNET_DISK_file_read (fd,
328                                 hostkeys_data,
329                                 fs);
330   if ( (sret < 0) ||
331        (fs != (size_t) sret) )
332   {
333     fprintf (stderr,
334              _("Could not read hostkey file: %s\n"),
335              filename);
336     GNUNET_free (hostkeys_data);
337     GNUNET_DISK_file_close (fd);
338     return;
339   }
340   GNUNET_DISK_file_close (fd);
341
342   if (NULL == hostkeys_data)
343     return;
344   total_hostkeys = fs / GNUNET_TESTING_HOSTKEYFILESIZE;
345   for (c = 0; (c < total_hostkeys) && (c < list_keys_count); c++)
346   {
347     GNUNET_memcpy (&private_key,
348             hostkeys_data + (c * GNUNET_TESTING_HOSTKEYFILESIZE),
349             GNUNET_TESTING_HOSTKEYFILESIZE);
350     GNUNET_CRYPTO_eddsa_key_get_public (&private_key, &public_key);
351     hostkey_str = GNUNET_CRYPTO_eddsa_public_key_to_string (&public_key);
352     if (NULL != hostkey_str)
353     {
354       fprintf (stderr, "%4u: %s\n", c, hostkey_str);
355       GNUNET_free (hostkey_str);
356     }
357     else
358       fprintf (stderr, "%4u: %s\n", c, "invalid");
359   }
360   GNUNET_free (hostkeys_data);
361 }
362
363
364 /**
365  * Main function that will be run by the scheduler.
366  *
367  * @param cls closure, NULL
368  * @param args remaining command-line arguments
369  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
370  * @param cfg configuration
371  */
372 static void
373 run (void *cls,
374      char *const *args,
375      const char *cfgfile,
376      const struct GNUNET_CONFIGURATION_Handle *cfg)
377 {
378   (void) cls;
379   (void) cfgfile;
380   (void) cfg;
381   
382   if (print_examples_flag)
383   {
384     print_examples ();
385     return;
386   }
387   if (NULL == args[0])
388   {
389     FPRINTF (stderr,
390              "%s",
391              _("No hostkey file specified on command line\n"));
392     return;
393   }
394   if (list_keys)
395   {
396     print_key (args[0]);
397     return;
398   }
399   if (make_keys > 0)
400   {
401     create_keys (args[0], args[1]);
402     return;
403   }
404   if (print_public_key || print_public_key_hex || print_private_key)
405   {
406     char *str;
407     struct GNUNET_DISK_FileHandle *keyfile;
408     struct GNUNET_CRYPTO_EddsaPrivateKey pk;
409     struct GNUNET_CRYPTO_EddsaPublicKey pub;
410
411     keyfile = GNUNET_DISK_file_open (args[0], GNUNET_DISK_OPEN_READ,
412                                      GNUNET_DISK_PERM_NONE);
413     if (NULL == keyfile)
414       return;
415     while (sizeof (pk) ==
416            GNUNET_DISK_file_read (keyfile, &pk, sizeof (pk)))
417     {
418       GNUNET_CRYPTO_eddsa_key_get_public (&pk, &pub);
419       if (print_public_key_hex)
420       {
421         print_hex ("HEX:", &pub, sizeof (pub));
422       }
423       else if (print_public_key)
424       {
425         str = GNUNET_CRYPTO_eddsa_public_key_to_string (&pub);
426         FPRINTF (stdout, "%s\n", str);
427         GNUNET_free (str);
428       }
429       else if (print_private_key)
430       {
431         str = GNUNET_CRYPTO_eddsa_private_key_to_string (&pk);
432         FPRINTF (stdout, "%s\n", str);
433         GNUNET_free (str);
434       }
435     }
436     GNUNET_DISK_file_close (keyfile);
437   }
438
439 }
440
441
442 /**
443  * Program to manipulate ECC key files.
444  *
445  * @param argc number of arguments from the command line
446  * @param argv command line arguments
447  * @return 0 ok, 1 on error
448  */
449 int
450 main (int argc,
451       char *const *argv)
452 {
453   struct GNUNET_GETOPT_CommandLineOption options[] = {
454     GNUNET_GETOPT_option_flag ('i',
455                                "iterate",
456                                gettext_noop ("list keys included in a file (for testing)"),
457                                &list_keys),
458     GNUNET_GETOPT_option_uint ('e',
459                                "end=",
460                                "COUNT",
461                                gettext_noop ("number of keys to list included in a file (for testing)"),
462                                &list_keys_count),
463     GNUNET_GETOPT_option_uint ('g',
464                                "generate-keys",
465                                "COUNT",
466                                gettext_noop ("create COUNT public-private key pairs (for testing)"),
467                                &make_keys),
468     GNUNET_GETOPT_option_flag ('p',
469                                "print-public-key",
470                                gettext_noop ("print the public key in ASCII format"),
471                                &print_public_key),
472     GNUNET_GETOPT_option_flag ('P',
473                                "print-private-key",
474                                gettext_noop ("print the private key in ASCII format"),
475                                &print_private_key),
476     GNUNET_GETOPT_option_flag ('x',
477                                "print-hex",
478                                gettext_noop ("print the public key in HEX format"),
479                                &print_public_key_hex),
480     GNUNET_GETOPT_option_flag ('E',
481                                "examples",
482                                gettext_noop ("print examples of ECC operations (used for compatibility testing)"),
483                                &print_examples_flag),
484     GNUNET_GETOPT_OPTION_END
485   };
486   int ret;
487
488   list_keys_count = UINT32_MAX;
489   if (GNUNET_OK !=
490       GNUNET_STRINGS_get_utf8_args (argc, argv,
491                                     &argc, &argv))
492     return 2;
493
494   ret = (GNUNET_OK ==
495          GNUNET_PROGRAM_run (argc,
496                              argv,
497                              "gnunet-ecc [OPTIONS] keyfile [VANITY_PREFIX]",
498                              gettext_noop ("Manipulate GNUnet private ECC key files"),
499                              options,
500                              &run,
501                              NULL)) ? 0 : 1;
502   GNUNET_free ((void*) argv);
503   return ret;
504 }
505
506 /* end of gnunet-ecc.c */