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