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