-fix (mostly harmless) use of uninitialized variable
[oweals/gnunet.git] / src / core / gnunet-service-core_kx.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 core/gnunet-service-core_kx.c
23  * @brief code for managing the key exchange (SET_KEY, PING, PONG) with other peers
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet-service-core_kx.h"
28 #include "gnunet-service-core.h"
29 #include "gnunet-service-core_clients.h"
30 #include "gnunet-service-core_neighbours.h"
31 #include "gnunet-service-core_sessions.h"
32 #include "gnunet_statistics_service.h"
33 #include "gnunet_constants.h"
34 #include "gnunet_signatures.h"
35 #include "gnunet_protocols.h"
36 #include "core.h"
37
38
39 /**
40  * How long do we wait for SET_KEY confirmation initially?
41  */
42 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
43
44 /**
45  * What is the minimum frequency for a PING message?
46  */
47 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
48
49 /**
50  * How often do we rekey?
51  */
52 #define REKEY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
53
54 /**
55  * What time difference do we tolerate?
56  */
57 #define REKEY_TOLERANCE GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
58
59 /**
60  * What is the maximum age of a message for us to consider processing
61  * it?  Note that this looks at the timestamp used by the other peer,
62  * so clock skew between machines does come into play here.  So this
63  * should be picked high enough so that a little bit of clock skew
64  * does not prevent peers from connecting to us.
65  */
66 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
67
68
69
70 GNUNET_NETWORK_STRUCT_BEGIN
71
72 /**
73  * Message transmitted with the signed ephemeral key of a peer.  The
74  * session key is then derived from the two ephemeral keys (ECDHE).
75  */
76 struct EphemeralKeyMessage
77 {
78
79   /**
80    * Message type is #GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY.
81    */
82   struct GNUNET_MessageHeader header;
83
84   /**
85    * Status of the sender (should be in "enum PeerStateMachine"), nbo.
86    */
87   int32_t sender_status GNUNET_PACKED;
88
89   /**
90    * An ECC signature of the 'origin' asserting the validity of
91    * the given ephemeral key.
92    */
93   struct GNUNET_CRYPTO_EddsaSignature signature;
94
95   /**
96    * Information about what is being signed.
97    */
98   struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
99
100   /**
101    * At what time was this key created (beginning of validity).
102    */
103   struct GNUNET_TIME_AbsoluteNBO creation_time;
104
105   /**
106    * When does the given ephemeral key expire (end of validity).
107    */
108   struct GNUNET_TIME_AbsoluteNBO expiration_time;
109
110   /**
111    * Ephemeral public ECC key.
112    */
113   struct GNUNET_CRYPTO_EcdhePublicKey ephemeral_key;
114
115   /**
116    * Public key of the signing peer (persistent version, not the ephemeral public key).
117    */
118   struct GNUNET_PeerIdentity origin_identity;
119
120 };
121
122
123 /**
124  * We're sending an (encrypted) PING to the other peer to check if he
125  * can decrypt.  The other peer should respond with a PONG with the
126  * same content, except this time encrypted with the receiver's key.
127  */
128 struct PingMessage
129 {
130   /**
131    * Message type is #GNUNET_MESSAGE_TYPE_CORE_PING.
132    */
133   struct GNUNET_MessageHeader header;
134
135   /**
136    * Seed for the IV
137    */
138   uint32_t iv_seed GNUNET_PACKED;
139
140   /**
141    * Intended target of the PING, used primarily to check
142    * that decryption actually worked.
143    */
144   struct GNUNET_PeerIdentity target;
145
146   /**
147    * Random number chosen to make reply harder.
148    */
149   uint32_t challenge GNUNET_PACKED;
150 };
151
152
153 /**
154  * Response to a PING.  Includes data from the original PING.
155  */
156 struct PongMessage
157 {
158   /**
159    * Message type is #GNUNET_MESSAGE_TYPE_CORE_PONG.
160    */
161   struct GNUNET_MessageHeader header;
162
163   /**
164    * Seed for the IV
165    */
166   uint32_t iv_seed GNUNET_PACKED;
167
168   /**
169    * Random number to make faking the reply harder.  Must be
170    * first field after header (this is where we start to encrypt!).
171    */
172   uint32_t challenge GNUNET_PACKED;
173
174   /**
175    * Reserved, always zero.
176    */
177   uint32_t reserved;
178
179   /**
180    * Intended target of the PING, used primarily to check
181    * that decryption actually worked.
182    */
183   struct GNUNET_PeerIdentity target;
184 };
185
186
187 /**
188  * Encapsulation for encrypted messages exchanged between
189  * peers.  Followed by the actual encrypted data.
190  */
191 struct EncryptedMessage
192 {
193   /**
194    * Message type is either #GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE.
195    */
196   struct GNUNET_MessageHeader header;
197
198   /**
199    * Random value used for IV generation.
200    */
201   uint32_t iv_seed GNUNET_PACKED;
202
203   /**
204    * MAC of the encrypted message (starting at 'sequence_number'),
205    * used to verify message integrity. Everything after this value
206    * (excluding this value itself) will be encrypted and authenticated.
207    * ENCRYPTED_HEADER_SIZE must be set to the offset of the *next* field.
208    */
209   struct GNUNET_HashCode hmac;
210
211   /**
212    * Sequence number, in network byte order.  This field
213    * must be the first encrypted/decrypted field
214    */
215   uint32_t sequence_number GNUNET_PACKED;
216
217   /**
218    * Reserved, always zero.
219    */
220   uint32_t reserved;
221
222   /**
223    * Timestamp.  Used to prevent reply of ancient messages
224    * (recent messages are caught with the sequence number).
225    */
226   struct GNUNET_TIME_AbsoluteNBO timestamp;
227
228 };
229 GNUNET_NETWORK_STRUCT_END
230
231
232 /**
233  * Number of bytes (at the beginning) of "struct EncryptedMessage"
234  * that are NOT encrypted.
235  */
236 #define ENCRYPTED_HEADER_SIZE (offsetof(struct EncryptedMessage, sequence_number))
237
238
239 /**
240  * Information about the status of a key exchange with another peer.
241  */
242 struct GSC_KeyExchangeInfo
243 {
244
245   /**
246    * DLL.
247    */
248   struct GSC_KeyExchangeInfo *next;
249
250   /**
251    * DLL.
252    */
253   struct GSC_KeyExchangeInfo *prev;
254
255   /**
256    * Identity of the peer.
257    */
258   struct GNUNET_PeerIdentity peer;
259
260   /**
261    * PING message we transmit to the other peer.
262    */
263   struct PingMessage ping;
264
265   /**
266    * Ephemeral public ECC key of the other peer.
267    */
268   struct GNUNET_CRYPTO_EcdhePublicKey other_ephemeral_key;
269
270   /**
271    * Key we use to encrypt our messages for the other peer
272    * (initialized by us when we do the handshake).
273    */
274   struct GNUNET_CRYPTO_SymmetricSessionKey encrypt_key;
275
276   /**
277    * Key we use to decrypt messages from the other peer
278    * (given to us by the other peer during the handshake).
279    */
280   struct GNUNET_CRYPTO_SymmetricSessionKey decrypt_key;
281
282   /**
283    * At what time did the other peer generate the decryption key?
284    */
285   struct GNUNET_TIME_Absolute foreign_key_expires;
286
287   /**
288    * When should the session time out (if there are no PONGs)?
289    */
290   struct GNUNET_TIME_Absolute timeout;
291
292   /**
293    * At what frequency are we currently re-trying SET_KEY messages?
294    */
295   struct GNUNET_TIME_Relative set_key_retry_frequency;
296
297   /**
298    * ID of task used for re-trying SET_KEY and PING message.
299    */
300   GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
301
302   /**
303    * ID of task used for sending keep-alive pings.
304    */
305   GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
306
307   /**
308    * Bit map indicating which of the 32 sequence numbers before the last
309    * were received (good for accepting out-of-order packets and
310    * estimating reliability of the connection)
311    */
312   unsigned int last_packets_bitmap;
313
314   /**
315    * last sequence number received on this connection (highest)
316    */
317   uint32_t last_sequence_number_received;
318
319   /**
320    * last sequence number transmitted
321    */
322   uint32_t last_sequence_number_sent;
323
324   /**
325    * What was our PING challenge number (for this peer)?
326    */
327   uint32_t ping_challenge;
328
329   /**
330    * What is our connection status?
331    */
332   enum GNUNET_CORE_KxState status;
333
334 };
335
336
337 /**
338  * Our private key.
339  */
340 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
341
342 /**
343  * Our ephemeral private key.
344  */
345 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
346
347 /**
348  * Current message we send for a key exchange.
349  */
350 static struct EphemeralKeyMessage current_ekm;
351
352 /**
353  * Our message stream tokenizer (for encrypted payload).
354  */
355 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
356
357 /**
358  * DLL head.
359  */
360 static struct GSC_KeyExchangeInfo *kx_head;
361
362 /**
363  * DLL tail.
364  */
365 static struct GSC_KeyExchangeInfo *kx_tail;
366
367 /**
368  * Task scheduled for periodic re-generation (and thus rekeying) of our
369  * ephemeral key.
370  */
371 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
372
373 /**
374  * Notification context for all monitors.
375  */
376 static struct GNUNET_SERVER_NotificationContext *nc;
377
378
379 /**
380  * Inform the given monitor about the KX state of
381  * the given peer.
382  *
383  * @param mc monitor to inform
384  * @param kx key exchange state to inform about
385  */
386 static void
387 monitor_notify (struct GNUNET_SERVER_Client *client,
388                 struct GSC_KeyExchangeInfo *kx)
389 {
390   struct MonitorNotifyMessage msg;
391
392   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY);
393   msg.header.size = htons (sizeof (msg));
394   msg.state = htonl ((uint32_t) kx->status);
395   msg.peer = kx->peer;
396   msg.timeout = GNUNET_TIME_absolute_hton (kx->timeout);
397   GNUNET_SERVER_notification_context_unicast (nc,
398                                               client,
399                                               &msg.header,
400                                               GNUNET_NO);
401 }
402
403
404 /**
405  * Inform all monitors about the KX state of the given peer.
406  *
407  * @param kx key exchange state to inform about
408  */
409 static void
410 monitor_notify_all (struct GSC_KeyExchangeInfo *kx)
411 {
412   struct MonitorNotifyMessage msg;
413
414   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY);
415   msg.header.size = htons (sizeof (msg));
416   msg.state = htonl ((uint32_t) kx->status);
417   msg.peer = kx->peer;
418   msg.timeout = GNUNET_TIME_absolute_hton (kx->timeout);
419   GNUNET_SERVER_notification_context_broadcast (nc,
420                                                 &msg.header,
421                                                 GNUNET_NO);
422 }
423
424
425 /**
426  * Derive an authentication key from "set key" information
427  *
428  * @param akey authentication key to derive
429  * @param skey session key to use
430  * @param seed seed to use
431  */
432 static void
433 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
434                  const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, uint32_t seed)
435 {
436   static const char ctx[] = "authentication key";
437
438   GNUNET_CRYPTO_hmac_derive_key (akey, skey,
439                                  &seed, sizeof (seed),
440                                  skey, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
441                                  ctx, sizeof (ctx),
442                                  NULL);
443 }
444
445
446 /**
447  * Derive an IV from packet information
448  *
449  * @param iv initialization vector to initialize
450  * @param skey session key to use
451  * @param seed seed to use
452  * @param identity identity of the other peer to use
453  */
454 static void
455 derive_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
456            const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, uint32_t seed,
457            const struct GNUNET_PeerIdentity *identity)
458 {
459   static const char ctx[] = "initialization vector";
460
461   GNUNET_CRYPTO_symmetric_derive_iv (iv, skey, &seed, sizeof (seed),
462                                      identity,
463                                      sizeof (struct GNUNET_PeerIdentity), ctx,
464                                      sizeof (ctx), NULL);
465 }
466
467
468 /**
469  * Derive an IV from pong packet information
470  *
471  * @param iv initialization vector to initialize
472  * @param skey session key to use
473  * @param seed seed to use
474  * @param challenge nonce to use
475  * @param identity identity of the other peer to use
476  */
477 static void
478 derive_pong_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
479                 const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, uint32_t seed,
480                 uint32_t challenge, const struct GNUNET_PeerIdentity *identity)
481 {
482   static const char ctx[] = "pong initialization vector";
483
484   GNUNET_CRYPTO_symmetric_derive_iv (iv, skey, &seed, sizeof (seed),
485                                      identity,
486                                      sizeof (struct GNUNET_PeerIdentity),
487                                      &challenge, sizeof (challenge),
488                                      ctx, sizeof (ctx),
489                                      NULL);
490 }
491
492
493 /**
494  * Derive an AES key from key material
495  *
496  * @param sender peer identity of the sender
497  * @param receiver peer identity of the sender
498  * @param key_material high entropy key material to use
499  * @param skey set to derived session key
500  */
501 static void
502 derive_aes_key (const struct GNUNET_PeerIdentity *sender,
503                 const struct GNUNET_PeerIdentity *receiver,
504                 const struct GNUNET_HashCode *key_material,
505                 struct GNUNET_CRYPTO_SymmetricSessionKey *skey)
506 {
507   static const char ctx[] = "aes key generation vector";
508
509   GNUNET_CRYPTO_kdf (skey, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
510                      ctx, sizeof (ctx),
511                      key_material, sizeof (struct GNUNET_HashCode),
512                      sender, sizeof (struct GNUNET_PeerIdentity),
513                      receiver, sizeof (struct GNUNET_PeerIdentity),
514                      NULL);
515 }
516
517
518 /**
519  * Encrypt size bytes from @a in and write the result to @a out.  Use the
520  * @a kx key for outbound traffic of the given neighbour.
521  *
522  * @param kx key information context
523  * @param iv initialization vector to use
524  * @param in ciphertext
525  * @param out plaintext
526  * @param size size of @a in/@a out
527  * @return #GNUNET_OK on success
528  */
529 static int
530 do_encrypt (struct GSC_KeyExchangeInfo *kx,
531             const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
532             const void *in, void *out, size_t size)
533 {
534   if (size != (uint16_t) size)
535   {
536     GNUNET_break (0);
537     return GNUNET_NO;
538   }
539   GNUNET_assert (size ==
540                  GNUNET_CRYPTO_symmetric_encrypt (in, (uint16_t) size,
541                                             &kx->encrypt_key, iv, out));
542   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes encrypted"), size,
543                             GNUNET_NO);
544   /* the following is too sensitive to write to log files by accident,
545      so we require manual intervention to get this one... */
546 #if 0
547   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
548               "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
549               (unsigned int) size, GNUNET_i2s (&kx->peer),
550               (unsigned int) kx->encrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
551                                                                            sizeof
552                                                                            (iv)));
553 #endif
554   return GNUNET_OK;
555 }
556
557
558 /**
559  * Decrypt size bytes from @a in and write the result to @a out.  Use the
560  * @a kx key for inbound traffic of the given neighbour.  This function does
561  * NOT do any integrity-checks on the result.
562  *
563  * @param kx key information context
564  * @param iv initialization vector to use
565  * @param in ciphertext
566  * @param out plaintext
567  * @param size size of @a in / @a out
568  * @return #GNUNET_OK on success
569  */
570 static int
571 do_decrypt (struct GSC_KeyExchangeInfo *kx,
572             const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
573             const void *in, void *out, size_t size)
574 {
575   if (size != (uint16_t) size)
576   {
577     GNUNET_break (0);
578     return GNUNET_NO;
579   }
580   if ( (kx->status != GNUNET_CORE_KX_STATE_KEY_RECEIVED) &&
581        (kx->status != GNUNET_CORE_KX_STATE_UP) &&
582        (kx->status != GNUNET_CORE_KX_STATE_REKEY_SENT) )
583   {
584     GNUNET_break_op (0);
585     return GNUNET_SYSERR;
586   }
587   if (size !=
588       GNUNET_CRYPTO_symmetric_decrypt (in, (uint16_t) size, &kx->decrypt_key, iv,
589                                  out))
590   {
591     GNUNET_break (0);
592     return GNUNET_SYSERR;
593   }
594   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes decrypted"), size,
595                             GNUNET_NO);
596   /* the following is too sensitive to write to log files by accident,
597      so we require manual intervention to get this one... */
598 #if 0
599   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
600               "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
601               (unsigned int) size, GNUNET_i2s (&kx->peer),
602               (unsigned int) kx->decrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
603                                                                            sizeof
604                                                                            (*iv)));
605 #endif
606   return GNUNET_OK;
607 }
608
609
610 /**
611  * Send our key (and encrypted PING) to the other peer.
612  *
613  * @param kx key exchange context
614  */
615 static void
616 send_key (struct GSC_KeyExchangeInfo *kx);
617
618
619 /**
620  * Task that will retry #send_key() if our previous attempt failed.
621  *
622  * @param cls our `struct GSC_KeyExchangeInfo`
623  * @param tc scheduler context
624  */
625 static void
626 set_key_retry_task (void *cls,
627                     const struct GNUNET_SCHEDULER_TaskContext *tc)
628 {
629   struct GSC_KeyExchangeInfo *kx = cls;
630
631   kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
632   kx->set_key_retry_frequency = GNUNET_TIME_STD_BACKOFF (kx->set_key_retry_frequency);
633   GNUNET_assert (GNUNET_CORE_KX_STATE_DOWN != kx->status);
634   send_key (kx);
635 }
636
637
638 /**
639  * Create a fresh PING message for transmission to the other peer.
640  *
641  * @param kx key exchange context to create PING for
642  */
643 static void
644 setup_fresh_ping (struct GSC_KeyExchangeInfo *kx)
645 {
646   struct PingMessage pp;
647   struct PingMessage *pm;
648   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
649
650   pm = &kx->ping;
651   pm->header.size = htons (sizeof (struct PingMessage));
652   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
653   pm->iv_seed =
654       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
655   derive_iv (&iv, &kx->encrypt_key, pm->iv_seed, &kx->peer);
656   pp.challenge = kx->ping_challenge;
657   pp.target = kx->peer;
658   do_encrypt (kx, &iv, &pp.target, &pm->target,
659               sizeof (struct PingMessage) - ((void *) &pm->target -
660                                              (void *) pm));
661 }
662
663
664 /**
665  * Start the key exchange with the given peer.
666  *
667  * @param pid identity of the peer to do a key exchange with
668  * @return key exchange information context
669  */
670 struct GSC_KeyExchangeInfo *
671 GSC_KX_start (const struct GNUNET_PeerIdentity *pid)
672 {
673   struct GSC_KeyExchangeInfo *kx;
674   struct GNUNET_HashCode h1;
675   struct GNUNET_HashCode h2;
676
677   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
678               "Initiating key exchange with `%s'\n",
679               GNUNET_i2s (pid));
680   GNUNET_STATISTICS_update (GSC_stats,
681                             gettext_noop ("# key exchanges initiated"), 1,
682                             GNUNET_NO);
683   kx = GNUNET_new (struct GSC_KeyExchangeInfo);
684   kx->peer = *pid;
685   kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
686   GNUNET_CONTAINER_DLL_insert (kx_head,
687                                kx_tail,
688                                kx);
689   kx->status = GNUNET_CORE_KX_STATE_KEY_SENT;
690   monitor_notify_all (kx);
691   GNUNET_CRYPTO_hash (pid,
692                       sizeof (struct GNUNET_PeerIdentity),
693                       &h1);
694   GNUNET_CRYPTO_hash (&GSC_my_identity,
695                       sizeof (struct GNUNET_PeerIdentity),
696                       &h2);
697   if (0 < GNUNET_CRYPTO_hash_cmp (&h1,
698                                   &h2))
699   {
700     /* peer with "lower" identity starts KX, otherwise we typically end up
701        with both peers starting the exchange and transmit the 'set key'
702        message twice */
703     send_key (kx);
704   }
705   else
706   {
707     /* peer with "higher" identity starts a delayed  KX, if the "lower" peer
708      * does not start a KX since he sees no reasons to do so  */
709     kx->retry_set_key_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
710                                                            &set_key_retry_task, kx);
711   }
712   return kx;
713 }
714
715
716 /**
717  * Stop key exchange with the given peer.  Clean up key material.
718  *
719  * @param kx key exchange to stop
720  */
721 void
722 GSC_KX_stop (struct GSC_KeyExchangeInfo *kx)
723 {
724   GSC_SESSIONS_end (&kx->peer);
725   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# key exchanges stopped"),
726                             1, GNUNET_NO);
727   if (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
728   {
729     GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
730     kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
731   }
732   if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
733   {
734     GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
735     kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
736   }
737   kx->status = GNUNET_CORE_KX_PEER_DISCONNECT;
738   monitor_notify_all (kx);
739   GNUNET_CONTAINER_DLL_remove (kx_head,
740                                kx_tail,
741                                kx);
742   GNUNET_free (kx);
743 }
744
745
746 /**
747  * Send our PING to the other peer.
748  *
749  * @param kx key exchange context
750  */
751 static void
752 send_ping (struct GSC_KeyExchangeInfo *kx)
753 {
754   GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
755                            MIN_PING_FREQUENCY);
756 }
757
758
759 /**
760  * Derive fresh session keys from the current ephemeral keys.
761  *
762  * @param kx session to derive keys for
763  */
764 static void
765 derive_session_keys (struct GSC_KeyExchangeInfo *kx)
766 {
767   struct GNUNET_HashCode key_material;
768
769   if (GNUNET_OK !=
770       GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
771                               &kx->other_ephemeral_key,
772                               &key_material))
773   {
774     GNUNET_break (0);
775     return;
776   }
777   derive_aes_key (&GSC_my_identity,
778                   &kx->peer,
779                   &key_material,
780                   &kx->encrypt_key);
781   derive_aes_key (&kx->peer,
782                   &GSC_my_identity,
783                   &key_material,
784                   &kx->decrypt_key);
785   memset (&key_material, 0, sizeof (key_material));
786   /* fresh key, reset sequence numbers */
787   kx->last_sequence_number_received = 0;
788   kx->last_packets_bitmap = 0;
789   setup_fresh_ping (kx);
790 }
791
792
793 /**
794  * We received a SET_KEY message.  Validate and update
795  * our key material and status.
796  *
797  * @param kx key exchange status for the corresponding peer
798  * @param msg the set key message we received
799  */
800 void
801 GSC_KX_handle_ephemeral_key (struct GSC_KeyExchangeInfo *kx,
802                              const struct GNUNET_MessageHeader *msg)
803 {
804   const struct EphemeralKeyMessage *m;
805   struct GNUNET_TIME_Absolute start_t;
806   struct GNUNET_TIME_Absolute end_t;
807   struct GNUNET_TIME_Absolute now;
808   enum GNUNET_CORE_KxState sender_status;
809   uint16_t size;
810
811   size = ntohs (msg->size);
812   if (sizeof (struct EphemeralKeyMessage) != size)
813   {
814     GNUNET_break_op (0);
815     return;
816   }
817   m = (const struct EphemeralKeyMessage *) msg;
818   end_t = GNUNET_TIME_absolute_ntoh (m->expiration_time);
819   if ( ( (GNUNET_CORE_KX_STATE_KEY_RECEIVED == kx->status) ||
820          (GNUNET_CORE_KX_STATE_UP == kx->status) ||
821          (GNUNET_CORE_KX_STATE_REKEY_SENT == kx->status) ) &&
822        (end_t.abs_value_us <= kx->foreign_key_expires.abs_value_us) )
823   {
824     GNUNET_STATISTICS_update (GSC_stats,
825                               gettext_noop ("# old ephemeral keys ignored"),
826                               1, GNUNET_NO);
827     return;
828   }
829   start_t = GNUNET_TIME_absolute_ntoh (m->creation_time);
830
831   GNUNET_STATISTICS_update (GSC_stats,
832                             gettext_noop ("# ephemeral keys received"),
833                             1, GNUNET_NO);
834
835   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
836               "Core service receives `%s' request from `%4s'.\n", "EPHEMERAL_KEY",
837               GNUNET_i2s (&kx->peer));
838   if (0 !=
839       memcmp (&m->origin_identity,
840               &kx->peer.public_key,
841               sizeof (struct GNUNET_PeerIdentity)))
842   {
843     GNUNET_break_op (0);
844     return;
845   }
846   if ((ntohl (m->purpose.size) !=
847        sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
848        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
849        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
850        sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) +
851        sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)) ||
852       (GNUNET_OK !=
853        GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY,
854                                  &m->purpose,
855                                  &m->signature, &m->origin_identity.public_key)))
856   {
857     /* invalid signature */
858     GNUNET_break_op (0);
859     return;
860   }
861   now = GNUNET_TIME_absolute_get ();
862   if ( (end_t.abs_value_us < GNUNET_TIME_absolute_subtract (now, REKEY_TOLERANCE).abs_value_us) ||
863        (start_t.abs_value_us > GNUNET_TIME_absolute_add (now, REKEY_TOLERANCE).abs_value_us) )
864   {
865     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
866                 _("Ephemeral key message from peer `%s' rejected as its validity range does not match our system time (%llu not in [%llu,%llu]).\n"),
867                 GNUNET_i2s (&kx->peer),
868                 now.abs_value_us,
869                 start_t.abs_value_us,
870                 end_t.abs_value_us);
871     return;
872   }
873   kx->other_ephemeral_key = m->ephemeral_key;
874   kx->foreign_key_expires = end_t;
875   derive_session_keys (kx);
876   GNUNET_STATISTICS_update (GSC_stats,
877                             gettext_noop ("# EPHEMERAL_KEY messages received"), 1,
878                             GNUNET_NO);
879
880   /* check if we still need to send the sender our key */
881   sender_status = (enum GNUNET_CORE_KxState) ntohl (m->sender_status);
882   switch (sender_status)
883   {
884   case GNUNET_CORE_KX_STATE_DOWN:
885     GNUNET_break_op (0);
886     break;
887   case GNUNET_CORE_KX_STATE_KEY_SENT:
888     /* fine, need to send our key after updating our status, see below */
889     GSC_SESSIONS_reinit (&kx->peer);
890     break;
891   case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
892     /* other peer already got our key, but typemap did go down */
893     GSC_SESSIONS_reinit (&kx->peer);
894     break;
895   case GNUNET_CORE_KX_STATE_UP:
896     /* other peer already got our key, typemap NOT down */
897     break;
898   case GNUNET_CORE_KX_STATE_REKEY_SENT:
899     /* other peer already got our key, typemap NOT down */
900     break;
901   default:
902     GNUNET_break (0);
903     break;
904   }
905   /* check if we need to confirm everything is fine via PING + PONG */
906   switch (kx->status)
907   {
908   case GNUNET_CORE_KX_STATE_DOWN:
909     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
910     kx->status = GNUNET_CORE_KX_STATE_KEY_RECEIVED;
911     monitor_notify_all (kx);
912     if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
913       send_key (kx);
914     send_ping (kx);
915     break;
916   case GNUNET_CORE_KX_STATE_KEY_SENT:
917     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
918     kx->status = GNUNET_CORE_KX_STATE_KEY_RECEIVED;
919     monitor_notify_all (kx);
920     if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
921       send_key (kx);
922     send_ping (kx);
923     break;
924   case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
925     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
926     if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
927       send_key (kx);
928     send_ping (kx);
929     break;
930   case GNUNET_CORE_KX_STATE_UP:
931     kx->status = GNUNET_CORE_KX_STATE_REKEY_SENT;
932     monitor_notify_all (kx);
933     if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
934       send_key (kx);
935     /* we got a new key, need to reconfirm! */
936     send_ping (kx);
937     break;
938   case GNUNET_CORE_KX_STATE_REKEY_SENT:
939     if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
940       send_key (kx);
941     /* we got a new key, need to reconfirm! */
942     send_ping (kx);
943     break;
944   default:
945     GNUNET_break (0);
946     break;
947   }
948 }
949
950
951 /**
952  * We received a PING message.  Validate and transmit
953  * a PONG message.
954  *
955  * @param kx key exchange status for the corresponding peer
956  * @param msg the encrypted PING message itself
957  */
958 void
959 GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *kx,
960                     const struct GNUNET_MessageHeader *msg)
961 {
962   const struct PingMessage *m;
963   struct PingMessage t;
964   struct PongMessage tx;
965   struct PongMessage tp;
966   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
967   uint16_t msize;
968
969   msize = ntohs (msg->size);
970   if (msize != sizeof (struct PingMessage))
971   {
972     GNUNET_break_op (0);
973     return;
974   }
975   GNUNET_STATISTICS_update (GSC_stats,
976                             gettext_noop ("# PING messages received"), 1,
977                             GNUNET_NO);
978   if ( (kx->status != GNUNET_CORE_KX_STATE_KEY_RECEIVED) &&
979        (kx->status != GNUNET_CORE_KX_STATE_UP) &&
980        (kx->status != GNUNET_CORE_KX_STATE_REKEY_SENT))
981   {
982     /* ignore */
983     GNUNET_STATISTICS_update (GSC_stats,
984                               gettext_noop ("# PING messages dropped (out of order)"), 1,
985                               GNUNET_NO);
986     return;
987   }
988   m = (const struct PingMessage *) msg;
989   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
990               "Core service receives `%s' request from `%4s'.\n", "PING",
991               GNUNET_i2s (&kx->peer));
992   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
993   if (GNUNET_OK !=
994       do_decrypt (kx, &iv, &m->target, &t.target,
995                   sizeof (struct PingMessage) - ((void *) &m->target -
996                                                  (void *) m)))
997   {
998     GNUNET_break_op (0);
999     return;
1000   }
1001   if (0 !=
1002       memcmp (&t.target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
1003   {
1004     char sender[9];
1005     char peer[9];
1006
1007     GNUNET_snprintf (sender, sizeof (sender), "%8s", GNUNET_i2s (&kx->peer));
1008     GNUNET_snprintf (peer, sizeof (peer), "%8s", GNUNET_i2s (&t.target));
1009     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1010                 _
1011                 ("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
1012                 sender, GNUNET_i2s (&GSC_my_identity), peer);
1013     GNUNET_break_op (0);
1014     return;
1015   }
1016   /* construct PONG */
1017   tx.reserved = 0;
1018   tx.challenge = t.challenge;
1019   tx.target = t.target;
1020   tp.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
1021   tp.header.size = htons (sizeof (struct PongMessage));
1022   tp.iv_seed =
1023       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1024   derive_pong_iv (&iv, &kx->encrypt_key, tp.iv_seed, t.challenge, &kx->peer);
1025   do_encrypt (kx, &iv, &tx.challenge, &tp.challenge,
1026               sizeof (struct PongMessage) - ((void *) &tp.challenge -
1027                                              (void *) &tp));
1028   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages created"),
1029                             1, GNUNET_NO);
1030   GSC_NEIGHBOURS_transmit (&kx->peer, &tp.header,
1031                            GNUNET_TIME_UNIT_FOREVER_REL /* FIXME: timeout */ );
1032 }
1033
1034
1035 /**
1036  * Task triggered when a neighbour entry is about to time out
1037  * (and we should prevent this by sending a PING).
1038  *
1039  * @param cls the 'struct GSC_KeyExchangeInfo'
1040  * @param tc scheduler context (not used)
1041  */
1042 static void
1043 send_keep_alive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1044 {
1045   struct GSC_KeyExchangeInfo *kx = cls;
1046   struct GNUNET_TIME_Relative retry;
1047   struct GNUNET_TIME_Relative left;
1048
1049   kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1050   left = GNUNET_TIME_absolute_get_remaining (kx->timeout);
1051   if (0 == left.rel_value_us)
1052   {
1053     GNUNET_STATISTICS_update (GSC_stats,
1054                               gettext_noop ("# sessions terminated by timeout"),
1055                               1, GNUNET_NO);
1056     GSC_SESSIONS_end (&kx->peer);
1057     kx->status = GNUNET_CORE_KX_STATE_KEY_SENT;
1058     monitor_notify_all (kx);
1059     send_key (kx);
1060     return;
1061   }
1062   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending KEEPALIVE to `%s'\n",
1063               GNUNET_i2s (&kx->peer));
1064   GNUNET_STATISTICS_update (GSC_stats,
1065                             gettext_noop ("# keepalive messages sent"), 1,
1066                             GNUNET_NO);
1067   setup_fresh_ping (kx);
1068   GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
1069                            kx->set_key_retry_frequency);
1070   retry =
1071       GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1072                                 MIN_PING_FREQUENCY);
1073   kx->keep_alive_task =
1074       GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx);
1075 }
1076
1077
1078 /**
1079  * We've seen a valid message from the other peer.
1080  * Update the time when the session would time out
1081  * and delay sending our keep alive message further.
1082  *
1083  * @param kx key exchange where we saw activity
1084  */
1085 static void
1086 update_timeout (struct GSC_KeyExchangeInfo *kx)
1087 {
1088   kx->timeout =
1089       GNUNET_TIME_relative_to_absolute
1090       (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1091   monitor_notify_all (kx);
1092   if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1093     GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1094   kx->keep_alive_task =
1095       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
1096                                     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1097                                      2), &send_keep_alive, kx);
1098 }
1099
1100
1101 /**
1102  * We received a PONG message.  Validate and update our status.
1103  *
1104  * @param kx key exchange context for the the PONG
1105  * @param msg the encrypted PONG message itself
1106  */
1107 void
1108 GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx,
1109                     const struct GNUNET_MessageHeader *msg)
1110 {
1111   const struct PongMessage *m;
1112   struct PongMessage t;
1113   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1114   uint16_t msize;
1115
1116   msize = ntohs (msg->size);
1117   if (sizeof (struct PongMessage) != msize)
1118   {
1119     GNUNET_break_op (0);
1120     return;
1121   }
1122   GNUNET_STATISTICS_update (GSC_stats,
1123                             gettext_noop ("# PONG messages received"), 1,
1124                             GNUNET_NO);
1125   switch (kx->status)
1126   {
1127   case GNUNET_CORE_KX_STATE_DOWN:
1128     GNUNET_STATISTICS_update (GSC_stats,
1129                               gettext_noop ("# PONG messages dropped (connection down)"), 1,
1130                               GNUNET_NO);
1131     return;
1132   case GNUNET_CORE_KX_STATE_KEY_SENT:
1133     GNUNET_STATISTICS_update (GSC_stats,
1134                               gettext_noop ("# PONG messages dropped (out of order)"), 1,
1135                               GNUNET_NO);
1136     return;
1137   case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
1138     break;
1139   case GNUNET_CORE_KX_STATE_UP:
1140     break;
1141   case GNUNET_CORE_KX_STATE_REKEY_SENT:
1142     break;
1143   default:
1144     GNUNET_break (0);
1145     return;
1146   }
1147   m = (const struct PongMessage *) msg;
1148   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1149               "Core service receives `%s' response from `%4s'.\n", "PONG",
1150               GNUNET_i2s (&kx->peer));
1151   /* mark as garbage, just to be sure */
1152   memset (&t, 255, sizeof (t));
1153   derive_pong_iv (&iv, &kx->decrypt_key, m->iv_seed, kx->ping_challenge,
1154                   &GSC_my_identity);
1155   if (GNUNET_OK !=
1156       do_decrypt (kx, &iv, &m->challenge, &t.challenge,
1157                   sizeof (struct PongMessage) - ((void *) &m->challenge -
1158                                                  (void *) m)))
1159   {
1160     GNUNET_break_op (0);
1161     return;
1162   }
1163   GNUNET_STATISTICS_update (GSC_stats,
1164                             gettext_noop ("# PONG messages decrypted"), 1,
1165                             GNUNET_NO);
1166   if ((0 != memcmp (&t.target, &kx->peer, sizeof (struct GNUNET_PeerIdentity)))
1167       || (kx->ping_challenge != t.challenge))
1168   {
1169     /* PONG malformed */
1170     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1171                 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
1172                 "PONG", GNUNET_i2s (&kx->peer),
1173                 (unsigned int) kx->ping_challenge);
1174     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1175                 "Received malformed `%s' received from `%4s' with challenge %u\n",
1176                 "PONG", GNUNET_i2s (&t.target), (unsigned int) t.challenge);
1177     return;
1178   }
1179   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PONG from `%s'\n",
1180               GNUNET_i2s (&kx->peer));
1181   /* no need to resend key any longer */
1182   if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
1183   {
1184     GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1185     kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1186   }
1187   switch (kx->status)
1188   {
1189   case GNUNET_CORE_KX_STATE_DOWN:
1190     GNUNET_assert (0);           /* should be impossible */
1191     return;
1192   case GNUNET_CORE_KX_STATE_KEY_SENT:
1193     GNUNET_assert (0);           /* should be impossible */
1194     return;
1195   case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
1196     GNUNET_STATISTICS_update (GSC_stats,
1197                               gettext_noop
1198                               ("# session keys confirmed via PONG"), 1,
1199                               GNUNET_NO);
1200     kx->status = GNUNET_CORE_KX_STATE_UP;
1201     monitor_notify_all (kx);
1202     GSC_SESSIONS_create (&kx->peer, kx);
1203     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
1204     update_timeout (kx);
1205     break;
1206   case GNUNET_CORE_KX_STATE_UP:
1207     GNUNET_STATISTICS_update (GSC_stats,
1208                               gettext_noop
1209                               ("# timeouts prevented via PONG"), 1,
1210                               GNUNET_NO);
1211     update_timeout (kx);
1212     break;
1213   case GNUNET_CORE_KX_STATE_REKEY_SENT:
1214     GNUNET_STATISTICS_update (GSC_stats,
1215                               gettext_noop
1216                               ("# rekey operations confirmed via PONG"), 1,
1217                               GNUNET_NO);
1218     kx->status = GNUNET_CORE_KX_STATE_UP;
1219     monitor_notify_all (kx);
1220     update_timeout (kx);
1221     break;
1222   default:
1223     GNUNET_break (0);
1224     break;
1225   }
1226 }
1227
1228
1229 /**
1230  * Send our key to the other peer.
1231  *
1232  * @param kx key exchange context
1233  */
1234 static void
1235 send_key (struct GSC_KeyExchangeInfo *kx)
1236 {
1237   GNUNET_assert (GNUNET_CORE_KX_STATE_DOWN != kx->status);
1238   if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
1239   {
1240      GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1241      kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1242   }
1243   /* always update sender status in SET KEY message */
1244   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1245               "Sending key to `%s' (my status: %d)\n",
1246               GNUNET_i2s (&kx->peer),
1247               kx->status);
1248   current_ekm.sender_status = htonl ((int32_t) (kx->status));
1249   GSC_NEIGHBOURS_transmit (&kx->peer, &current_ekm.header,
1250                            kx->set_key_retry_frequency);
1251   kx->retry_set_key_task =
1252       GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
1253                                     &set_key_retry_task, kx);
1254 }
1255
1256
1257 /**
1258  * Encrypt and transmit a message with the given payload.
1259  *
1260  * @param kx key exchange context
1261  * @param payload payload of the message
1262  * @param payload_size number of bytes in 'payload'
1263  */
1264 void
1265 GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
1266                              const void *payload, size_t payload_size)
1267 {
1268   size_t used = payload_size + sizeof (struct EncryptedMessage);
1269   char pbuf[used];              /* plaintext */
1270   char cbuf[used];              /* ciphertext */
1271   struct EncryptedMessage *em;  /* encrypted message */
1272   struct EncryptedMessage *ph;  /* plaintext header */
1273   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1274   struct GNUNET_CRYPTO_AuthKey auth_key;
1275
1276   ph = (struct EncryptedMessage *) pbuf;
1277   ph->iv_seed =
1278       htonl (GNUNET_CRYPTO_random_u32
1279              (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
1280   ph->sequence_number = htonl (++kx->last_sequence_number_sent);
1281   ph->reserved = 0;
1282   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1283   memcpy (&ph[1], payload, payload_size);
1284
1285   em = (struct EncryptedMessage *) cbuf;
1286   em->header.size = htons (used);
1287   em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1288   em->iv_seed = ph->iv_seed;
1289   derive_iv (&iv, &kx->encrypt_key, ph->iv_seed, &kx->peer);
1290   GNUNET_assert (GNUNET_OK ==
1291                  do_encrypt (kx, &iv, &ph->sequence_number,
1292                              &em->sequence_number,
1293                              used - ENCRYPTED_HEADER_SIZE));
1294   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Encrypted %u bytes for %s\n",
1295               used - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1296   derive_auth_key (&auth_key,
1297                    &kx->encrypt_key,
1298                    ph->iv_seed);
1299   GNUNET_CRYPTO_hmac (&auth_key, &em->sequence_number,
1300                       used - ENCRYPTED_HEADER_SIZE, &em->hmac);
1301   GSC_NEIGHBOURS_transmit (&kx->peer, &em->header,
1302                            GNUNET_TIME_UNIT_FOREVER_REL);
1303 }
1304
1305
1306 /**
1307  * Closure for #deliver_message()
1308  */
1309 struct DeliverMessageContext
1310 {
1311
1312   /**
1313    * Key exchange context.
1314    */
1315   struct GSC_KeyExchangeInfo *kx;
1316
1317   /**
1318    * Sender of the message.
1319    */
1320   const struct GNUNET_PeerIdentity *peer;
1321 };
1322
1323
1324 /**
1325  * We received an encrypted message.  Decrypt, validate and
1326  * pass on to the appropriate clients.
1327  *
1328  * @param kx key exchange context for encrypting the message
1329  * @param msg encrypted message
1330  */
1331 void
1332 GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *kx,
1333                                  const struct GNUNET_MessageHeader *msg)
1334 {
1335   const struct EncryptedMessage *m;
1336   struct EncryptedMessage *pt;  /* plaintext */
1337   struct GNUNET_HashCode ph;
1338   uint32_t snum;
1339   struct GNUNET_TIME_Absolute t;
1340   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1341   struct GNUNET_CRYPTO_AuthKey auth_key;
1342   struct DeliverMessageContext dmc;
1343   uint16_t size = ntohs (msg->size);
1344   char buf[size] GNUNET_ALIGN;
1345
1346   if (size <
1347       sizeof (struct EncryptedMessage) + sizeof (struct GNUNET_MessageHeader))
1348   {
1349     GNUNET_break_op (0);
1350     return;
1351   }
1352   m = (const struct EncryptedMessage *) msg;
1353   if (GNUNET_CORE_KX_STATE_UP != kx->status)
1354   {
1355     GNUNET_STATISTICS_update (GSC_stats,
1356                               gettext_noop
1357                               ("# DATA message dropped (out of order)"),
1358                               1, GNUNET_NO);
1359     return;
1360   }
1361   if (0 == GNUNET_TIME_absolute_get_remaining (kx->foreign_key_expires).rel_value_us)
1362   {
1363     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1364                 _("Session to peer `%s' went down due to key expiration (should not happen)\n"),
1365                 GNUNET_i2s (&kx->peer));
1366     GNUNET_STATISTICS_update (GSC_stats,
1367                               gettext_noop ("# sessions terminated by key expiration"),
1368                               1, GNUNET_NO);
1369     GSC_SESSIONS_end (&kx->peer);
1370     if (GNUNET_SCHEDULER_NO_TASK != kx->keep_alive_task)
1371     {
1372       GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1373       kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1374     }
1375     kx->status = GNUNET_CORE_KX_STATE_KEY_SENT;
1376     monitor_notify_all (kx);
1377     send_key (kx);
1378     return;
1379   }
1380
1381   /* validate hash */
1382   derive_auth_key (&auth_key, &kx->decrypt_key, m->iv_seed);
1383   GNUNET_CRYPTO_hmac (&auth_key, &m->sequence_number,
1384                       size - ENCRYPTED_HEADER_SIZE, &ph);
1385   if (0 != memcmp (&ph, &m->hmac, sizeof (struct GNUNET_HashCode)))
1386   {
1387     /* checksum failed */
1388     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1389                 "Failed checksum validation for a message from `%s'\n",
1390                 GNUNET_i2s (&kx->peer));
1391     return;
1392   }
1393   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
1394   /* decrypt */
1395   if (GNUNET_OK !=
1396       do_decrypt (kx, &iv, &m->sequence_number, &buf[ENCRYPTED_HEADER_SIZE],
1397                   size - ENCRYPTED_HEADER_SIZE))
1398     return;
1399   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1400               "Decrypted %u bytes from %s\n",
1401               size - ENCRYPTED_HEADER_SIZE,
1402               GNUNET_i2s (&kx->peer));
1403   pt = (struct EncryptedMessage *) buf;
1404
1405   /* validate sequence number */
1406   snum = ntohl (pt->sequence_number);
1407   if (kx->last_sequence_number_received == snum)
1408   {
1409     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1410                 "Received duplicate message, ignoring.\n");
1411     /* duplicate, ignore */
1412     GNUNET_STATISTICS_update (GSC_stats,
1413                               gettext_noop ("# bytes dropped (duplicates)"),
1414                               size, GNUNET_NO);
1415     return;
1416   }
1417   if ((kx->last_sequence_number_received > snum) &&
1418       (kx->last_sequence_number_received - snum > 32))
1419   {
1420     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1421                 "Received ancient out of sequence message, ignoring.\n");
1422     /* ancient out of sequence, ignore */
1423     GNUNET_STATISTICS_update (GSC_stats,
1424                               gettext_noop
1425                               ("# bytes dropped (out of sequence)"), size,
1426                               GNUNET_NO);
1427     return;
1428   }
1429   if (kx->last_sequence_number_received > snum)
1430   {
1431     unsigned int rotbit = 1 << (kx->last_sequence_number_received - snum - 1);
1432
1433     if ((kx->last_packets_bitmap & rotbit) != 0)
1434     {
1435       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1436                   "Received duplicate message, ignoring.\n");
1437       GNUNET_STATISTICS_update (GSC_stats,
1438                                 gettext_noop ("# bytes dropped (duplicates)"),
1439                                 size, GNUNET_NO);
1440       /* duplicate, ignore */
1441       return;
1442     }
1443     kx->last_packets_bitmap |= rotbit;
1444   }
1445   if (kx->last_sequence_number_received < snum)
1446   {
1447     unsigned int shift = (snum - kx->last_sequence_number_received);
1448
1449     if (shift >= 8 * sizeof (kx->last_packets_bitmap))
1450       kx->last_packets_bitmap = 0;
1451     else
1452       kx->last_packets_bitmap <<= shift;
1453     kx->last_sequence_number_received = snum;
1454   }
1455
1456   /* check timestamp */
1457   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
1458   if (GNUNET_TIME_absolute_get_duration (t).rel_value_us >
1459       MAX_MESSAGE_AGE.rel_value_us)
1460   {
1461     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1462                 "Message received far too old (%s). Content ignored.\n",
1463                 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (t),
1464                                                         GNUNET_YES));
1465     GNUNET_STATISTICS_update (GSC_stats,
1466                               gettext_noop
1467                               ("# bytes dropped (ancient message)"), size,
1468                               GNUNET_NO);
1469     return;
1470   }
1471
1472   /* process decrypted message(s) */
1473   update_timeout (kx);
1474   GNUNET_STATISTICS_update (GSC_stats,
1475                             gettext_noop ("# bytes of payload decrypted"),
1476                             size - sizeof (struct EncryptedMessage),
1477                             GNUNET_NO);
1478   dmc.kx = kx;
1479   dmc.peer = &kx->peer;
1480   if (GNUNET_OK !=
1481       GNUNET_SERVER_mst_receive (mst, &dmc,
1482                                  &buf[sizeof (struct EncryptedMessage)],
1483                                  size - sizeof (struct EncryptedMessage),
1484                                  GNUNET_YES,
1485                                  GNUNET_NO))
1486     GNUNET_break_op (0);
1487 }
1488
1489
1490 /**
1491  * Deliver P2P message to interested clients.
1492  * Invokes send twice, once for clients that want the full message, and once
1493  * for clients that only want the header
1494  *
1495  * @param cls always NULL
1496  * @param client who sent us the message (struct GSC_KeyExchangeInfo)
1497  * @param m the message
1498  */
1499 static int
1500 deliver_message (void *cls,
1501                  void *client,
1502                  const struct GNUNET_MessageHeader *m)
1503 {
1504   struct DeliverMessageContext *dmc = client;
1505
1506   if (GNUNET_CORE_KX_STATE_UP != dmc->kx->status)
1507   {
1508     GNUNET_STATISTICS_update (GSC_stats,
1509                               gettext_noop
1510                               ("# PAYLOAD dropped (out of order)"),
1511                               1, GNUNET_NO);
1512     return GNUNET_OK;
1513   }
1514   switch (ntohs (m->type))
1515   {
1516   case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP:
1517   case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP:
1518     GSC_SESSIONS_set_typemap (dmc->peer, m);
1519     return GNUNET_OK;
1520   case GNUNET_MESSAGE_TYPE_CORE_CONFIRM_TYPE_MAP:
1521     GSC_SESSIONS_confirm_typemap (dmc->peer, m);
1522     return GNUNET_OK;
1523   default:
1524     GSC_CLIENTS_deliver_message (dmc->peer, m,
1525                                  ntohs (m->size),
1526                                  GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
1527     GSC_CLIENTS_deliver_message (dmc->peer, m,
1528                                  sizeof (struct GNUNET_MessageHeader),
1529                                  GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
1530   }
1531   return GNUNET_OK;
1532 }
1533
1534
1535 /**
1536  * Setup the message that links the ephemeral key to our persistent
1537  * public key and generate the appropriate signature.
1538  */
1539 static void
1540 sign_ephemeral_key ()
1541 {
1542   current_ekm.header.size = htons (sizeof (struct EphemeralKeyMessage));
1543   current_ekm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY);
1544   current_ekm.sender_status = 0; /* to be set later */
1545   current_ekm.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY);
1546   current_ekm.purpose.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
1547                                     sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1548                                     sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1549                                     sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
1550                                     sizeof (struct GNUNET_PeerIdentity));
1551   current_ekm.creation_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1552   if (GNUNET_YES ==
1553       GNUNET_CONFIGURATION_get_value_yesno (GSC_cfg,
1554                                             "core",
1555                                             "USE_EPHEMERAL_KEYS"))
1556   {
1557     current_ekm.expiration_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_add (REKEY_FREQUENCY,
1558                                                                                                                          REKEY_TOLERANCE)));
1559   }
1560   else
1561   {
1562     current_ekm.expiration_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_FOREVER_ABS);
1563   }
1564   GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key,
1565                                       &current_ekm.ephemeral_key);
1566   current_ekm.origin_identity = GSC_my_identity;
1567   GNUNET_assert (GNUNET_OK ==
1568                  GNUNET_CRYPTO_eddsa_sign (my_private_key,
1569                                          &current_ekm.purpose,
1570                                          &current_ekm.signature));
1571 }
1572
1573
1574 /**
1575  * Task run to trigger rekeying.
1576  *
1577  * @param cls closure, NULL
1578  * @param tc scheduler context
1579  */
1580 static void
1581 do_rekey (void *cls,
1582           const struct GNUNET_SCHEDULER_TaskContext *tc)
1583 {
1584   struct GSC_KeyExchangeInfo *pos;
1585
1586   rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY,
1587                                              &do_rekey,
1588                                              NULL);
1589   if (NULL != my_ephemeral_key)
1590     GNUNET_free (my_ephemeral_key);
1591   my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1592   GNUNET_assert (NULL != my_ephemeral_key);
1593   sign_ephemeral_key ();
1594   for (pos = kx_head; NULL != pos; pos = pos->next)
1595   {
1596     if (GNUNET_CORE_KX_STATE_UP == pos->status)
1597     {
1598       pos->status = GNUNET_CORE_KX_STATE_REKEY_SENT;
1599       monitor_notify_all (pos);
1600       derive_session_keys (pos);
1601     }
1602     if (GNUNET_CORE_KX_STATE_DOWN == pos->status)
1603     {
1604       pos->status = GNUNET_CORE_KX_STATE_KEY_SENT;
1605       monitor_notify_all (pos);
1606     }
1607     monitor_notify_all (pos);
1608     send_key (pos);
1609   }
1610 }
1611
1612
1613 /**
1614  * Initialize KX subsystem.
1615  *
1616  * @param pk private key to use for the peer
1617  * @param server the server of the CORE service
1618  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1619  */
1620 int
1621 GSC_KX_init (struct GNUNET_CRYPTO_EddsaPrivateKey *pk,
1622              struct GNUNET_SERVER_Handle *server)
1623 {
1624   nc = GNUNET_SERVER_notification_context_create (server,
1625                                                   1);
1626   my_private_key = pk;
1627   GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
1628                                                   &GSC_my_identity.public_key);
1629   my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1630   if (NULL == my_ephemeral_key)
1631   {
1632     GNUNET_break (0);
1633     GNUNET_free (my_private_key);
1634     my_private_key = NULL;
1635     return GNUNET_SYSERR;
1636   }
1637   sign_ephemeral_key ();
1638   rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY,
1639                                              &do_rekey,
1640                                              NULL);
1641   mst = GNUNET_SERVER_mst_create (&deliver_message, NULL);
1642   return GNUNET_OK;
1643 }
1644
1645
1646 /**
1647  * Shutdown KX subsystem.
1648  */
1649 void
1650 GSC_KX_done ()
1651 {
1652   if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1653   {
1654     GNUNET_SCHEDULER_cancel (rekey_task);
1655     rekey_task = GNUNET_SCHEDULER_NO_TASK;
1656   }
1657   if (NULL != my_ephemeral_key)
1658   {
1659     GNUNET_free (my_ephemeral_key);
1660     my_ephemeral_key = NULL;
1661   }
1662   if (NULL != my_private_key)
1663   {
1664     GNUNET_free (my_private_key);
1665     my_private_key = NULL;
1666   }
1667   if (NULL != mst)
1668   {
1669     GNUNET_SERVER_mst_destroy (mst);
1670     mst = NULL;
1671   }
1672   if (NULL != nc)
1673   {
1674     GNUNET_SERVER_notification_context_destroy (nc);
1675     nc = NULL;
1676   }
1677 }
1678
1679
1680 /**
1681  * Handle #GNUNET_MESSAGE_TYPE_CORE_MONITOR_PEERS request.  For this
1682  * request type, the client does not have to have transmitted an INIT
1683  * request.  All current peers are returned, regardless of which
1684  * message types they accept.
1685  *
1686  * @param cls unused
1687  * @param client client sending the iteration request
1688  * @param message iteration request message
1689  */
1690 void
1691 GSC_KX_handle_client_monitor_peers (void *cls,
1692                                     struct GNUNET_SERVER_Client *client,
1693                                     const struct GNUNET_MessageHeader *message)
1694 {
1695   struct MonitorNotifyMessage done_msg;
1696   struct GSC_KeyExchangeInfo *kx;
1697
1698   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1699   GNUNET_SERVER_notification_context_add (nc,
1700                                           client);
1701   for (kx = kx_head; NULL != kx; kx = kx->next)
1702     monitor_notify (client, kx);
1703   done_msg.header.size = htons (sizeof (struct MonitorNotifyMessage));
1704   done_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY);
1705   done_msg.state = htonl ((uint32_t) GNUNET_CORE_KX_ITERATION_FINISHED);
1706   memset (&done_msg.peer, 0, sizeof (struct GNUNET_PeerIdentity));
1707   done_msg.timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_FOREVER_ABS);
1708   GNUNET_SERVER_notification_context_unicast (nc,
1709                                               client,
1710                                               &done_msg.header,
1711                                               GNUNET_NO);
1712 }
1713
1714
1715 /* end of gnunet-service-core_kx.c */