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