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