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