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