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