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