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