towards fixing #3363: replacing old iteration API with new monitoring API for core...
[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, gettext_noop ("# old ephemeral keys ignored"),
825                               1, GNUNET_NO);
826     return;
827   }
828   start_t = GNUNET_TIME_absolute_ntoh (m->creation_time);
829
830   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# ephemeral keys received"),
831                             1, GNUNET_NO);
832
833   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
834               "Core service receives `%s' request from `%4s'.\n", "EPHEMERAL_KEY",
835               GNUNET_i2s (&kx->peer));
836   if (0 !=
837       memcmp (&m->origin_identity,
838               &kx->peer.public_key,
839               sizeof (struct GNUNET_PeerIdentity)))
840   {
841     GNUNET_break_op (0);
842     return;
843   }
844   if ((ntohl (m->purpose.size) !=
845        sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
846        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
847        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
848        sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) +
849        sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)) ||
850       (GNUNET_OK !=
851        GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY,
852                                  &m->purpose,
853                                  &m->signature, &m->origin_identity.public_key)))
854   {
855     /* invalid signature */
856     GNUNET_break_op (0);
857     return;
858   }
859   now = GNUNET_TIME_absolute_get ();
860   if ( (end_t.abs_value_us < GNUNET_TIME_absolute_subtract (now, REKEY_TOLERANCE).abs_value_us) ||
861        (start_t.abs_value_us > GNUNET_TIME_absolute_add (now, REKEY_TOLERANCE).abs_value_us) )
862   {
863     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
864                 _("Ephemeral key message from peer `%s' rejected as its validity range does not match our system time (%llu not in [%llu,%llu]).\n"),
865                 GNUNET_i2s (&kx->peer),
866                 now.abs_value_us,
867                 start_t.abs_value_us,
868                 end_t.abs_value_us);
869     return;
870   }
871   kx->other_ephemeral_key = m->ephemeral_key;
872   kx->foreign_key_expires = end_t;
873   derive_session_keys (kx);
874   GNUNET_STATISTICS_update (GSC_stats,
875                             gettext_noop ("# EPHEMERAL_KEY messages received"), 1,
876                             GNUNET_NO);
877
878   /* check if we still need to send the sender our key */
879   sender_status = (enum GNUNET_CORE_KxState) ntohl (m->sender_status);
880   switch (sender_status)
881   {
882   case GNUNET_CORE_KX_STATE_DOWN:
883     GNUNET_break_op (0);
884     break;
885   case GNUNET_CORE_KX_STATE_KEY_SENT:
886     /* fine, need to send our key after updating our status, see below */
887     break;
888   case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
889   case GNUNET_CORE_KX_STATE_UP:
890   case GNUNET_CORE_KX_STATE_REKEY_SENT:
891     /* other peer already got our key */
892     break;
893   default:
894     GNUNET_break (0);
895     break;
896   }
897   /* check if we need to confirm everything is fine via PING + PONG */
898   switch (kx->status)
899   {
900   case GNUNET_CORE_KX_STATE_DOWN:
901     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
902     kx->status = GNUNET_CORE_KX_STATE_KEY_RECEIVED;
903     monitor_notify_all (kx);
904     if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
905       send_key (kx);
906     send_ping (kx);
907     break;
908   case GNUNET_CORE_KX_STATE_KEY_SENT:
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_RECEIVED:
917     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
918     if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
919       send_key (kx);
920     send_ping (kx);
921     break;
922   case GNUNET_CORE_KX_STATE_UP:
923     kx->status = GNUNET_CORE_KX_STATE_REKEY_SENT;
924     monitor_notify_all (kx);
925     if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
926       send_key (kx);
927     /* we got a new key, need to reconfirm! */
928     send_ping (kx);
929     break;
930   case GNUNET_CORE_KX_STATE_REKEY_SENT:
931     if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
932       send_key (kx);
933     /* we got a new key, need to reconfirm! */
934     send_ping (kx);
935     break;
936   default:
937     GNUNET_break (0);
938     break;
939   }
940 }
941
942
943 /**
944  * We received a PING message.  Validate and transmit
945  * a PONG message.
946  *
947  * @param kx key exchange status for the corresponding peer
948  * @param msg the encrypted PING message itself
949  */
950 void
951 GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *kx,
952                     const struct GNUNET_MessageHeader *msg)
953 {
954   const struct PingMessage *m;
955   struct PingMessage t;
956   struct PongMessage tx;
957   struct PongMessage tp;
958   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
959   uint16_t msize;
960
961   msize = ntohs (msg->size);
962   if (msize != sizeof (struct PingMessage))
963   {
964     GNUNET_break_op (0);
965     return;
966   }
967   GNUNET_STATISTICS_update (GSC_stats,
968                             gettext_noop ("# PING messages received"), 1,
969                             GNUNET_NO);
970   if ( (kx->status != GNUNET_CORE_KX_STATE_KEY_RECEIVED) &&
971        (kx->status != GNUNET_CORE_KX_STATE_UP) &&
972        (kx->status != GNUNET_CORE_KX_STATE_REKEY_SENT))
973   {
974     /* ignore */
975     GNUNET_STATISTICS_update (GSC_stats,
976                               gettext_noop ("# PING messages dropped (out of order)"), 1,
977                               GNUNET_NO);
978     return;
979   }
980   m = (const struct PingMessage *) msg;
981   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
982               "Core service receives `%s' request from `%4s'.\n", "PING",
983               GNUNET_i2s (&kx->peer));
984   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
985   if (GNUNET_OK !=
986       do_decrypt (kx, &iv, &m->target, &t.target,
987                   sizeof (struct PingMessage) - ((void *) &m->target -
988                                                  (void *) m)))
989   {
990     GNUNET_break_op (0);
991     return;
992   }
993   if (0 !=
994       memcmp (&t.target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
995   {
996     char sender[9];
997     char peer[9];
998
999     GNUNET_snprintf (sender, sizeof (sender), "%8s", GNUNET_i2s (&kx->peer));
1000     GNUNET_snprintf (peer, sizeof (peer), "%8s", GNUNET_i2s (&t.target));
1001     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1002                 _
1003                 ("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
1004                 sender, GNUNET_i2s (&GSC_my_identity), peer);
1005     GNUNET_break_op (0);
1006     return;
1007   }
1008   /* construct PONG */
1009   tx.reserved = 0;
1010   tx.challenge = t.challenge;
1011   tx.target = t.target;
1012   tp.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
1013   tp.header.size = htons (sizeof (struct PongMessage));
1014   tp.iv_seed =
1015       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1016   derive_pong_iv (&iv, &kx->encrypt_key, tp.iv_seed, t.challenge, &kx->peer);
1017   do_encrypt (kx, &iv, &tx.challenge, &tp.challenge,
1018               sizeof (struct PongMessage) - ((void *) &tp.challenge -
1019                                              (void *) &tp));
1020   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages created"),
1021                             1, GNUNET_NO);
1022   GSC_NEIGHBOURS_transmit (&kx->peer, &tp.header,
1023                            GNUNET_TIME_UNIT_FOREVER_REL /* FIXME: timeout */ );
1024 }
1025
1026
1027 /**
1028  * Task triggered when a neighbour entry is about to time out
1029  * (and we should prevent this by sending a PING).
1030  *
1031  * @param cls the 'struct GSC_KeyExchangeInfo'
1032  * @param tc scheduler context (not used)
1033  */
1034 static void
1035 send_keep_alive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1036 {
1037   struct GSC_KeyExchangeInfo *kx = cls;
1038   struct GNUNET_TIME_Relative retry;
1039   struct GNUNET_TIME_Relative left;
1040
1041   kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1042   left = GNUNET_TIME_absolute_get_remaining (kx->timeout);
1043   if (0 == left.rel_value_us)
1044   {
1045     GNUNET_STATISTICS_update (GSC_stats,
1046                               gettext_noop ("# sessions terminated by timeout"),
1047                               1, GNUNET_NO);
1048     GSC_SESSIONS_end (&kx->peer);
1049     kx->status = GNUNET_CORE_KX_STATE_KEY_SENT;
1050     monitor_notify_all (kx);
1051     send_key (kx);
1052     return;
1053   }
1054   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending KEEPALIVE to `%s'\n",
1055               GNUNET_i2s (&kx->peer));
1056   GNUNET_STATISTICS_update (GSC_stats,
1057                             gettext_noop ("# keepalive messages sent"), 1,
1058                             GNUNET_NO);
1059   setup_fresh_ping (kx);
1060   GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
1061                            kx->set_key_retry_frequency);
1062   retry =
1063       GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1064                                 MIN_PING_FREQUENCY);
1065   kx->keep_alive_task =
1066       GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx);
1067 }
1068
1069
1070 /**
1071  * We've seen a valid message from the other peer.
1072  * Update the time when the session would time out
1073  * and delay sending our keep alive message further.
1074  *
1075  * @param kx key exchange where we saw activity
1076  */
1077 static void
1078 update_timeout (struct GSC_KeyExchangeInfo *kx)
1079 {
1080   kx->timeout =
1081       GNUNET_TIME_relative_to_absolute
1082       (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1083   if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1084     GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1085   kx->keep_alive_task =
1086       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
1087                                     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1088                                      2), &send_keep_alive, kx);
1089 }
1090
1091
1092 /**
1093  * We received a PONG message.  Validate and update our status.
1094  *
1095  * @param kx key exchange context for the the PONG
1096  * @param msg the encrypted PONG message itself
1097  */
1098 void
1099 GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx,
1100                     const struct GNUNET_MessageHeader *msg)
1101 {
1102   const struct PongMessage *m;
1103   struct PongMessage t;
1104   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1105   uint16_t msize;
1106
1107   msize = ntohs (msg->size);
1108   if (sizeof (struct PongMessage) != msize)
1109   {
1110     GNUNET_break_op (0);
1111     return;
1112   }
1113   GNUNET_STATISTICS_update (GSC_stats,
1114                             gettext_noop ("# PONG messages received"), 1,
1115                             GNUNET_NO);
1116   switch (kx->status)
1117   {
1118   case GNUNET_CORE_KX_STATE_DOWN:
1119     GNUNET_STATISTICS_update (GSC_stats,
1120                               gettext_noop ("# PONG messages dropped (connection down)"), 1,
1121                               GNUNET_NO);
1122     return;
1123   case GNUNET_CORE_KX_STATE_KEY_SENT:
1124     GNUNET_STATISTICS_update (GSC_stats,
1125                               gettext_noop ("# PONG messages dropped (out of order)"), 1,
1126                               GNUNET_NO);
1127     return;
1128   case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
1129     break;
1130   case GNUNET_CORE_KX_STATE_UP:
1131     break;
1132   case GNUNET_CORE_KX_STATE_REKEY_SENT:
1133     break;
1134   default:
1135     GNUNET_break (0);
1136     return;
1137   }
1138   m = (const struct PongMessage *) msg;
1139   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1140               "Core service receives `%s' response from `%4s'.\n", "PONG",
1141               GNUNET_i2s (&kx->peer));
1142   /* mark as garbage, just to be sure */
1143   memset (&t, 255, sizeof (t));
1144   derive_pong_iv (&iv, &kx->decrypt_key, m->iv_seed, kx->ping_challenge,
1145                   &GSC_my_identity);
1146   if (GNUNET_OK !=
1147       do_decrypt (kx, &iv, &m->challenge, &t.challenge,
1148                   sizeof (struct PongMessage) - ((void *) &m->challenge -
1149                                                  (void *) m)))
1150   {
1151     GNUNET_break_op (0);
1152     return;
1153   }
1154   GNUNET_STATISTICS_update (GSC_stats,
1155                             gettext_noop ("# PONG messages decrypted"), 1,
1156                             GNUNET_NO);
1157   if ((0 != memcmp (&t.target, &kx->peer, sizeof (struct GNUNET_PeerIdentity)))
1158       || (kx->ping_challenge != t.challenge))
1159   {
1160     /* PONG malformed */
1161     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1162                 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
1163                 "PONG", GNUNET_i2s (&kx->peer),
1164                 (unsigned int) kx->ping_challenge);
1165     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1166                 "Received malformed `%s' received from `%4s' with challenge %u\n",
1167                 "PONG", GNUNET_i2s (&t.target), (unsigned int) t.challenge);
1168     return;
1169   }
1170   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PONG from `%s'\n",
1171               GNUNET_i2s (&kx->peer));
1172   /* no need to resend key any longer */
1173   if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
1174   {
1175     GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1176     kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1177   }
1178   switch (kx->status)
1179   {
1180   case GNUNET_CORE_KX_STATE_DOWN:
1181     GNUNET_assert (0);           /* should be impossible */
1182     return;
1183   case GNUNET_CORE_KX_STATE_KEY_SENT:
1184     GNUNET_assert (0);           /* should be impossible */
1185     return;
1186   case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
1187     GNUNET_STATISTICS_update (GSC_stats,
1188                               gettext_noop
1189                               ("# session keys confirmed via PONG"), 1,
1190                               GNUNET_NO);
1191     kx->status = GNUNET_CORE_KX_STATE_UP;
1192     monitor_notify_all (kx);
1193     GSC_SESSIONS_create (&kx->peer, kx);
1194     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
1195     update_timeout (kx);
1196     break;
1197   case GNUNET_CORE_KX_STATE_UP:
1198     GNUNET_STATISTICS_update (GSC_stats,
1199                               gettext_noop
1200                               ("# timeouts prevented via PONG"), 1,
1201                               GNUNET_NO);
1202     update_timeout (kx);
1203     break;
1204   case GNUNET_CORE_KX_STATE_REKEY_SENT:
1205     GNUNET_STATISTICS_update (GSC_stats,
1206                               gettext_noop
1207                               ("# rekey operations confirmed via PONG"), 1,
1208                               GNUNET_NO);
1209     kx->status = GNUNET_CORE_KX_STATE_UP;
1210     monitor_notify_all (kx);
1211     update_timeout (kx);
1212     break;
1213   default:
1214     GNUNET_break (0);
1215     break;
1216   }
1217 }
1218
1219
1220 /**
1221  * Send our key to the other peer.
1222  *
1223  * @param kx key exchange context
1224  */
1225 static void
1226 send_key (struct GSC_KeyExchangeInfo *kx)
1227 {
1228   GNUNET_assert (GNUNET_CORE_KX_STATE_DOWN != kx->status);
1229   if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
1230   {
1231      GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1232      kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1233   }
1234   /* always update sender status in SET KEY message */
1235   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1236               "Sending key to `%s' (my status: %d)\n",
1237               GNUNET_i2s (&kx->peer),
1238               kx->status);
1239   current_ekm.sender_status = htonl ((int32_t) (kx->status));
1240   GSC_NEIGHBOURS_transmit (&kx->peer, &current_ekm.header,
1241                            kx->set_key_retry_frequency);
1242   kx->retry_set_key_task =
1243       GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
1244                                     &set_key_retry_task, kx);
1245 }
1246
1247
1248 /**
1249  * Encrypt and transmit a message with the given payload.
1250  *
1251  * @param kx key exchange context
1252  * @param payload payload of the message
1253  * @param payload_size number of bytes in 'payload'
1254  */
1255 void
1256 GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
1257                              const void *payload, size_t payload_size)
1258 {
1259   size_t used = payload_size + sizeof (struct EncryptedMessage);
1260   char pbuf[used];              /* plaintext */
1261   char cbuf[used];              /* ciphertext */
1262   struct EncryptedMessage *em;  /* encrypted message */
1263   struct EncryptedMessage *ph;  /* plaintext header */
1264   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1265   struct GNUNET_CRYPTO_AuthKey auth_key;
1266
1267   ph = (struct EncryptedMessage *) pbuf;
1268   ph->iv_seed =
1269       htonl (GNUNET_CRYPTO_random_u32
1270              (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
1271   ph->sequence_number = htonl (++kx->last_sequence_number_sent);
1272   ph->reserved = 0;
1273   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1274   memcpy (&ph[1], payload, payload_size);
1275
1276   em = (struct EncryptedMessage *) cbuf;
1277   em->header.size = htons (used);
1278   em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1279   em->iv_seed = ph->iv_seed;
1280   derive_iv (&iv, &kx->encrypt_key, ph->iv_seed, &kx->peer);
1281   GNUNET_assert (GNUNET_OK ==
1282                  do_encrypt (kx, &iv, &ph->sequence_number,
1283                              &em->sequence_number,
1284                              used - ENCRYPTED_HEADER_SIZE));
1285   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Encrypted %u bytes for %s\n",
1286               used - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1287   derive_auth_key (&auth_key,
1288                    &kx->encrypt_key,
1289                    ph->iv_seed);
1290   GNUNET_CRYPTO_hmac (&auth_key, &em->sequence_number,
1291                       used - ENCRYPTED_HEADER_SIZE, &em->hmac);
1292   GSC_NEIGHBOURS_transmit (&kx->peer, &em->header,
1293                            GNUNET_TIME_UNIT_FOREVER_REL);
1294 }
1295
1296
1297 /**
1298  * Closure for #deliver_message()
1299  */
1300 struct DeliverMessageContext
1301 {
1302
1303   /**
1304    * Key exchange context.
1305    */
1306   struct GSC_KeyExchangeInfo *kx;
1307
1308   /**
1309    * Sender of the message.
1310    */
1311   const struct GNUNET_PeerIdentity *peer;
1312 };
1313
1314
1315 /**
1316  * We received an encrypted message.  Decrypt, validate and
1317  * pass on to the appropriate clients.
1318  *
1319  * @param kx key exchange context for encrypting the message
1320  * @param msg encrypted message
1321  */
1322 void
1323 GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *kx,
1324                                  const struct GNUNET_MessageHeader *msg)
1325 {
1326   const struct EncryptedMessage *m;
1327   struct EncryptedMessage *pt;  /* plaintext */
1328   struct GNUNET_HashCode ph;
1329   uint32_t snum;
1330   struct GNUNET_TIME_Absolute t;
1331   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1332   struct GNUNET_CRYPTO_AuthKey auth_key;
1333   struct DeliverMessageContext dmc;
1334   uint16_t size = ntohs (msg->size);
1335   char buf[size] GNUNET_ALIGN;
1336
1337   if (size <
1338       sizeof (struct EncryptedMessage) + sizeof (struct GNUNET_MessageHeader))
1339   {
1340     GNUNET_break_op (0);
1341     return;
1342   }
1343   m = (const struct EncryptedMessage *) msg;
1344   if (GNUNET_CORE_KX_STATE_UP != kx->status)
1345   {
1346     GNUNET_STATISTICS_update (GSC_stats,
1347                               gettext_noop
1348                               ("# DATA message dropped (out of order)"),
1349                               1, GNUNET_NO);
1350     return;
1351   }
1352   if (0 == GNUNET_TIME_absolute_get_remaining (kx->foreign_key_expires).rel_value_us)
1353   {
1354     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1355                 _("Session to peer `%s' went down due to key expiration (should not happen)\n"),
1356                 GNUNET_i2s (&kx->peer));
1357     GNUNET_STATISTICS_update (GSC_stats,
1358                               gettext_noop ("# sessions terminated by key expiration"),
1359                               1, GNUNET_NO);
1360     GSC_SESSIONS_end (&kx->peer);
1361     if (GNUNET_SCHEDULER_NO_TASK != kx->keep_alive_task)
1362     {
1363       GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1364       kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1365     }
1366     kx->status = GNUNET_CORE_KX_STATE_KEY_SENT;
1367     monitor_notify_all (kx);
1368     send_key (kx);
1369     return;
1370   }
1371
1372   /* validate hash */
1373   derive_auth_key (&auth_key, &kx->decrypt_key, m->iv_seed);
1374   GNUNET_CRYPTO_hmac (&auth_key, &m->sequence_number,
1375                       size - ENCRYPTED_HEADER_SIZE, &ph);
1376   if (0 != memcmp (&ph, &m->hmac, sizeof (struct GNUNET_HashCode)))
1377   {
1378     /* checksum failed */
1379     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1380                 "Failed checksum validation for a message from `%s'\n",
1381                 GNUNET_i2s (&kx->peer));
1382     return;
1383   }
1384   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
1385   /* decrypt */
1386   if (GNUNET_OK !=
1387       do_decrypt (kx, &iv, &m->sequence_number, &buf[ENCRYPTED_HEADER_SIZE],
1388                   size - ENCRYPTED_HEADER_SIZE))
1389     return;
1390   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1391               "Decrypted %u bytes from %s\n",
1392               size - ENCRYPTED_HEADER_SIZE,
1393               GNUNET_i2s (&kx->peer));
1394   pt = (struct EncryptedMessage *) buf;
1395
1396   /* validate sequence number */
1397   snum = ntohl (pt->sequence_number);
1398   if (kx->last_sequence_number_received == snum)
1399   {
1400     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1401                 "Received duplicate message, ignoring.\n");
1402     /* duplicate, ignore */
1403     GNUNET_STATISTICS_update (GSC_stats,
1404                               gettext_noop ("# bytes dropped (duplicates)"),
1405                               size, GNUNET_NO);
1406     return;
1407   }
1408   if ((kx->last_sequence_number_received > snum) &&
1409       (kx->last_sequence_number_received - snum > 32))
1410   {
1411     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1412                 "Received ancient out of sequence message, ignoring.\n");
1413     /* ancient out of sequence, ignore */
1414     GNUNET_STATISTICS_update (GSC_stats,
1415                               gettext_noop
1416                               ("# bytes dropped (out of sequence)"), size,
1417                               GNUNET_NO);
1418     return;
1419   }
1420   if (kx->last_sequence_number_received > snum)
1421   {
1422     unsigned int rotbit = 1 << (kx->last_sequence_number_received - snum - 1);
1423
1424     if ((kx->last_packets_bitmap & rotbit) != 0)
1425     {
1426       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1427                   "Received duplicate message, ignoring.\n");
1428       GNUNET_STATISTICS_update (GSC_stats,
1429                                 gettext_noop ("# bytes dropped (duplicates)"),
1430                                 size, GNUNET_NO);
1431       /* duplicate, ignore */
1432       return;
1433     }
1434     kx->last_packets_bitmap |= rotbit;
1435   }
1436   if (kx->last_sequence_number_received < snum)
1437   {
1438     unsigned int shift = (snum - kx->last_sequence_number_received);
1439
1440     if (shift >= 8 * sizeof (kx->last_packets_bitmap))
1441       kx->last_packets_bitmap = 0;
1442     else
1443       kx->last_packets_bitmap <<= shift;
1444     kx->last_sequence_number_received = snum;
1445   }
1446
1447   /* check timestamp */
1448   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
1449   if (GNUNET_TIME_absolute_get_duration (t).rel_value_us >
1450       MAX_MESSAGE_AGE.rel_value_us)
1451   {
1452     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1453                 "Message received far too old (%s). Content ignored.\n",
1454                 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (t),
1455                                                         GNUNET_YES));
1456     GNUNET_STATISTICS_update (GSC_stats,
1457                               gettext_noop
1458                               ("# bytes dropped (ancient message)"), size,
1459                               GNUNET_NO);
1460     return;
1461   }
1462
1463   /* process decrypted message(s) */
1464   update_timeout (kx);
1465   GNUNET_STATISTICS_update (GSC_stats,
1466                             gettext_noop ("# bytes of payload decrypted"),
1467                             size - sizeof (struct EncryptedMessage),
1468                             GNUNET_NO);
1469   dmc.kx = kx;
1470   dmc.peer = &kx->peer;
1471   if (GNUNET_OK !=
1472       GNUNET_SERVER_mst_receive (mst, &dmc,
1473                                  &buf[sizeof (struct EncryptedMessage)],
1474                                  size - sizeof (struct EncryptedMessage),
1475                                  GNUNET_YES,
1476                                  GNUNET_NO))
1477     GNUNET_break_op (0);
1478 }
1479
1480
1481 /**
1482  * Deliver P2P message to interested clients.
1483  * Invokes send twice, once for clients that want the full message, and once
1484  * for clients that only want the header
1485  *
1486  * @param cls always NULL
1487  * @param client who sent us the message (struct GSC_KeyExchangeInfo)
1488  * @param m the message
1489  */
1490 static int
1491 deliver_message (void *cls,
1492                  void *client,
1493                  const struct GNUNET_MessageHeader *m)
1494 {
1495   struct DeliverMessageContext *dmc = client;
1496
1497   if (GNUNET_CORE_KX_STATE_UP != dmc->kx->status)
1498   {
1499     GNUNET_STATISTICS_update (GSC_stats,
1500                               gettext_noop
1501                               ("# PAYLOAD dropped (out of order)"),
1502                               1, GNUNET_NO);
1503     return GNUNET_OK;
1504   }
1505   switch (ntohs (m->type))
1506   {
1507   case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP:
1508   case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP:
1509     GSC_SESSIONS_set_typemap (dmc->peer, m);
1510     return GNUNET_OK;
1511   default:
1512     GSC_CLIENTS_deliver_message (dmc->peer, m,
1513                                  ntohs (m->size),
1514                                  GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
1515     GSC_CLIENTS_deliver_message (dmc->peer, m,
1516                                  sizeof (struct GNUNET_MessageHeader),
1517                                  GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
1518   }
1519   return GNUNET_OK;
1520 }
1521
1522
1523 /**
1524  * Setup the message that links the ephemeral key to our persistent
1525  * public key and generate the appropriate signature.
1526  */
1527 static void
1528 sign_ephemeral_key ()
1529 {
1530   current_ekm.header.size = htons (sizeof (struct EphemeralKeyMessage));
1531   current_ekm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY);
1532   current_ekm.sender_status = 0; /* to be set later */
1533   current_ekm.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY);
1534   current_ekm.purpose.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
1535                                     sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1536                                     sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1537                                     sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
1538                                     sizeof (struct GNUNET_PeerIdentity));
1539   current_ekm.creation_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1540   if (GNUNET_YES ==
1541       GNUNET_CONFIGURATION_get_value_yesno (GSC_cfg,
1542                                             "core",
1543                                             "USE_EPHEMERAL_KEYS"))
1544   {
1545     current_ekm.expiration_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_add (REKEY_FREQUENCY,
1546                                                                                                                          REKEY_TOLERANCE)));
1547   }
1548   else
1549   {
1550     current_ekm.expiration_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_FOREVER_ABS);
1551   }
1552   GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key,
1553                                       &current_ekm.ephemeral_key);
1554   current_ekm.origin_identity = GSC_my_identity;
1555   GNUNET_assert (GNUNET_OK ==
1556                  GNUNET_CRYPTO_eddsa_sign (my_private_key,
1557                                          &current_ekm.purpose,
1558                                          &current_ekm.signature));
1559 }
1560
1561
1562 /**
1563  * Task run to trigger rekeying.
1564  *
1565  * @param cls closure, NULL
1566  * @param tc scheduler context
1567  */
1568 static void
1569 do_rekey (void *cls,
1570           const struct GNUNET_SCHEDULER_TaskContext *tc)
1571 {
1572   struct GSC_KeyExchangeInfo *pos;
1573
1574   rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY,
1575                                              &do_rekey,
1576                                              NULL);
1577   if (NULL != my_ephemeral_key)
1578     GNUNET_free (my_ephemeral_key);
1579   my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1580   GNUNET_assert (NULL != my_ephemeral_key);
1581   sign_ephemeral_key ();
1582   for (pos = kx_head; NULL != pos; pos = pos->next)
1583   {
1584     if (GNUNET_CORE_KX_STATE_UP == pos->status)
1585     {
1586       pos->status = GNUNET_CORE_KX_STATE_REKEY_SENT;
1587       monitor_notify_all (pos);
1588       derive_session_keys (pos);
1589     }
1590     if (GNUNET_CORE_KX_STATE_DOWN == pos->status)
1591     {
1592       pos->status = GNUNET_CORE_KX_STATE_KEY_SENT;
1593       monitor_notify_all (pos);
1594     }
1595     monitor_notify_all (pos);
1596     send_key (pos);
1597   }
1598 }
1599
1600
1601 /**
1602  * Initialize KX subsystem.
1603  *
1604  * @param pk private key to use for the peer
1605  * @param server the server of the CORE service
1606  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1607  */
1608 int
1609 GSC_KX_init (struct GNUNET_CRYPTO_EddsaPrivateKey *pk,
1610              struct GNUNET_SERVER_Handle *server)
1611 {
1612   nc = GNUNET_SERVER_notification_context_create (server,
1613                                                   1);
1614   my_private_key = pk;
1615   GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
1616                                                   &GSC_my_identity.public_key);
1617   my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1618   if (NULL == my_ephemeral_key)
1619   {
1620     GNUNET_break (0);
1621     GNUNET_free (my_private_key);
1622     my_private_key = NULL;
1623     return GNUNET_SYSERR;
1624   }
1625   sign_ephemeral_key ();
1626   rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY,
1627                                              &do_rekey,
1628                                              NULL);
1629   mst = GNUNET_SERVER_mst_create (&deliver_message, NULL);
1630   return GNUNET_OK;
1631 }
1632
1633
1634 /**
1635  * Shutdown KX subsystem.
1636  */
1637 void
1638 GSC_KX_done ()
1639 {
1640   if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1641   {
1642     GNUNET_SCHEDULER_cancel (rekey_task);
1643     rekey_task = GNUNET_SCHEDULER_NO_TASK;
1644   }
1645   if (NULL != my_ephemeral_key)
1646   {
1647     GNUNET_free (my_ephemeral_key);
1648     my_ephemeral_key = NULL;
1649   }
1650   if (NULL != my_private_key)
1651   {
1652     GNUNET_free (my_private_key);
1653     my_private_key = NULL;
1654   }
1655   if (NULL != mst)
1656   {
1657     GNUNET_SERVER_mst_destroy (mst);
1658     mst = NULL;
1659   }
1660   if (NULL != nc)
1661   {
1662     GNUNET_SERVER_notification_context_destroy (nc);
1663     nc = NULL;
1664   }
1665 }
1666
1667
1668 /**
1669  * Handle #GNUNET_MESSAGE_TYPE_CORE_MONITOR_PEERS request.  For this
1670  * request type, the client does not have to have transmitted an INIT
1671  * request.  All current peers are returned, regardless of which
1672  * message types they accept.
1673  *
1674  * @param cls unused
1675  * @param client client sending the iteration request
1676  * @param message iteration request message
1677  */
1678 void
1679 GSC_KX_handle_client_monitor_peers (void *cls,
1680                                     struct GNUNET_SERVER_Client *client,
1681                                     const struct GNUNET_MessageHeader *message)
1682 {
1683   struct MonitorNotifyMessage done_msg;
1684   struct GSC_KeyExchangeInfo *kx;
1685
1686   GNUNET_SERVER_notification_context_add (nc,
1687                                           client);
1688   for (kx = kx_head; NULL != kx; kx = kx->next)
1689     monitor_notify (client, kx);
1690   done_msg.header.size = htons (sizeof (struct MonitorNotifyMessage));
1691   done_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY);
1692   done_msg.state = htonl ((uint32_t) GNUNET_CORE_KX_ITERATION_FINISHED);
1693   memset (&done_msg.peer, 0, sizeof (struct GNUNET_PeerIdentity));
1694   done_msg.timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_FOREVER_ABS);
1695   GNUNET_SERVER_notification_context_unicast (nc,
1696                                               client,
1697                                               &done_msg.header,
1698                                               GNUNET_NO);
1699 }
1700
1701
1702 /* end of gnunet-service-core_kx.c */