Merge branch 'cadet-new-options'
[oweals/gnunet.git] / src / util / crypto_ecc_setup.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2012, 2013, 2015 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/crypto_ecc_setup.c
23  * @brief helper function for easy EdDSA key setup
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include <gcrypt.h>
28 #include "gnunet_util_lib.h"
29
30 #define LOG(kind,...) GNUNET_log_from (kind, "util-crypto-ecc", __VA_ARGS__)
31
32 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-crypto-ecc", syscall)
33
34 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-crypto-ecc", syscall, filename)
35
36 /**
37  * Log an error message at log-level 'level' that indicates
38  * a failure of the command 'cmd' with the message given
39  * by gcry_strerror(rc).
40  */
41 #define LOG_GCRY(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gcry_strerror(rc)); } while(0)
42
43
44 /**
45  * Wait for a short time (we're trying to lock a file or want
46  * to give another process a shot at finishing a disk write, etc.).
47  * Sleeps for 100ms (as that should be long enough for virtually all
48  * modern systems to context switch and allow another process to do
49  * some 'real' work).
50  */
51 static void
52 short_wait ()
53 {
54   struct GNUNET_TIME_Relative timeout;
55
56   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
57   (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
58 }
59
60
61 /**
62  * Create a new private key by reading it from a file.  If the
63  * files does not exist, create a new key and write it to the
64  * file.  Caller must free return value.  Note that this function
65  * can not guarantee that another process might not be trying
66  * the same operation on the same file at the same time.
67  * If the contents of the file
68  * are invalid the old file is deleted and a fresh key is
69  * created.
70  *
71  * @param filename name of file to use to store the key
72  * @return new private key, NULL on error (for example,
73  *   permission denied)
74  */
75 struct GNUNET_CRYPTO_EddsaPrivateKey *
76 GNUNET_CRYPTO_eddsa_key_create_from_file (const char *filename)
77 {
78   struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
79   struct GNUNET_DISK_FileHandle *fd;
80   unsigned int cnt;
81   int ec;
82   uint64_t fs;
83   ssize_t sret;
84
85   if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
86     return NULL;
87   while (GNUNET_YES != GNUNET_DISK_file_test (filename))
88   {
89     fd = GNUNET_DISK_file_open (filename,
90                                 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
91                                 | GNUNET_DISK_OPEN_FAILIFEXISTS,
92                                 GNUNET_DISK_PERM_USER_READ |
93                                 GNUNET_DISK_PERM_USER_WRITE);
94     if (NULL == fd)
95     {
96       if (EEXIST == errno)
97       {
98         if (GNUNET_YES != GNUNET_DISK_file_test (filename))
99         {
100           /* must exist but not be accessible, fail for good! */
101           if (0 != ACCESS (filename, R_OK))
102             LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
103           else
104             GNUNET_break (0);   /* what is going on!? */
105           return NULL;
106         }
107         continue;
108       }
109       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
110       return NULL;
111     }
112     cnt = 0;
113     while (GNUNET_YES !=
114            GNUNET_DISK_file_lock (fd, 0,
115                                   sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey),
116                                   GNUNET_YES))
117     {
118       short_wait ();
119       if (0 == ++cnt % 10)
120       {
121         ec = errno;
122         LOG (GNUNET_ERROR_TYPE_ERROR,
123              _("Could not acquire lock on file `%s': %s...\n"),
124              filename,
125              STRERROR (ec));
126       }
127     }
128     LOG (GNUNET_ERROR_TYPE_INFO,
129          _("Creating a new private key.  This may take a while.\n"));
130     priv = GNUNET_CRYPTO_eddsa_key_create ();
131     GNUNET_assert (NULL != priv);
132     GNUNET_assert (sizeof (*priv) ==
133                    GNUNET_DISK_file_write (fd, priv, sizeof (*priv)));
134     GNUNET_DISK_file_sync (fd);
135     if (GNUNET_YES !=
136         GNUNET_DISK_file_unlock (fd, 0,
137                                  sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey)))
138       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
139     GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
140     return priv;
141   }
142   /* key file exists already, read it! */
143   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
144                               GNUNET_DISK_PERM_NONE);
145   if (NULL == fd)
146   {
147     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
148     return NULL;
149   }
150   cnt = 0;
151   while (1)
152   {
153     if (GNUNET_YES !=
154         GNUNET_DISK_file_lock (fd, 0,
155                                sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey),
156                                GNUNET_NO))
157     {
158       if (0 == ++cnt % 60)
159       {
160         ec = errno;
161         LOG (GNUNET_ERROR_TYPE_ERROR,
162              _("Could not acquire lock on file `%s': %s...\n"), filename,
163              STRERROR (ec));
164         LOG (GNUNET_ERROR_TYPE_ERROR,
165              _
166              ("This may be ok if someone is currently generating a private key.\n"));
167       }
168       short_wait ();
169       continue;
170     }
171     if (GNUNET_YES != GNUNET_DISK_file_test (filename))
172     {
173       /* eh, what!? File we opened is now gone!? */
174       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
175       if (GNUNET_YES !=
176           GNUNET_DISK_file_unlock (fd, 0,
177                                    sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey)))
178         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
179       GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
180
181       return NULL;
182     }
183     if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
184       fs = 0;
185     if (fs < sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey))
186     {
187       /* maybe we got the read lock before the key generating
188        * process had a chance to get the write lock; give it up! */
189       if (GNUNET_YES !=
190           GNUNET_DISK_file_unlock (fd, 0,
191                                    sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey)))
192         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
193       if (0 == ++cnt % 10)
194       {
195         LOG (GNUNET_ERROR_TYPE_ERROR,
196              _("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
197              filename,
198              (unsigned int) fs,
199              (unsigned int) sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey));
200         LOG (GNUNET_ERROR_TYPE_ERROR,
201              _("This may be ok if someone is currently generating a key.\n"));
202       }
203       short_wait ();                /* wait a bit longer! */
204       continue;
205     }
206     break;
207   }
208   fs = sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey);
209   priv = GNUNET_malloc (fs);
210   sret = GNUNET_DISK_file_read (fd,
211                                 priv,
212                                 fs);
213   GNUNET_assert ( (sret >= 0) &&
214                   (fs == (size_t) sret) );
215   if (GNUNET_YES !=
216       GNUNET_DISK_file_unlock (fd,
217                                0,
218                                sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey)))
219     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
220                        "fcntl",
221                        filename);
222   GNUNET_assert (GNUNET_YES ==
223                  GNUNET_DISK_file_close (fd));
224 #if CRYPTO_BUG
225   if (GNUNET_OK !=
226       check_eddsa_key (priv))
227   {
228     GNUNET_break (0);
229     GNUNET_free (priv);
230     return NULL;
231   }
232 #endif
233   return priv;
234 }
235
236
237 /**
238  * Create a new private key by reading it from a file.  If the
239  * files does not exist, create a new key and write it to the
240  * file.  Caller must free return value.  Note that this function
241  * can not guarantee that another process might not be trying
242  * the same operation on the same file at the same time.
243  * If the contents of the file
244  * are invalid the old file is deleted and a fresh key is
245  * created.
246  *
247  * @param filename name of file to use to store the key
248  * @return new private key, NULL on error (for example,
249  *   permission denied)
250  */
251 struct GNUNET_CRYPTO_EcdsaPrivateKey *
252 GNUNET_CRYPTO_ecdsa_key_create_from_file (const char *filename)
253 {
254   struct GNUNET_CRYPTO_EcdsaPrivateKey *priv;
255   struct GNUNET_DISK_FileHandle *fd;
256   unsigned int cnt;
257   int ec;
258   uint64_t fs;
259   ssize_t sret;
260
261   if (GNUNET_SYSERR ==
262       GNUNET_DISK_directory_create_for_file (filename))
263     return NULL;
264   while (GNUNET_YES != GNUNET_DISK_file_test (filename))
265   {
266     fd = GNUNET_DISK_file_open (filename,
267                                 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
268                                 | GNUNET_DISK_OPEN_FAILIFEXISTS,
269                                 GNUNET_DISK_PERM_USER_READ |
270                                 GNUNET_DISK_PERM_USER_WRITE);
271     if (NULL == fd)
272     {
273       if (EEXIST == errno)
274       {
275         if (GNUNET_YES != GNUNET_DISK_file_test (filename))
276         {
277           /* must exist but not be accessible, fail for good! */
278           if (0 != ACCESS (filename, R_OK))
279             LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR,
280                                "access",
281                                filename);
282           else
283             GNUNET_break (0);   /* what is going on!? */
284           return NULL;
285         }
286         continue;
287       }
288       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR,
289                          "open",
290                          filename);
291       return NULL;
292     }
293     cnt = 0;
294     while (GNUNET_YES !=
295            GNUNET_DISK_file_lock (fd,
296                                   0,
297                                   sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
298                                   GNUNET_YES))
299     {
300       short_wait ();
301       if (0 == ++cnt % 10)
302       {
303         ec = errno;
304         LOG (GNUNET_ERROR_TYPE_ERROR,
305              _("Could not acquire lock on file `%s': %s...\n"),
306              filename,
307              STRERROR (ec));
308       }
309     }
310     LOG (GNUNET_ERROR_TYPE_INFO,
311          _("Creating a new private key.  This may take a while.\n"));
312     priv = GNUNET_CRYPTO_ecdsa_key_create ();
313     GNUNET_assert (NULL != priv);
314     GNUNET_assert (sizeof (*priv) ==
315                    GNUNET_DISK_file_write (fd,
316                                            priv,
317                                            sizeof (*priv)));
318     GNUNET_DISK_file_sync (fd);
319     if (GNUNET_YES !=
320         GNUNET_DISK_file_unlock (fd, 0,
321                                  sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
322       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
323                          "fcntl",
324                          filename);
325     GNUNET_assert (GNUNET_YES ==
326                    GNUNET_DISK_file_close (fd));
327     return priv;
328   }
329   /* key file exists already, read it! */
330   fd = GNUNET_DISK_file_open (filename,
331                               GNUNET_DISK_OPEN_READ,
332                               GNUNET_DISK_PERM_NONE);
333   if (NULL == fd)
334   {
335     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR,
336                        "open",
337                        filename);
338     return NULL;
339   }
340   cnt = 0;
341   while (1)
342   {
343     if (GNUNET_YES !=
344         GNUNET_DISK_file_lock (fd, 0,
345                                sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
346                                GNUNET_NO))
347     {
348       if (0 == ++cnt % 60)
349       {
350         ec = errno;
351         LOG (GNUNET_ERROR_TYPE_ERROR,
352              _("Could not acquire lock on file `%s': %s...\n"),
353              filename,
354              STRERROR (ec));
355         LOG (GNUNET_ERROR_TYPE_ERROR,
356              _("This may be ok if someone is currently generating a private key.\n"));
357       }
358       short_wait ();
359       continue;
360     }
361     if (GNUNET_YES !=
362         GNUNET_DISK_file_test (filename))
363     {
364       /* eh, what!? File we opened is now gone!? */
365       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
366                          "stat",
367                          filename);
368       if (GNUNET_YES !=
369           GNUNET_DISK_file_unlock (fd, 0,
370                                    sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
371         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
372                            "fcntl",
373                            filename);
374       GNUNET_assert (GNUNET_OK ==
375                      GNUNET_DISK_file_close (fd));
376
377       return NULL;
378     }
379     if (GNUNET_OK !=
380         GNUNET_DISK_file_size (filename,
381                                &fs,
382                                GNUNET_YES,
383                                GNUNET_YES))
384       fs = 0;
385     if (fs < sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))
386     {
387       /* maybe we got the read lock before the key generating
388        * process had a chance to get the write lock; give it up! */
389       if (GNUNET_YES !=
390           GNUNET_DISK_file_unlock (fd, 0,
391                                    sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
392         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
393                            "fcntl",
394                            filename);
395       if (0 == ++cnt % 10)
396       {
397         LOG (GNUNET_ERROR_TYPE_ERROR,
398              _("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
399              filename, (unsigned int) fs,
400              (unsigned int) sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
401         LOG (GNUNET_ERROR_TYPE_ERROR,
402              _("This may be ok if someone is currently generating a key.\n"));
403       }
404       short_wait ();                /* wait a bit longer! */
405       continue;
406     }
407     break;
408   }
409   fs = sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey);
410   priv = GNUNET_malloc (fs);
411   sret = GNUNET_DISK_file_read (fd,
412                                 priv,
413                                 fs);
414   GNUNET_assert ( (sret >= 0) &&
415                   (fs == (size_t) sret) );
416   if (GNUNET_YES !=
417       GNUNET_DISK_file_unlock (fd, 0,
418                                sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
419     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
420                        "fcntl",
421                        filename);
422   GNUNET_assert (GNUNET_YES ==
423                  GNUNET_DISK_file_close (fd));
424   return priv;
425 }
426
427
428 /**
429  * Create a new private key by reading our peer's key from
430  * the file specified in the configuration.
431  *
432  * @param cfg the configuration to use
433  * @return new private key, NULL on error (for example,
434  *   permission denied)
435  */
436 struct GNUNET_CRYPTO_EddsaPrivateKey *
437 GNUNET_CRYPTO_eddsa_key_create_from_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
438 {
439   struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
440   char *fn;
441
442   if (GNUNET_OK !=
443       GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
444     return NULL;
445   priv = GNUNET_CRYPTO_eddsa_key_create_from_file (fn);
446   GNUNET_free (fn);
447   return priv;
448 }
449
450
451 /**
452  * Retrieve the identity of the host's peer.
453  *
454  * @param cfg configuration to use
455  * @param dst pointer to where to write the peer identity
456  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the identity
457  *         could not be retrieved
458  */
459 int
460 GNUNET_CRYPTO_get_peer_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
461                                  struct GNUNET_PeerIdentity *dst)
462 {
463   struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
464
465   if (NULL == (priv = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg)))
466   {
467     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
468                 _("Could not load peer's private key\n"));
469     return GNUNET_SYSERR;
470   }
471   GNUNET_CRYPTO_eddsa_key_get_public (priv, &dst->public_key);
472   GNUNET_free (priv);
473   return GNUNET_OK;
474 }
475
476
477 /**
478  * Setup a key file for a peer given the name of the
479  * configuration file (!).  This function is used so that
480  * at a later point code can be certain that reading a
481  * key is fast (for example in time-dependent testcases).
482  *
483  * @param cfg_name name of the configuration file to use
484  */
485 void
486 GNUNET_CRYPTO_eddsa_setup_key (const char *cfg_name)
487 {
488   struct GNUNET_CONFIGURATION_Handle *cfg;
489   struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
490
491   cfg = GNUNET_CONFIGURATION_create ();
492   (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
493   priv = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
494   if (NULL != priv)
495     GNUNET_free (priv);
496   GNUNET_CONFIGURATION_destroy (cfg);
497 }
498
499 /* end of crypto_ecc_setup.c */