- htons => htonl
[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 CORE_EPHEMERAL_KEY.
81    */
82   struct GNUNET_MessageHeader header;
83
84   /**
85    * Status of the sender (should be in "enum PeerStateMachine"), nbo.
86    */
87   int32_t sender_status GNUNET_PACKED;
88
89   /**
90    * An ECC signature of the 'origin' asserting the validity of
91    * the given ephemeral key.
92    */
93   struct GNUNET_CRYPTO_EddsaSignature signature;
94
95   /**
96    * Information about what is being signed.
97    */
98   struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
99
100   /**
101    * At what time was this key created (beginning of validity).
102    */
103   struct GNUNET_TIME_AbsoluteNBO creation_time;
104
105   /**
106    * When does the given ephemeral key expire (end of validity).
107    */
108   struct GNUNET_TIME_AbsoluteNBO expiration_time;
109
110   /**
111    * Ephemeral public ECC key.
112    */
113   struct GNUNET_CRYPTO_EcdhePublicKey ephemeral_key;
114
115   /**
116    * Public key of the signing peer (persistent version, not the ephemeral public key).
117    */
118   struct GNUNET_PeerIdentity origin_identity;
119
120 };
121
122
123 /**
124  * We're sending an (encrypted) PING to the other peer to check if he
125  * can decrypt.  The other peer should respond with a PONG with the
126  * same content, except this time encrypted with the receiver's key.
127  */
128 struct PingMessage
129 {
130   /**
131    * Message type is 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 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 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  * State machine for our P2P encryption handshake.  Everyone starts in
241  * "DOWN", if we receive the other peer's key (other peer initiated)
242  * we start in state RECEIVED (since we will immediately send our
243  * own); otherwise we start in SENT.  If we get back a PONG from
244  * within either state, we move up to CONFIRMED (the PONG will always
245  * be sent back encrypted with the key we sent to the other peer).
246  */
247 enum KxStateMachine
248 {
249   /**
250    * No handshake yet.
251    */
252   KX_STATE_DOWN,
253
254   /**
255    * We've sent our session key.
256    */
257   KX_STATE_KEY_SENT,
258
259   /**
260    * We've received the other peers session key.
261    */
262   KX_STATE_KEY_RECEIVED,
263
264   /**
265    * The other peer has confirmed our session key + PING with a PONG
266    * message encrypted with his session key (which we got).  Key
267    * exchange is done.
268    */
269   KX_STATE_UP,
270
271   /**
272    * We're rekeying (or had a timeout), so we have sent the other peer
273    * our new ephemeral key, but we did not get a matching PONG yet.
274    * This is equivalent to being 'KX_STATE_KEY_RECEIVED', except that
275    * the session is marked as 'up' with sessions (as we don't want to
276    * drop and re-establish P2P connections simply due to rekeying).
277    */
278   KX_STATE_REKEY_SENT
279
280 };
281
282
283 /**
284  * Information about the status of a key exchange with another peer.
285  */
286 struct GSC_KeyExchangeInfo
287 {
288
289   /**
290    * DLL.
291    */
292   struct GSC_KeyExchangeInfo *next;
293
294   /**
295    * DLL.
296    */
297   struct GSC_KeyExchangeInfo *prev;
298
299   /**
300    * Identity of the peer.
301    */
302   struct GNUNET_PeerIdentity peer;
303
304   /**
305    * PING message we transmit to the other peer.
306    */
307   struct PingMessage ping;
308
309   /**
310    * Ephemeral public ECC key of the other peer.
311    */
312   struct GNUNET_CRYPTO_EcdhePublicKey other_ephemeral_key;
313
314   /**
315    * Key we use to encrypt our messages for the other peer
316    * (initialized by us when we do the handshake).
317    */
318   struct GNUNET_CRYPTO_SymmetricSessionKey encrypt_key;
319
320   /**
321    * Key we use to decrypt messages from the other peer
322    * (given to us by the other peer during the handshake).
323    */
324   struct GNUNET_CRYPTO_SymmetricSessionKey decrypt_key;
325
326   /**
327    * At what time did the other peer generate the decryption key?
328    */
329   struct GNUNET_TIME_Absolute foreign_key_expires;
330
331   /**
332    * When should the session time out (if there are no PONGs)?
333    */
334   struct GNUNET_TIME_Absolute timeout;
335
336   /**
337    * At what frequency are we currently re-trying SET_KEY messages?
338    */
339   struct GNUNET_TIME_Relative set_key_retry_frequency;
340
341   /**
342    * ID of task used for re-trying SET_KEY and PING message.
343    */
344   GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
345
346   /**
347    * ID of task used for sending keep-alive pings.
348    */
349   GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
350
351   /**
352    * Bit map indicating which of the 32 sequence numbers before the last
353    * were received (good for accepting out-of-order packets and
354    * estimating reliability of the connection)
355    */
356   unsigned int last_packets_bitmap;
357
358   /**
359    * last sequence number received on this connection (highest)
360    */
361   uint32_t last_sequence_number_received;
362
363   /**
364    * last sequence number transmitted
365    */
366   uint32_t last_sequence_number_sent;
367
368   /**
369    * What was our PING challenge number (for this peer)?
370    */
371   uint32_t ping_challenge;
372
373   /**
374    * What is our connection status?
375    */
376   enum KxStateMachine status;
377
378 };
379
380
381 /**
382  * Our private key.
383  */
384 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
385
386 /**
387  * Our ephemeral private key.
388  */
389 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
390
391 /**
392  * Current message we send for a key exchange.
393  */
394 static struct EphemeralKeyMessage current_ekm;
395
396 /**
397  * Our message stream tokenizer (for encrypted payload).
398  */
399 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
400
401 /**
402  * DLL head.
403  */
404 static struct GSC_KeyExchangeInfo *kx_head;
405
406 /**
407  * DLL tail.
408  */
409 static struct GSC_KeyExchangeInfo *kx_tail;
410
411 /**
412  * Task scheduled for periodic re-generation (and thus rekeying) of our
413  * ephemeral key.
414  */
415 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
416
417
418 /**
419  * Derive an authentication key from "set key" information
420  *
421  * @param akey authentication key to derive
422  * @param skey session key to use
423  * @param seed seed to use
424  */
425 static void
426 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
427                  const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, uint32_t seed)
428 {
429   static const char ctx[] = "authentication key";
430
431   GNUNET_CRYPTO_hmac_derive_key (akey, skey,
432                                  &seed, sizeof (seed),
433                                  skey, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
434                                  ctx, sizeof (ctx),
435                                  NULL);
436 }
437
438
439 /**
440  * Derive an IV from packet information
441  *
442  * @param iv initialization vector to initialize
443  * @param skey session key to use
444  * @param seed seed to use
445  * @param identity identity of the other peer to use
446  */
447 static void
448 derive_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
449            const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, uint32_t seed,
450            const struct GNUNET_PeerIdentity *identity)
451 {
452   static const char ctx[] = "initialization vector";
453
454   GNUNET_CRYPTO_symmetric_derive_iv (iv, skey, &seed, sizeof (seed),
455                                      identity,
456                                      sizeof (struct GNUNET_PeerIdentity), ctx,
457                                      sizeof (ctx), NULL);
458 }
459
460
461 /**
462  * Derive an IV from pong packet information
463  *
464  * @param iv initialization vector to initialize
465  * @param skey session key to use
466  * @param seed seed to use
467  * @param challenge nonce to use
468  * @param identity identity of the other peer to use
469  */
470 static void
471 derive_pong_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
472                 const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, uint32_t seed,
473                 uint32_t challenge, const struct GNUNET_PeerIdentity *identity)
474 {
475   static const char ctx[] = "pong initialization vector";
476
477   GNUNET_CRYPTO_symmetric_derive_iv (iv, skey, &seed, sizeof (seed),
478                                      identity,
479                                      sizeof (struct GNUNET_PeerIdentity),
480                                      &challenge, sizeof (challenge),
481                                      ctx, sizeof (ctx),
482                                      NULL);
483 }
484
485
486 /**
487  * Derive an AES key from key material
488  *
489  * @param sender peer identity of the sender
490  * @param receiver peer identity of the sender
491  * @param key_material high entropy key material to use
492  * @param skey set to derived session key
493  */
494 static void
495 derive_aes_key (const struct GNUNET_PeerIdentity *sender,
496                 const struct GNUNET_PeerIdentity *receiver,
497                 const struct GNUNET_HashCode *key_material,
498                 struct GNUNET_CRYPTO_SymmetricSessionKey *skey)
499 {
500   static const char ctx[] = "aes key generation vector";
501
502   GNUNET_CRYPTO_kdf (skey, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
503                      ctx, sizeof (ctx),
504                      key_material, sizeof (struct GNUNET_HashCode),
505                      sender, sizeof (struct GNUNET_PeerIdentity),
506                      receiver, sizeof (struct GNUNET_PeerIdentity),
507                      NULL);
508 }
509
510
511 /**
512  * Encrypt size bytes from in and write the result to out.  Use the
513  * key for outbound traffic of the given neighbour.
514  *
515  * @param kx key information context
516  * @param iv initialization vector to use
517  * @param in ciphertext
518  * @param out plaintext
519  * @param size size of in/out
520  * @return GNUNET_OK on success
521  */
522 static int
523 do_encrypt (struct GSC_KeyExchangeInfo *kx,
524             const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
525             const void *in, void *out, size_t size)
526 {
527   if (size != (uint16_t) size)
528   {
529     GNUNET_break (0);
530     return GNUNET_NO;
531   }
532   GNUNET_assert (size ==
533                  GNUNET_CRYPTO_symmetric_encrypt (in, (uint16_t) size,
534                                             &kx->encrypt_key, iv, out));
535   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes encrypted"), size,
536                             GNUNET_NO);
537   /* the following is too sensitive to write to log files by accident,
538      so we require manual intervention to get this one... */
539 #if 0
540   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
541               "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
542               (unsigned int) size, GNUNET_i2s (&kx->peer),
543               (unsigned int) kx->encrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
544                                                                            sizeof
545                                                                            (iv)));
546 #endif
547   return GNUNET_OK;
548 }
549
550
551 /**
552  * Decrypt size bytes from in and write the result to out.  Use the
553  * key for inbound traffic of the given neighbour.  This function does
554  * NOT do any integrity-checks on the result.
555  *
556  * @param kx key information context
557  * @param iv initialization vector to use
558  * @param in ciphertext
559  * @param out plaintext
560  * @param size size of @a in / @a out
561  * @return #GNUNET_OK on success
562  */
563 static int
564 do_decrypt (struct GSC_KeyExchangeInfo *kx,
565             const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
566             const void *in, void *out, size_t size)
567 {
568   if (size != (uint16_t) size)
569   {
570     GNUNET_break (0);
571     return GNUNET_NO;
572   }
573   if ( (kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP) &&
574        (kx->status != KX_STATE_REKEY_SENT) )
575   {
576     GNUNET_break_op (0);
577     return GNUNET_SYSERR;
578   }
579   if (size !=
580       GNUNET_CRYPTO_symmetric_decrypt (in, (uint16_t) size, &kx->decrypt_key, iv,
581                                  out))
582   {
583     GNUNET_break (0);
584     return GNUNET_SYSERR;
585   }
586   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes decrypted"), size,
587                             GNUNET_NO);
588   /* the following is too sensitive to write to log files by accident,
589      so we require manual intervention to get this one... */
590 #if 0
591   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
592               "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
593               (unsigned int) size, GNUNET_i2s (&kx->peer),
594               (unsigned int) kx->decrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
595                                                                            sizeof
596                                                                            (*iv)));
597 #endif
598   return GNUNET_OK;
599 }
600
601
602 /**
603  * Send our key (and encrypted PING) to the other peer.
604  *
605  * @param kx key exchange context
606  */
607 static void
608 send_key (struct GSC_KeyExchangeInfo *kx);
609
610
611 /**
612  * Task that will retry "send_key" if our previous attempt failed.
613  *
614  * @param cls our 'struct GSC_KeyExchangeInfo'
615  * @param tc scheduler context
616  */
617 static void
618 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
619 {
620   struct GSC_KeyExchangeInfo *kx = cls;
621
622   kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
623   kx->set_key_retry_frequency = GNUNET_TIME_STD_BACKOFF (kx->set_key_retry_frequency);
624   GNUNET_assert (KX_STATE_DOWN != kx->status);
625   send_key (kx);
626 }
627
628
629 /**
630  * Create a fresh PING message for transmission to the other peer.
631  *
632  * @param kx key exchange context to create PING for
633  */
634 static void
635 setup_fresh_ping (struct GSC_KeyExchangeInfo *kx)
636 {
637   struct PingMessage pp;
638   struct PingMessage *pm;
639   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
640
641   pm = &kx->ping;
642   pm->header.size = htons (sizeof (struct PingMessage));
643   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
644   pm->iv_seed =
645       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
646   derive_iv (&iv, &kx->encrypt_key, pm->iv_seed, &kx->peer);
647   pp.challenge = kx->ping_challenge;
648   pp.target = kx->peer;
649   do_encrypt (kx, &iv, &pp.target, &pm->target,
650               sizeof (struct PingMessage) - ((void *) &pm->target -
651                                              (void *) pm));
652 }
653
654
655 /**
656  * Start the key exchange with the given peer.
657  *
658  * @param pid identity of the peer to do a key exchange with
659  * @return key exchange information context
660  */
661 struct GSC_KeyExchangeInfo *
662 GSC_KX_start (const struct GNUNET_PeerIdentity *pid)
663 {
664   struct GSC_KeyExchangeInfo *kx;
665   struct GNUNET_HashCode h1;
666   struct GNUNET_HashCode h2;
667
668   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
669               "Initiating key exchange with `%s'\n",
670               GNUNET_i2s (pid));
671   GNUNET_STATISTICS_update (GSC_stats,
672                             gettext_noop ("# key exchanges initiated"), 1,
673                             GNUNET_NO);
674   kx = GNUNET_new (struct GSC_KeyExchangeInfo);
675   kx->peer = *pid;
676   kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
677   GNUNET_CONTAINER_DLL_insert (kx_head,
678                                kx_tail,
679                                kx);
680   GNUNET_CRYPTO_hash (pid, sizeof (struct GNUNET_PeerIdentity), &h1);
681   GNUNET_CRYPTO_hash (&GSC_my_identity, sizeof (struct GNUNET_PeerIdentity), &h2);
682
683   kx->status = KX_STATE_KEY_SENT;
684   if (0 < GNUNET_CRYPTO_hash_cmp (&h1,
685                                   &h2))
686   {
687     /* peer with "lower" identity starts KX, otherwise we typically end up
688        with both peers starting the exchange and transmit the 'set key'
689        message twice */
690     send_key (kx);
691   }
692   else
693   {
694     /* peer with "higher" identity starts a delayed  KX, if the "lower" peer
695      * does not start a KX since he sees no reasons to do so  */
696     kx->retry_set_key_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
697           &set_key_retry_task, kx);
698   }
699   return kx;
700 }
701
702
703 /**
704  * Stop key exchange with the given peer.  Clean up key material.
705  *
706  * @param kx key exchange to stop
707  */
708 void
709 GSC_KX_stop (struct GSC_KeyExchangeInfo *kx)
710 {
711   GSC_SESSIONS_end (&kx->peer);
712   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# key exchanges stopped"),
713                             1, GNUNET_NO);
714   if (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
715   {
716     GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
717     kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
718   }
719   if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
720   {
721     GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
722     kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
723   }
724   GNUNET_CONTAINER_DLL_remove (kx_head,
725                                kx_tail,
726                                kx);
727   GNUNET_free (kx);
728 }
729
730
731 /**
732  * Send our PING to the other peer.
733  *
734  * @param kx key exchange context
735  */
736 static void
737 send_ping (struct GSC_KeyExchangeInfo *kx)
738 {
739   GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
740                            MIN_PING_FREQUENCY);
741 }
742
743
744 /**
745  * Derive fresh session keys from the current ephemeral keys.
746  *
747  * @param kx session to derive keys for
748  */
749 static void
750 derive_session_keys (struct GSC_KeyExchangeInfo *kx)
751 {
752   struct GNUNET_HashCode key_material;
753
754   if (GNUNET_OK !=
755       GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
756                               &kx->other_ephemeral_key,
757                               &key_material))
758   {
759     GNUNET_break (0);
760     return;
761   }
762   derive_aes_key (&GSC_my_identity,
763                   &kx->peer,
764                   &key_material,
765                   &kx->encrypt_key);
766   derive_aes_key (&kx->peer,
767                   &GSC_my_identity,
768                   &key_material,
769                   &kx->decrypt_key);
770   memset (&key_material, 0, sizeof (key_material));
771   /* fresh key, reset sequence numbers */
772   kx->last_sequence_number_received = 0;
773   kx->last_packets_bitmap = 0;
774   setup_fresh_ping (kx);
775 }
776
777
778 /**
779  * We received a SET_KEY message.  Validate and update
780  * our key material and status.
781  *
782  * @param kx key exchange status for the corresponding peer
783  * @param msg the set key message we received
784  */
785 void
786 GSC_KX_handle_ephemeral_key (struct GSC_KeyExchangeInfo *kx,
787                              const struct GNUNET_MessageHeader *msg)
788 {
789   const struct EphemeralKeyMessage *m;
790   struct GNUNET_TIME_Absolute start_t;
791   struct GNUNET_TIME_Absolute end_t;
792   struct GNUNET_TIME_Absolute now;
793   enum KxStateMachine sender_status;
794   uint16_t size;
795
796   size = ntohs (msg->size);
797   if (sizeof (struct EphemeralKeyMessage) != size)
798   {
799     GNUNET_break_op (0);
800     return;
801   }
802   m = (const struct EphemeralKeyMessage *) msg;
803   end_t = GNUNET_TIME_absolute_ntoh (m->expiration_time);
804   if ( ( (KX_STATE_KEY_RECEIVED == kx->status) ||
805          (KX_STATE_UP == kx->status) ||
806          (KX_STATE_REKEY_SENT == kx->status) ) &&
807        (end_t.abs_value_us <= kx->foreign_key_expires.abs_value_us) )
808   {
809     GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# old ephemeral keys ignored"),
810                               1, GNUNET_NO);
811     return;
812   }
813   start_t = GNUNET_TIME_absolute_ntoh (m->creation_time);
814
815   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# ephemeral keys received"),
816                             1, GNUNET_NO);
817
818   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
819               "Core service receives `%s' request from `%4s'.\n", "EPHEMERAL_KEY",
820               GNUNET_i2s (&kx->peer));
821   if (0 !=
822       memcmp (&m->origin_identity,
823               &kx->peer.public_key,
824               sizeof (struct GNUNET_PeerIdentity)))
825   {
826     GNUNET_break_op (0);
827     return;
828   }
829   if ((ntohl (m->purpose.size) !=
830        sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
831        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
832        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
833        sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) +
834        sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)) ||
835       (GNUNET_OK !=
836        GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY,
837                                  &m->purpose,
838                                  &m->signature, &m->origin_identity.public_key)))
839   {
840     /* invalid signature */
841     GNUNET_break_op (0);
842     return;
843   }
844   now = GNUNET_TIME_absolute_get ();
845   if ( (end_t.abs_value_us < GNUNET_TIME_absolute_subtract (now, REKEY_TOLERANCE).abs_value_us) ||
846        (start_t.abs_value_us > GNUNET_TIME_absolute_add (now, REKEY_TOLERANCE).abs_value_us) )
847   {
848     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
849                 _("Ephemeral key message from peer `%s' rejected as its validity range does not match our system time (%llu not in [%llu,%llu]).\n"),
850                 GNUNET_i2s (&kx->peer),
851                 now.abs_value_us,
852                 start_t.abs_value_us,
853                 end_t.abs_value_us);
854     return;
855   }
856   kx->other_ephemeral_key = m->ephemeral_key;
857   kx->foreign_key_expires = end_t;
858   derive_session_keys (kx);
859   GNUNET_STATISTICS_update (GSC_stats,
860                             gettext_noop ("# EPHEMERAL_KEY messages received"), 1,
861                             GNUNET_NO);
862
863   /* check if we still need to send the sender our key */
864   sender_status = (enum KxStateMachine) ntohl (m->sender_status);
865   switch (sender_status)
866   {
867   case KX_STATE_DOWN:
868     GNUNET_break_op (0);
869     break;
870   case KX_STATE_KEY_SENT:
871     /* fine, need to send our key after updating our status, see below */
872     break;
873   case KX_STATE_KEY_RECEIVED:
874   case KX_STATE_UP:
875   case KX_STATE_REKEY_SENT:
876     /* other peer already got our key */
877     break;
878   default:
879     GNUNET_break (0);
880     break;
881   }
882   /* check if we need to confirm everything is fine via PING + PONG */
883   switch (kx->status)
884   {
885   case KX_STATE_DOWN:
886     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
887     kx->status = KX_STATE_KEY_RECEIVED;
888     if (KX_STATE_KEY_SENT == sender_status)
889       send_key (kx);
890     send_ping (kx);
891     break;
892   case KX_STATE_KEY_SENT:
893     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
894     kx->status = KX_STATE_KEY_RECEIVED;
895     if (KX_STATE_KEY_SENT == sender_status)
896       send_key (kx);
897     send_ping (kx);
898     break;
899   case KX_STATE_KEY_RECEIVED:
900     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
901     if (KX_STATE_KEY_SENT == sender_status)
902       send_key (kx);
903     send_ping (kx);
904     break;
905   case KX_STATE_UP:
906     kx->status = KX_STATE_REKEY_SENT;
907     if (KX_STATE_KEY_SENT == sender_status)
908       send_key (kx);
909     /* we got a new key, need to reconfirm! */
910     send_ping (kx);
911     break;
912   case KX_STATE_REKEY_SENT:
913     if (KX_STATE_KEY_SENT == sender_status)
914       send_key (kx);
915     /* we got a new key, need to reconfirm! */
916     send_ping (kx);
917     break;
918   default:
919     GNUNET_break (0);
920     break;
921   }
922 }
923
924
925 /**
926  * We received a PING message.  Validate and transmit
927  * a PONG message.
928  *
929  * @param kx key exchange status for the corresponding peer
930  * @param msg the encrypted PING message itself
931  */
932 void
933 GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *kx,
934                     const struct GNUNET_MessageHeader *msg)
935 {
936   const struct PingMessage *m;
937   struct PingMessage t;
938   struct PongMessage tx;
939   struct PongMessage tp;
940   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
941   uint16_t msize;
942
943   msize = ntohs (msg->size);
944   if (msize != sizeof (struct PingMessage))
945   {
946     GNUNET_break_op (0);
947     return;
948   }
949   GNUNET_STATISTICS_update (GSC_stats,
950                             gettext_noop ("# PING messages received"), 1,
951                             GNUNET_NO);
952   if ( (kx->status != KX_STATE_KEY_RECEIVED) &&
953        (kx->status != KX_STATE_UP) &&
954        (kx->status != KX_STATE_REKEY_SENT))
955   {
956     /* ignore */
957     GNUNET_STATISTICS_update (GSC_stats,
958                               gettext_noop ("# PING messages dropped (out of order)"), 1,
959                               GNUNET_NO);
960     return;
961   }
962   m = (const struct PingMessage *) msg;
963   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
964               "Core service receives `%s' request from `%4s'.\n", "PING",
965               GNUNET_i2s (&kx->peer));
966   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
967   if (GNUNET_OK !=
968       do_decrypt (kx, &iv, &m->target, &t.target,
969                   sizeof (struct PingMessage) - ((void *) &m->target -
970                                                  (void *) m)))
971   {
972     GNUNET_break_op (0);
973     return;
974   }
975   if (0 !=
976       memcmp (&t.target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
977   {
978     char sender[9];
979     char peer[9];
980
981     GNUNET_snprintf (sender, sizeof (sender), "%8s", GNUNET_i2s (&kx->peer));
982     GNUNET_snprintf (peer, sizeof (peer), "%8s", GNUNET_i2s (&t.target));
983     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
984                 _
985                 ("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
986                 sender, GNUNET_i2s (&GSC_my_identity), peer);
987     GNUNET_break_op (0);
988     return;
989   }
990   /* construct PONG */
991   tx.reserved = 0;
992   tx.challenge = t.challenge;
993   tx.target = t.target;
994   tp.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
995   tp.header.size = htons (sizeof (struct PongMessage));
996   tp.iv_seed =
997       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
998   derive_pong_iv (&iv, &kx->encrypt_key, tp.iv_seed, t.challenge, &kx->peer);
999   do_encrypt (kx, &iv, &tx.challenge, &tp.challenge,
1000               sizeof (struct PongMessage) - ((void *) &tp.challenge -
1001                                              (void *) &tp));
1002   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages created"),
1003                             1, GNUNET_NO);
1004   GSC_NEIGHBOURS_transmit (&kx->peer, &tp.header,
1005                            GNUNET_TIME_UNIT_FOREVER_REL /* FIXME: timeout */ );
1006 }
1007
1008
1009 /**
1010  * Task triggered when a neighbour entry is about to time out
1011  * (and we should prevent this by sending a PING).
1012  *
1013  * @param cls the 'struct GSC_KeyExchangeInfo'
1014  * @param tc scheduler context (not used)
1015  */
1016 static void
1017 send_keep_alive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1018 {
1019   struct GSC_KeyExchangeInfo *kx = cls;
1020   struct GNUNET_TIME_Relative retry;
1021   struct GNUNET_TIME_Relative left;
1022
1023   kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1024   left = GNUNET_TIME_absolute_get_remaining (kx->timeout);
1025   if (0 == left.rel_value_us)
1026   {
1027     GNUNET_STATISTICS_update (GSC_stats,
1028                               gettext_noop ("# sessions terminated by timeout"),
1029                               1, GNUNET_NO);
1030     GSC_SESSIONS_end (&kx->peer);
1031     kx->status = KX_STATE_KEY_SENT;
1032     send_key (kx);
1033     return;
1034   }
1035   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending KEEPALIVE to `%s'\n",
1036               GNUNET_i2s (&kx->peer));
1037   GNUNET_STATISTICS_update (GSC_stats,
1038                             gettext_noop ("# keepalive messages sent"), 1,
1039                             GNUNET_NO);
1040   setup_fresh_ping (kx);
1041   GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
1042                            kx->set_key_retry_frequency);
1043   retry =
1044       GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1045                                 MIN_PING_FREQUENCY);
1046   kx->keep_alive_task =
1047       GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx);
1048 }
1049
1050
1051 /**
1052  * We've seen a valid message from the other peer.
1053  * Update the time when the session would time out
1054  * and delay sending our keep alive message further.
1055  *
1056  * @param kx key exchange where we saw activity
1057  */
1058 static void
1059 update_timeout (struct GSC_KeyExchangeInfo *kx)
1060 {
1061   kx->timeout =
1062       GNUNET_TIME_relative_to_absolute
1063       (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1064   if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1065     GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1066   kx->keep_alive_task =
1067       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
1068                                     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1069                                      2), &send_keep_alive, kx);
1070 }
1071
1072
1073 /**
1074  * We received a PONG message.  Validate and update our status.
1075  *
1076  * @param kx key exchange context for the the PONG
1077  * @param msg the encrypted PONG message itself
1078  */
1079 void
1080 GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx,
1081                     const struct GNUNET_MessageHeader *msg)
1082 {
1083   const struct PongMessage *m;
1084   struct PongMessage t;
1085   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1086   uint16_t msize;
1087
1088   msize = ntohs (msg->size);
1089   if (sizeof (struct PongMessage) != msize)
1090   {
1091     GNUNET_break_op (0);
1092     return;
1093   }
1094   GNUNET_STATISTICS_update (GSC_stats,
1095                             gettext_noop ("# PONG messages received"), 1,
1096                             GNUNET_NO);
1097   switch (kx->status)
1098   {
1099   case KX_STATE_DOWN:
1100     GNUNET_STATISTICS_update (GSC_stats,
1101                               gettext_noop ("# PONG messages dropped (connection down)"), 1,
1102                               GNUNET_NO);
1103     return;
1104   case KX_STATE_KEY_SENT:
1105     GNUNET_STATISTICS_update (GSC_stats,
1106                               gettext_noop ("# PONG messages dropped (out of order)"), 1,
1107                               GNUNET_NO);
1108     return;
1109   case KX_STATE_KEY_RECEIVED:
1110     break;
1111   case KX_STATE_UP:
1112     break;
1113   case KX_STATE_REKEY_SENT:
1114     break;
1115   default:
1116     GNUNET_break (0);
1117     return;
1118   }
1119   m = (const struct PongMessage *) msg;
1120   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1121               "Core service receives `%s' response from `%4s'.\n", "PONG",
1122               GNUNET_i2s (&kx->peer));
1123   /* mark as garbage, just to be sure */
1124   memset (&t, 255, sizeof (t));
1125   derive_pong_iv (&iv, &kx->decrypt_key, m->iv_seed, kx->ping_challenge,
1126                   &GSC_my_identity);
1127   if (GNUNET_OK !=
1128       do_decrypt (kx, &iv, &m->challenge, &t.challenge,
1129                   sizeof (struct PongMessage) - ((void *) &m->challenge -
1130                                                  (void *) m)))
1131   {
1132     GNUNET_break_op (0);
1133     return;
1134   }
1135   GNUNET_STATISTICS_update (GSC_stats,
1136                             gettext_noop ("# PONG messages decrypted"), 1,
1137                             GNUNET_NO);
1138   if ((0 != memcmp (&t.target, &kx->peer, sizeof (struct GNUNET_PeerIdentity)))
1139       || (kx->ping_challenge != t.challenge))
1140   {
1141     /* PONG malformed */
1142     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1143                 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
1144                 "PONG", GNUNET_i2s (&kx->peer),
1145                 (unsigned int) kx->ping_challenge);
1146     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1147                 "Received malformed `%s' received from `%4s' with challenge %u\n",
1148                 "PONG", GNUNET_i2s (&t.target), (unsigned int) t.challenge);
1149     return;
1150   }
1151   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PONG from `%s'\n",
1152               GNUNET_i2s (&kx->peer));
1153   /* no need to resend key any longer */
1154   if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
1155   {
1156     GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1157     kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1158   }
1159   switch (kx->status)
1160   {
1161   case KX_STATE_DOWN:
1162     GNUNET_assert (0);           /* should be impossible */
1163     return;
1164   case KX_STATE_KEY_SENT:
1165     GNUNET_assert (0);           /* should be impossible */
1166     return;
1167   case KX_STATE_KEY_RECEIVED:
1168     GNUNET_STATISTICS_update (GSC_stats,
1169                               gettext_noop
1170                               ("# session keys confirmed via PONG"), 1,
1171                               GNUNET_NO);
1172     kx->status = KX_STATE_UP;
1173     GSC_SESSIONS_create (&kx->peer, kx);
1174     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
1175     update_timeout (kx);
1176     break;
1177   case KX_STATE_UP:
1178     GNUNET_STATISTICS_update (GSC_stats,
1179                               gettext_noop
1180                               ("# timeouts prevented via PONG"), 1,
1181                               GNUNET_NO);
1182     update_timeout (kx);
1183     break;
1184   case KX_STATE_REKEY_SENT:
1185     GNUNET_STATISTICS_update (GSC_stats,
1186                               gettext_noop
1187                               ("# rekey operations confirmed via PONG"), 1,
1188                               GNUNET_NO);
1189     kx->status = KX_STATE_UP;
1190     update_timeout (kx);
1191     break;
1192   default:
1193     GNUNET_break (0);
1194     break;
1195   }
1196 }
1197
1198
1199 /**
1200  * Send our key to the other peer.
1201  *
1202  * @param kx key exchange context
1203  */
1204 static void
1205 send_key (struct GSC_KeyExchangeInfo *kx)
1206 {
1207   GNUNET_assert (KX_STATE_DOWN != kx->status);
1208   if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
1209   {
1210      GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1211      kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1212   }
1213   /* always update sender status in SET KEY message */
1214   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1215               "Sending key to `%s' (my status: %d)\n",
1216               GNUNET_i2s (&kx->peer),
1217               kx->status);
1218   current_ekm.sender_status = htonl ((int32_t) (kx->status));
1219   GSC_NEIGHBOURS_transmit (&kx->peer, &current_ekm.header,
1220                            kx->set_key_retry_frequency);
1221   kx->retry_set_key_task =
1222       GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
1223                                     &set_key_retry_task, kx);
1224 }
1225
1226
1227 /**
1228  * Encrypt and transmit a message with the given payload.
1229  *
1230  * @param kx key exchange context
1231  * @param payload payload of the message
1232  * @param payload_size number of bytes in 'payload'
1233  */
1234 void
1235 GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
1236                              const void *payload, size_t payload_size)
1237 {
1238   size_t used = payload_size + sizeof (struct EncryptedMessage);
1239   char pbuf[used];              /* plaintext */
1240   char cbuf[used];              /* ciphertext */
1241   struct EncryptedMessage *em;  /* encrypted message */
1242   struct EncryptedMessage *ph;  /* plaintext header */
1243   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1244   struct GNUNET_CRYPTO_AuthKey auth_key;
1245
1246   ph = (struct EncryptedMessage *) pbuf;
1247   ph->iv_seed =
1248       htonl (GNUNET_CRYPTO_random_u32
1249              (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
1250   ph->sequence_number = htonl (++kx->last_sequence_number_sent);
1251   ph->reserved = 0;
1252   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1253   memcpy (&ph[1], payload, payload_size);
1254
1255   em = (struct EncryptedMessage *) cbuf;
1256   em->header.size = htons (used);
1257   em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1258   em->iv_seed = ph->iv_seed;
1259   derive_iv (&iv, &kx->encrypt_key, ph->iv_seed, &kx->peer);
1260   GNUNET_assert (GNUNET_OK ==
1261                  do_encrypt (kx, &iv, &ph->sequence_number,
1262                              &em->sequence_number,
1263                              used - ENCRYPTED_HEADER_SIZE));
1264   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Encrypted %u bytes for %s\n",
1265               used - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1266   derive_auth_key (&auth_key,
1267                    &kx->encrypt_key,
1268                    ph->iv_seed);
1269   GNUNET_CRYPTO_hmac (&auth_key, &em->sequence_number,
1270                       used - ENCRYPTED_HEADER_SIZE, &em->hmac);
1271   GSC_NEIGHBOURS_transmit (&kx->peer, &em->header,
1272                            GNUNET_TIME_UNIT_FOREVER_REL);
1273 }
1274
1275
1276 /**
1277  * Closure for #deliver_message()
1278  */
1279 struct DeliverMessageContext
1280 {
1281
1282   /**
1283    * Key exchange context.
1284    */
1285   struct GSC_KeyExchangeInfo *kx;
1286
1287   /**
1288    * Sender of the message.
1289    */
1290   const struct GNUNET_PeerIdentity *peer;
1291 };
1292
1293
1294 /**
1295  * We received an encrypted message.  Decrypt, validate and
1296  * pass on to the appropriate clients.
1297  *
1298  * @param kx key exchange context for encrypting the message
1299  * @param msg encrypted message
1300  */
1301 void
1302 GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *kx,
1303                                  const struct GNUNET_MessageHeader *msg)
1304 {
1305   const struct EncryptedMessage *m;
1306   struct EncryptedMessage *pt;  /* plaintext */
1307   struct GNUNET_HashCode ph;
1308   uint32_t snum;
1309   struct GNUNET_TIME_Absolute t;
1310   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1311   struct GNUNET_CRYPTO_AuthKey auth_key;
1312   struct DeliverMessageContext dmc;
1313   uint16_t size = ntohs (msg->size);
1314   char buf[size] GNUNET_ALIGN;
1315
1316   if (size <
1317       sizeof (struct EncryptedMessage) + sizeof (struct GNUNET_MessageHeader))
1318   {
1319     GNUNET_break_op (0);
1320     return;
1321   }
1322   m = (const struct EncryptedMessage *) msg;
1323   if (KX_STATE_UP != kx->status)
1324   {
1325     GNUNET_STATISTICS_update (GSC_stats,
1326                               gettext_noop
1327                               ("# DATA message dropped (out of order)"),
1328                               1, GNUNET_NO);
1329     return;
1330   }
1331   if (0 == GNUNET_TIME_absolute_get_remaining (kx->foreign_key_expires).rel_value_us)
1332   {
1333     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1334                 _("Session to peer `%s' went down due to key expiration (should not happen)\n"),
1335                 GNUNET_i2s (&kx->peer));
1336     GNUNET_STATISTICS_update (GSC_stats,
1337                               gettext_noop ("# sessions terminated by key expiration"),
1338                               1, GNUNET_NO);
1339     GSC_SESSIONS_end (&kx->peer);
1340     if (GNUNET_SCHEDULER_NO_TASK != kx->keep_alive_task)
1341     {
1342       GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1343       kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1344     }
1345     kx->status = KX_STATE_KEY_SENT;
1346     send_key (kx);
1347     return;
1348   }
1349
1350   /* validate hash */
1351   derive_auth_key (&auth_key, &kx->decrypt_key, m->iv_seed);
1352   GNUNET_CRYPTO_hmac (&auth_key, &m->sequence_number,
1353                       size - ENCRYPTED_HEADER_SIZE, &ph);
1354   if (0 != memcmp (&ph, &m->hmac, sizeof (struct GNUNET_HashCode)))
1355   {
1356     /* checksum failed */
1357     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1358                 "Failed checksum validation for a message from `%s'\n",
1359                 GNUNET_i2s (&kx->peer));
1360     return;
1361   }
1362   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
1363   /* decrypt */
1364   if (GNUNET_OK !=
1365       do_decrypt (kx, &iv, &m->sequence_number, &buf[ENCRYPTED_HEADER_SIZE],
1366                   size - ENCRYPTED_HEADER_SIZE))
1367     return;
1368   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1369               "Decrypted %u bytes from %s\n",
1370               size - ENCRYPTED_HEADER_SIZE,
1371               GNUNET_i2s (&kx->peer));
1372   pt = (struct EncryptedMessage *) buf;
1373
1374   /* validate sequence number */
1375   snum = ntohl (pt->sequence_number);
1376   if (kx->last_sequence_number_received == snum)
1377   {
1378     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1379                 "Received duplicate message, ignoring.\n");
1380     /* duplicate, ignore */
1381     GNUNET_STATISTICS_update (GSC_stats,
1382                               gettext_noop ("# bytes dropped (duplicates)"),
1383                               size, GNUNET_NO);
1384     return;
1385   }
1386   if ((kx->last_sequence_number_received > snum) &&
1387       (kx->last_sequence_number_received - snum > 32))
1388   {
1389     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1390                 "Received ancient out of sequence message, ignoring.\n");
1391     /* ancient out of sequence, ignore */
1392     GNUNET_STATISTICS_update (GSC_stats,
1393                               gettext_noop
1394                               ("# bytes dropped (out of sequence)"), size,
1395                               GNUNET_NO);
1396     return;
1397   }
1398   if (kx->last_sequence_number_received > snum)
1399   {
1400     unsigned int rotbit = 1 << (kx->last_sequence_number_received - snum - 1);
1401
1402     if ((kx->last_packets_bitmap & rotbit) != 0)
1403     {
1404       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1405                   "Received duplicate message, ignoring.\n");
1406       GNUNET_STATISTICS_update (GSC_stats,
1407                                 gettext_noop ("# bytes dropped (duplicates)"),
1408                                 size, GNUNET_NO);
1409       /* duplicate, ignore */
1410       return;
1411     }
1412     kx->last_packets_bitmap |= rotbit;
1413   }
1414   if (kx->last_sequence_number_received < snum)
1415   {
1416     unsigned int shift = (snum - kx->last_sequence_number_received);
1417
1418     if (shift >= 8 * sizeof (kx->last_packets_bitmap))
1419       kx->last_packets_bitmap = 0;
1420     else
1421       kx->last_packets_bitmap <<= shift;
1422     kx->last_sequence_number_received = snum;
1423   }
1424
1425   /* check timestamp */
1426   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
1427   if (GNUNET_TIME_absolute_get_duration (t).rel_value_us >
1428       MAX_MESSAGE_AGE.rel_value_us)
1429   {
1430     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1431                 "Message received far too old (%s). Content ignored.\n",
1432                 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (t),
1433                                                         GNUNET_YES));
1434     GNUNET_STATISTICS_update (GSC_stats,
1435                               gettext_noop
1436                               ("# bytes dropped (ancient message)"), size,
1437                               GNUNET_NO);
1438     return;
1439   }
1440
1441   /* process decrypted message(s) */
1442   update_timeout (kx);
1443   GNUNET_STATISTICS_update (GSC_stats,
1444                             gettext_noop ("# bytes of payload decrypted"),
1445                             size - sizeof (struct EncryptedMessage),
1446                             GNUNET_NO);
1447   dmc.kx = kx;
1448   dmc.peer = &kx->peer;
1449   if (GNUNET_OK !=
1450       GNUNET_SERVER_mst_receive (mst, &dmc,
1451                                  &buf[sizeof (struct EncryptedMessage)],
1452                                  size - sizeof (struct EncryptedMessage),
1453                                  GNUNET_YES,
1454                                  GNUNET_NO))
1455     GNUNET_break_op (0);
1456 }
1457
1458
1459 /**
1460  * Deliver P2P message to interested clients.
1461  * Invokes send twice, once for clients that want the full message, and once
1462  * for clients that only want the header
1463  *
1464  * @param cls always NULL
1465  * @param client who sent us the message (struct GSC_KeyExchangeInfo)
1466  * @param m the message
1467  */
1468 static int
1469 deliver_message (void *cls,
1470                  void *client,
1471                  const struct GNUNET_MessageHeader *m)
1472 {
1473   struct DeliverMessageContext *dmc = client;
1474
1475   if (KX_STATE_UP != dmc->kx->status)
1476   {
1477     GNUNET_STATISTICS_update (GSC_stats,
1478                               gettext_noop
1479                               ("# PAYLOAD dropped (out of order)"),
1480                               1, GNUNET_NO);
1481     return GNUNET_OK;
1482   }
1483   switch (ntohs (m->type))
1484   {
1485   case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP:
1486   case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP:
1487     GSC_SESSIONS_set_typemap (dmc->peer, m);
1488     return GNUNET_OK;
1489   default:
1490     GSC_CLIENTS_deliver_message (dmc->peer, m,
1491                                  ntohs (m->size),
1492                                  GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
1493     GSC_CLIENTS_deliver_message (dmc->peer, m,
1494                                  sizeof (struct GNUNET_MessageHeader),
1495                                  GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
1496   }
1497   return GNUNET_OK;
1498 }
1499
1500
1501 /**
1502  * Setup the message that links the ephemeral key to our persistent
1503  * public key and generate the appropriate signature.
1504  */
1505 static void
1506 sign_ephemeral_key ()
1507 {
1508   current_ekm.header.size = htons (sizeof (struct EphemeralKeyMessage));
1509   current_ekm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY);
1510   current_ekm.sender_status = 0; /* to be set later */
1511   current_ekm.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY);
1512   current_ekm.purpose.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
1513                                     sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1514                                     sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1515                                     sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
1516                                     sizeof (struct GNUNET_PeerIdentity));
1517   current_ekm.creation_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1518   if (GNUNET_YES ==
1519       GNUNET_CONFIGURATION_get_value_yesno (GSC_cfg,
1520                                             "core",
1521                                             "USE_EPHEMERAL_KEYS"))
1522   {
1523     current_ekm.expiration_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_add (REKEY_FREQUENCY,
1524                                                                                                                          REKEY_TOLERANCE)));
1525   }
1526   else
1527   {
1528     current_ekm.expiration_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_FOREVER_ABS);
1529   }
1530   GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key,
1531                                       &current_ekm.ephemeral_key);
1532   current_ekm.origin_identity = GSC_my_identity;
1533   GNUNET_assert (GNUNET_OK ==
1534                  GNUNET_CRYPTO_eddsa_sign (my_private_key,
1535                                          &current_ekm.purpose,
1536                                          &current_ekm.signature));
1537 }
1538
1539
1540 /**
1541  * Task run to trigger rekeying.
1542  *
1543  * @param cls closure, NULL
1544  * @param tc scheduler context
1545  */
1546 static void
1547 do_rekey (void *cls,
1548           const struct GNUNET_SCHEDULER_TaskContext *tc)
1549 {
1550   struct GSC_KeyExchangeInfo *pos;
1551
1552   rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY,
1553                                              &do_rekey,
1554                                              NULL);
1555   if (NULL != my_ephemeral_key)
1556     GNUNET_free (my_ephemeral_key);
1557   my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1558   GNUNET_assert (NULL != my_ephemeral_key);
1559   sign_ephemeral_key ();
1560   for (pos = kx_head; NULL != pos; pos = pos->next)
1561   {
1562     if (KX_STATE_UP == pos->status)
1563     {
1564       pos->status = KX_STATE_REKEY_SENT;
1565       derive_session_keys (pos);
1566     }
1567     if (KX_STATE_DOWN == pos->status)
1568     {
1569       pos->status = KX_STATE_KEY_SENT;
1570     }
1571     send_key (pos);
1572   }
1573 }
1574
1575
1576 /**
1577  * Initialize KX subsystem.
1578  *
1579  * @param pk private key to use for the peer
1580  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1581  */
1582 int
1583 GSC_KX_init (struct GNUNET_CRYPTO_EddsaPrivateKey *pk)
1584 {
1585   my_private_key = pk;
1586   GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
1587                                                   &GSC_my_identity.public_key);
1588   my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1589   if (NULL == my_ephemeral_key)
1590   {
1591     GNUNET_break (0);
1592     GNUNET_free (my_private_key);
1593     my_private_key = NULL;
1594     return GNUNET_SYSERR;
1595   }
1596   sign_ephemeral_key ();
1597   rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY,
1598                                              &do_rekey,
1599                                              NULL);
1600   mst = GNUNET_SERVER_mst_create (&deliver_message, NULL);
1601   return GNUNET_OK;
1602 }
1603
1604
1605 /**
1606  * Shutdown KX subsystem.
1607  */
1608 void
1609 GSC_KX_done ()
1610 {
1611   if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1612   {
1613     GNUNET_SCHEDULER_cancel (rekey_task);
1614     rekey_task = GNUNET_SCHEDULER_NO_TASK;
1615   }
1616   if (NULL != my_ephemeral_key)
1617   {
1618     GNUNET_free (my_ephemeral_key);
1619     my_ephemeral_key = NULL;
1620   }
1621   if (NULL != my_private_key)
1622   {
1623     GNUNET_free (my_private_key);
1624     my_private_key = NULL;
1625   }
1626   if (NULL != mst)
1627   {
1628     GNUNET_SERVER_mst_destroy (mst);
1629     mst = NULL;
1630   }
1631 }
1632
1633 /* end of gnunet-service-core_kx.c */