e7caf9ded3a5348f940ac7f6510a2399c21096aa
[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
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      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      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
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   return priv;
225 }
226
227
228 /**
229  * Create a new private key by reading it from a file.  If the
230  * files does not exist, create a new key and write it to the
231  * file.  Caller must free return value.  Note that this function
232  * can not guarantee that another process might not be trying
233  * the same operation on the same file at the same time.
234  * If the contents of the file
235  * are invalid the old file is deleted and a fresh key is
236  * created.
237  *
238  * @param filename name of file to use to store the key
239  * @return new private key, NULL on error (for example,
240  *   permission denied)
241  */
242 struct GNUNET_CRYPTO_EcdsaPrivateKey *
243 GNUNET_CRYPTO_ecdsa_key_create_from_file (const char *filename)
244 {
245   struct GNUNET_CRYPTO_EcdsaPrivateKey *priv;
246   struct GNUNET_DISK_FileHandle *fd;
247   unsigned int cnt;
248   int ec;
249   uint64_t fs;
250   ssize_t sret;
251   
252   if (GNUNET_SYSERR ==
253       GNUNET_DISK_directory_create_for_file (filename))
254     return NULL;
255   while (GNUNET_YES != GNUNET_DISK_file_test (filename))
256   {
257     fd = GNUNET_DISK_file_open (filename,
258                                 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
259                                 | GNUNET_DISK_OPEN_FAILIFEXISTS,
260                                 GNUNET_DISK_PERM_USER_READ |
261                                 GNUNET_DISK_PERM_USER_WRITE);
262     if (NULL == fd)
263     {
264       if (EEXIST == errno)
265       {
266         if (GNUNET_YES != GNUNET_DISK_file_test (filename))
267         {
268           /* must exist but not be accessible, fail for good! */
269           if (0 != ACCESS (filename, R_OK))
270             LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR,
271                                "access",
272                                filename);
273           else
274             GNUNET_break (0);   /* what is going on!? */
275           return NULL;
276         }
277         continue;
278       }
279       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR,
280                          "open",
281                          filename);
282       return NULL;
283     }
284     cnt = 0;
285     while (GNUNET_YES !=
286            GNUNET_DISK_file_lock (fd,
287                                   0,
288                                   sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
289                                   GNUNET_YES))
290     {
291       short_wait ();
292       if (0 == ++cnt % 10)
293       {
294         ec = errno;
295         LOG (GNUNET_ERROR_TYPE_ERROR,
296              _("Could not acquire lock on file `%s': %s...\n"),
297              filename,
298              STRERROR (ec));
299       }
300     }
301     LOG (GNUNET_ERROR_TYPE_INFO,
302          _("Creating a new private key.  This may take a while.\n"));
303     priv = GNUNET_CRYPTO_ecdsa_key_create ();
304     GNUNET_assert (NULL != priv);
305     GNUNET_assert (sizeof (*priv) ==
306                    GNUNET_DISK_file_write (fd,
307                                            priv,
308                                            sizeof (*priv)));
309     GNUNET_DISK_file_sync (fd);
310     if (GNUNET_YES !=
311         GNUNET_DISK_file_unlock (fd, 0,
312                                  sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
313       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
314                          "fcntl",
315                          filename);
316     GNUNET_assert (GNUNET_YES ==
317                    GNUNET_DISK_file_close (fd));
318     return priv;
319   }
320   /* key file exists already, read it! */
321   fd = GNUNET_DISK_file_open (filename,
322                               GNUNET_DISK_OPEN_READ,
323                               GNUNET_DISK_PERM_NONE);
324   if (NULL == fd)
325   {
326     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR,
327                        "open",
328                        filename);
329     return NULL;
330   }
331   cnt = 0;
332   while (1)
333   {
334     if (GNUNET_YES !=
335         GNUNET_DISK_file_lock (fd, 0,
336                                sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
337                                GNUNET_NO))
338     {
339       if (0 == ++cnt % 60)
340       {
341         ec = errno;
342         LOG (GNUNET_ERROR_TYPE_ERROR,
343              _("Could not acquire lock on file `%s': %s...\n"),
344              filename,
345              STRERROR (ec));
346         LOG (GNUNET_ERROR_TYPE_ERROR,
347              _("This may be ok if someone is currently generating a private key.\n"));
348       }
349       short_wait ();
350       continue;
351     }
352     if (GNUNET_YES !=
353         GNUNET_DISK_file_test (filename))
354     {
355       /* eh, what!? File we opened is now gone!? */
356       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
357                          "stat",
358                          filename);
359       if (GNUNET_YES !=
360           GNUNET_DISK_file_unlock (fd, 0,
361                                    sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
362         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
363                            "fcntl",
364                            filename);
365       GNUNET_assert (GNUNET_OK ==
366                      GNUNET_DISK_file_close (fd));
367
368       return NULL;
369     }
370     if (GNUNET_OK !=
371         GNUNET_DISK_file_size (filename,
372                                &fs,
373                                GNUNET_YES,
374                                GNUNET_YES))
375       fs = 0;
376     if (fs < sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))
377     {
378       /* maybe we got the read lock before the key generating
379        * process had a chance to get the write lock; give it up! */
380       if (GNUNET_YES !=
381           GNUNET_DISK_file_unlock (fd, 0,
382                                    sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
383         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
384                            "fcntl",
385                            filename);
386       if (0 == ++cnt % 10)
387       {
388         LOG (GNUNET_ERROR_TYPE_ERROR,
389              _("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
390              filename, (unsigned int) fs,
391              (unsigned int) sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
392         LOG (GNUNET_ERROR_TYPE_ERROR,
393              _("This may be ok if someone is currently generating a key.\n"));
394       }
395       short_wait ();                /* wait a bit longer! */
396       continue;
397     }
398     break;
399   }
400   fs = sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey);
401   priv = GNUNET_malloc (fs);
402   sret = GNUNET_DISK_file_read (fd,
403                                 priv,
404                                 fs);
405   GNUNET_assert ( (sret >= 0) &&
406                   (fs == (size_t) sret) );
407   if (GNUNET_YES !=
408       GNUNET_DISK_file_unlock (fd, 0,
409                                sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
410     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
411                        "fcntl",
412                        filename);
413   GNUNET_assert (GNUNET_YES ==
414                  GNUNET_DISK_file_close (fd));
415   return priv;
416 }
417
418
419 /**
420  * Create a new private key by reading our peer's key from
421  * the file specified in the configuration.
422  *
423  * @param cfg the configuration to use
424  * @return new private key, NULL on error (for example,
425  *   permission denied)
426  */
427 struct GNUNET_CRYPTO_EddsaPrivateKey *
428 GNUNET_CRYPTO_eddsa_key_create_from_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
429 {
430   struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
431   char *fn;
432
433   if (GNUNET_OK !=
434       GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
435     return NULL;
436   priv = GNUNET_CRYPTO_eddsa_key_create_from_file (fn);
437   GNUNET_free (fn);
438   return priv;
439 }
440
441
442 /**
443  * Retrieve the identity of the host's peer.
444  *
445  * @param cfg configuration to use
446  * @param dst pointer to where to write the peer identity
447  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the identity
448  *         could not be retrieved
449  */
450 int
451 GNUNET_CRYPTO_get_peer_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
452                                  struct GNUNET_PeerIdentity *dst)
453 {
454   struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
455
456   if (NULL == (priv = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg)))
457   {
458     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
459                 _("Could not load peer's private key\n"));
460     return GNUNET_SYSERR;
461   }
462   GNUNET_CRYPTO_eddsa_key_get_public (priv, &dst->public_key);
463   GNUNET_free (priv);
464   return GNUNET_OK;
465 }
466
467
468 /**
469  * Setup a key file for a peer given the name of the
470  * configuration file (!).  This function is used so that
471  * at a later point code can be certain that reading a
472  * key is fast (for example in time-dependent testcases).
473  *
474  * @param cfg_name name of the configuration file to use
475  */
476 void
477 GNUNET_CRYPTO_eddsa_setup_key (const char *cfg_name)
478 {
479   struct GNUNET_CONFIGURATION_Handle *cfg;
480   struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
481
482   cfg = GNUNET_CONFIGURATION_create ();
483   (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
484   priv = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
485   if (NULL != priv)
486     GNUNET_free (priv);
487   GNUNET_CONFIGURATION_destroy (cfg);
488 }
489
490 /* end of crypto_ecc_setup.c */