- log
[oweals/gnunet.git] / src / gnsrecord / gnsrecord_crypto.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009-2013 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file gnsrecord/gnsrecord_crypto.c
23  * @brief API for GNS record-related crypto
24  * @author Martin Schanzenbach
25  * @author Matthias Wachs
26  * @author Christian Grothoff
27  */
28 #include "platform.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_constants.h"
31 #include "gnunet_signatures.h"
32 #include "gnunet_arm_service.h"
33 #include "gnunet_gnsrecord_lib.h"
34 #include "gnunet_dnsparser_lib.h"
35 #include "gnunet_tun_lib.h"
36
37
38 #define LOG(kind,...) GNUNET_log_from (kind, "gnsrecord",__VA_ARGS__)
39
40
41 /**
42  * Derive session key and iv from label and public key.
43  *
44  * @param iv initialization vector to initialize
45  * @param skey session key to initialize
46  * @param label label to use for KDF
47  * @param pub public key to use for KDF
48  */
49 static void
50 derive_block_aes_key (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
51                       struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
52                       const char *label,
53                       const struct GNUNET_CRYPTO_EcdsaPublicKey *pub)
54 {
55   static const char ctx_key[] = "gns-aes-ctx-key";
56   static const char ctx_iv[] = "gns-aes-ctx-iv";
57
58   GNUNET_CRYPTO_kdf (skey, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
59                      pub, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
60                      label, strlen (label),
61                      ctx_key, strlen (ctx_key),
62                      NULL, 0);
63   GNUNET_CRYPTO_kdf (iv, sizeof (struct GNUNET_CRYPTO_SymmetricInitializationVector),
64                      pub, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
65                      label, strlen (label),
66                      ctx_iv, strlen (ctx_iv),
67                      NULL, 0);
68 }
69
70
71 /**
72  * Sign name and records
73  *
74  * @param key the private key
75  * @param expire block expiration
76  * @param label the name for the records
77  * @param rd record data
78  * @param rd_count number of records
79  * @return NULL on error (block too large)
80  */
81 struct GNUNET_GNSRECORD_Block *
82 GNUNET_GNSRECORD_block_create (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key,
83                                struct GNUNET_TIME_Absolute expire,
84                                const char *label,
85                                const struct GNUNET_GNSRECORD_Data *rd,
86                                unsigned int rd_count)
87 {
88   size_t payload_len = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
89   char payload[sizeof (uint32_t) + payload_len];
90   struct GNUNET_GNSRECORD_Block *block;
91   struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
92   struct GNUNET_CRYPTO_EcdsaPrivateKey *dkey;
93   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
94   struct GNUNET_CRYPTO_SymmetricSessionKey skey;
95   struct GNUNET_GNSRECORD_Data rdc[rd_count];
96   uint32_t rd_count_nbo;
97   unsigned int i;
98   struct GNUNET_TIME_Absolute now;
99
100   if (payload_len > GNUNET_GNSRECORD_MAX_BLOCK_SIZE)
101     return NULL;
102   /* convert relative to absolute times */
103   now = GNUNET_TIME_absolute_get ();
104   for (i=0;i<rd_count;i++)
105   {
106     rdc[i] = rd[i];
107     if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION))
108     {
109       /* encrypted blocks must never have relative expiration times, convert! */
110       rdc[i].flags &= ~GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION;
111       rdc[i].expiration_time += now.abs_value_us;
112     }
113   }
114   /* serialize */
115   rd_count_nbo = htonl (rd_count);
116   memcpy (payload, &rd_count_nbo, sizeof (uint32_t));
117   GNUNET_assert (payload_len ==
118                  GNUNET_GNSRECORD_records_serialize (rd_count, rdc,
119                                                      payload_len, &payload[sizeof (uint32_t)]));
120   block = GNUNET_malloc (sizeof (struct GNUNET_GNSRECORD_Block) +
121                          sizeof (uint32_t) + payload_len);
122   block->purpose.size = htonl (sizeof (uint32_t) + payload_len +
123                                sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
124                                sizeof (struct GNUNET_TIME_AbsoluteNBO));
125   block->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_GNS_RECORD_SIGN);
126   block->expiration_time = GNUNET_TIME_absolute_hton (expire);
127   /* encrypt and sign */
128   dkey = GNUNET_CRYPTO_ecdsa_private_key_derive (key,
129                                                  label,
130                                                  "gns");
131   GNUNET_CRYPTO_ecdsa_key_get_public (dkey,
132                                     &block->derived_key);
133   GNUNET_CRYPTO_ecdsa_key_get_public (key,
134                                     &pkey);
135   derive_block_aes_key (&iv, &skey, label, &pkey);
136   GNUNET_break (payload_len + sizeof (uint32_t) ==
137                 GNUNET_CRYPTO_symmetric_encrypt (payload, payload_len + sizeof (uint32_t),
138                                                  &skey, &iv,
139                                                  &block[1]));
140   if (GNUNET_OK !=
141       GNUNET_CRYPTO_ecdsa_sign (dkey,
142                               &block->purpose,
143                               &block->signature))
144   {
145     GNUNET_break (0);
146     GNUNET_free (dkey);
147     GNUNET_free (block);
148     return NULL;
149   }
150   GNUNET_free (dkey);
151   return block;
152 }
153
154
155 /**
156  * Check if a signature is valid.  This API is used by the GNS Block
157  * to validate signatures received from the network.
158  *
159  * @param block block to verify
160  * @return #GNUNET_OK if the signature is valid
161  */
162 int
163 GNUNET_GNSRECORD_block_verify (const struct GNUNET_GNSRECORD_Block *block)
164 {
165   return GNUNET_CRYPTO_ecdsa_verify (GNUNET_SIGNATURE_PURPOSE_GNS_RECORD_SIGN,
166                                    &block->purpose,
167                                    &block->signature,
168                                    &block->derived_key);
169 }
170
171
172 /**
173  * Decrypt block.
174  *
175  * @param block block to decrypt
176  * @param zone_key public key of the zone
177  * @param label the name for the records
178  * @param proc function to call with the result
179  * @param proc_cls closure for proc
180  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the block was
181  *        not well-formed
182  */
183 int
184 GNUNET_GNSRECORD_block_decrypt (const struct GNUNET_GNSRECORD_Block *block,
185                                 const struct GNUNET_CRYPTO_EcdsaPublicKey *zone_key,
186                                 const char *label,
187                                 GNUNET_GNSRECORD_RecordCallback proc,
188                                 void *proc_cls)
189 {
190   size_t payload_len = ntohl (block->purpose.size) -
191     sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) -
192     sizeof (struct GNUNET_TIME_AbsoluteNBO);
193   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
194   struct GNUNET_CRYPTO_SymmetricSessionKey skey;
195
196   if (ntohl (block->purpose.size) <
197       sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
198       sizeof (struct GNUNET_TIME_AbsoluteNBO))
199   {
200     GNUNET_break_op (0);
201     return GNUNET_SYSERR;
202   }
203   derive_block_aes_key (&iv, &skey, label, zone_key);
204   {
205     char payload[payload_len];
206     uint32_t rd_count;
207
208     GNUNET_break (payload_len ==
209                   GNUNET_CRYPTO_symmetric_decrypt (&block[1], payload_len,
210                                              &skey, &iv,
211                                              payload));
212     memcpy (&rd_count,
213             payload,
214             sizeof (uint32_t));
215     rd_count = ntohl (rd_count);
216     if (rd_count > 2048)
217     {
218       /* limit to sane value */
219       GNUNET_break_op (0);
220       return GNUNET_SYSERR;
221     }
222     {
223       struct GNUNET_GNSRECORD_Data rd[rd_count];
224       unsigned int i;
225       unsigned int j;
226       unsigned int k;
227       struct GNUNET_TIME_Absolute now;
228
229       if (GNUNET_OK !=
230           GNUNET_GNSRECORD_records_deserialize (payload_len - sizeof (uint32_t),
231                                                 &payload[sizeof (uint32_t)],
232                                                 rd_count,
233                                                 rd))
234       {
235         GNUNET_break_op (0);
236         return GNUNET_SYSERR;
237       }
238       /* hide expired records */
239       now = GNUNET_TIME_absolute_get ();
240       j = 0;
241       for (i=0;i<rd_count;i++)
242       {
243         if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_PENDING))
244           continue; /* PENDING should never be used */
245         if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION))
246         {
247           /* encrypted blocks must never have relative expiration times, skip! */
248           GNUNET_break_op (0);
249           continue;
250         }
251
252         if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_SHADOW_RECORD))
253         {
254           int include_record = GNUNET_YES;
255           /* Shadow record, figure out if we have a not expired active record */
256           for (k=0;k<rd_count;k++)
257           {
258             if (k == i)
259               continue;
260             if (rd[i].expiration_time < now.abs_value_us)
261               include_record = GNUNET_NO; /* Shadow record is expired */
262             if ((rd[k].record_type == rd[i].record_type)
263                 && (rd[k].expiration_time >= now.abs_value_us)
264                 && (0 == (rd[k].flags & GNUNET_GNSRECORD_RF_SHADOW_RECORD)))
265               include_record = GNUNET_NO; /* We have a non-expired, non-shadow record of the same type */
266           }
267           if (GNUNET_YES == include_record)
268           {
269             rd[i].flags ^= GNUNET_GNSRECORD_RF_SHADOW_RECORD; /* Remove Flag */
270             if (j != i)
271               rd[j] = rd[i];
272             j++;
273           }
274         }
275         else if (rd[i].expiration_time >= now.abs_value_us)
276         {
277           /* Include this record */
278           if (j != i)
279             rd[j] = rd[i];
280           j++;
281         }
282       }
283       rd_count = j;
284       if (NULL != proc)
285         proc (proc_cls, rd_count, (0 != rd_count) ? rd : NULL);
286     }
287   }
288   return GNUNET_OK;
289 }
290
291
292 /**
293  * Calculate the DHT query for a given @a label in a given @a zone.
294  *
295  * @param zone private key of the zone
296  * @param label label of the record
297  * @param query hash to use for the query
298  */
299 void
300 GNUNET_GNSRECORD_query_from_private_key (const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
301                                          const char *label,
302                                          struct GNUNET_HashCode *query)
303 {
304   struct GNUNET_CRYPTO_EcdsaPublicKey pub;
305
306   GNUNET_CRYPTO_ecdsa_key_get_public (zone, &pub);
307   GNUNET_GNSRECORD_query_from_public_key (&pub, label, query);
308 }
309
310
311 /**
312  * Calculate the DHT query for a given @a label in a given @a zone.
313  *
314  * @param pub public key of the zone
315  * @param label label of the record
316  * @param query hash to use for the query
317  */
318 void
319 GNUNET_GNSRECORD_query_from_public_key (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub,
320                                         const char *label,
321                                         struct GNUNET_HashCode *query)
322 {
323   struct GNUNET_CRYPTO_EcdsaPublicKey pd;
324
325   GNUNET_CRYPTO_ecdsa_public_key_derive (pub, label, "gns", &pd);
326   GNUNET_CRYPTO_hash (&pd, sizeof (pd), query);
327 }
328
329
330 /* end of gnsrecord_crypto.c */