splitting 'struct GNUNET_CRYPTO_EccPublicKey' into one struct for signing and another...
[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_EccPublicSignKey ephemeral_key;  
115
116   /**
117    * Public key of the signing peer (persistent version, not the ephemeral public key).
118    */
119   struct GNUNET_CRYPTO_EccPublicSignKey origin_public_key;
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_AesSessionKey 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_AesSessionKey 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 public key.
394  */
395 static struct GNUNET_CRYPTO_EccPublicSignKey my_public_key;
396
397 /**
398  * Our message stream tokenizer (for encrypted payload).
399  */
400 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
401
402 /**
403  * DLL head.
404  */
405 static struct GSC_KeyExchangeInfo *kx_head;
406
407 /**
408  * DLL tail.
409  */
410 static struct GSC_KeyExchangeInfo *kx_tail;
411
412 /**
413  * Task scheduled for periodic re-generation (and thus rekeying) of our
414  * ephemeral key.
415  */ 
416 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
417
418
419 /**
420  * Derive an authentication key from "set key" information
421  *
422  * @param akey authentication key to derive
423  * @param skey session key to use
424  * @param seed seed to use
425  */
426 static void
427 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
428                  const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed)
429 {
430   static const char ctx[] = "authentication key";
431
432   GNUNET_CRYPTO_hmac_derive_key (akey, skey, &seed, sizeof (seed), &skey->key,
433                                  sizeof (skey->key), ctx,
434                                  sizeof (ctx), NULL);
435 }
436
437
438 /**
439  * Derive an IV from packet information
440  *
441  * @param iv initialization vector to initialize
442  * @param skey session key to use
443  * @param seed seed to use
444  * @param identity identity of the other peer to use
445  */
446 static void
447 derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
448            const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
449            const struct GNUNET_PeerIdentity *identity)
450 {
451   static const char ctx[] = "initialization vector";
452
453   GNUNET_CRYPTO_aes_derive_iv (iv, skey, &seed, sizeof (seed),
454                                &identity->hashPubKey.bits,
455                                sizeof (identity->hashPubKey.bits), ctx,
456                                sizeof (ctx), NULL);
457 }
458
459
460 /**
461  * Derive an IV from pong packet information
462  *
463  * @param iv initialization vector to initialize
464  * @param skey session key to use
465  * @param seed seed to use
466  * @param challenge nonce to use
467  * @param identity identity of the other peer to use
468  */
469 static void
470 derive_pong_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
471                 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
472                 uint32_t challenge, const struct GNUNET_PeerIdentity *identity)
473 {
474   static const char ctx[] = "pong initialization vector";
475
476   GNUNET_CRYPTO_aes_derive_iv (iv, skey, &seed, sizeof (seed),
477                                &identity->hashPubKey.bits,
478                                sizeof (identity->hashPubKey.bits), &challenge,
479                                sizeof (challenge), ctx, sizeof (ctx), NULL);
480 }
481
482
483 /**
484  * Derive an AES key from key material
485  *
486  * @param sender peer identity of the sender
487  * @param receiver peer identity of the sender
488  * @param key_material high entropy key material to use
489  * @param skey set to derived session key 
490  */
491 static void
492 derive_aes_key (const struct GNUNET_PeerIdentity *sender,
493                 const struct GNUNET_PeerIdentity *receiver,
494                 const struct GNUNET_HashCode *key_material,
495                 struct GNUNET_CRYPTO_AesSessionKey *skey)
496 {
497   static const char ctx[] = "aes key generation vector";
498
499   GNUNET_CRYPTO_kdf (skey, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
500                      ctx, sizeof (ctx),
501                      key_material, sizeof (struct GNUNET_HashCode),
502                      sender, sizeof (struct GNUNET_PeerIdentity),
503                      receiver, sizeof (struct GNUNET_PeerIdentity),
504                      NULL);
505 }
506
507
508 /**
509  * Encrypt size bytes from in and write the result to out.  Use the
510  * key for outbound traffic of the given neighbour.
511  *
512  * @param kx key information context
513  * @param iv initialization vector to use
514  * @param in ciphertext
515  * @param out plaintext
516  * @param size size of in/out
517  * @return GNUNET_OK on success
518  */
519 static int
520 do_encrypt (struct GSC_KeyExchangeInfo *kx,
521             const struct GNUNET_CRYPTO_AesInitializationVector *iv,
522             const void *in, void *out, size_t size)
523 {
524   if (size != (uint16_t) size)
525   {
526     GNUNET_break (0);
527     return GNUNET_NO;
528   }
529   GNUNET_assert (size ==
530                  GNUNET_CRYPTO_aes_encrypt (in, (uint16_t) size,
531                                             &kx->encrypt_key, iv, out));
532   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes encrypted"), size,
533                             GNUNET_NO);
534   /* the following is too sensitive to write to log files by accident,
535      so we require manual intervention to get this one... */
536 #if 0
537   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
538               "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
539               (unsigned int) size, GNUNET_i2s (&kx->peer),
540               (unsigned int) kx->encrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
541                                                                            sizeof
542                                                                            (iv)));
543 #endif
544   return GNUNET_OK;
545 }
546
547
548 /**
549  * Decrypt size bytes from in and write the result to out.  Use the
550  * key for inbound traffic of the given neighbour.  This function does
551  * NOT do any integrity-checks on the result.
552  *
553  * @param kx key information context
554  * @param iv initialization vector to use
555  * @param in ciphertext
556  * @param out plaintext
557  * @param size size of in/out
558  * @return GNUNET_OK on success
559  */
560 static int
561 do_decrypt (struct GSC_KeyExchangeInfo *kx,
562             const struct GNUNET_CRYPTO_AesInitializationVector *iv,
563             const void *in, void *out, size_t size)
564 {
565   if (size != (uint16_t) size)
566   {
567     GNUNET_break (0);
568     return GNUNET_NO;
569   }
570   if ( (kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP) &&
571        (kx->status != KX_STATE_REKEY_SENT) )
572   {
573     GNUNET_break_op (0);
574     return GNUNET_SYSERR;
575   }
576   if (size !=
577       GNUNET_CRYPTO_aes_decrypt (in, (uint16_t) size, &kx->decrypt_key, iv,
578                                  out))
579   {
580     GNUNET_break (0);
581     return GNUNET_SYSERR;
582   }
583   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes decrypted"), size,
584                             GNUNET_NO);
585   /* the following is too sensitive to write to log files by accident,
586      so we require manual intervention to get this one... */
587 #if 0
588   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
589               "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
590               (unsigned int) size, GNUNET_i2s (&kx->peer),
591               (unsigned int) kx->decrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
592                                                                            sizeof
593                                                                            (*iv)));
594 #endif
595   return GNUNET_OK;
596 }
597
598
599 /**
600  * Send our key (and encrypted PING) to the other peer.
601  *
602  * @param kx key exchange context
603  */
604 static void
605 send_key (struct GSC_KeyExchangeInfo *kx);
606
607
608 /**
609  * Task that will retry "send_key" if our previous attempt failed.
610  *
611  * @param cls our 'struct GSC_KeyExchangeInfo'
612  * @param tc scheduler context
613  */
614 static void
615 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
616 {
617   struct GSC_KeyExchangeInfo *kx = cls;
618
619   kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
620   kx->set_key_retry_frequency = GNUNET_TIME_STD_BACKOFF (kx->set_key_retry_frequency);
621   GNUNET_assert (KX_STATE_DOWN != kx->status);
622   send_key (kx);
623 }
624
625
626 /**
627  * Create a fresh PING message for transmission to the other peer.
628  *
629  * @param kx key exchange context to create PING for
630  */
631 static void
632 setup_fresh_ping (struct GSC_KeyExchangeInfo *kx)
633 {
634   struct PingMessage pp;
635   struct PingMessage *pm;
636   struct GNUNET_CRYPTO_AesInitializationVector iv;
637
638   pm = &kx->ping;
639   pm->header.size = htons (sizeof (struct PingMessage));
640   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
641   pm->iv_seed =
642       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
643   derive_iv (&iv, &kx->encrypt_key, pm->iv_seed, &kx->peer);
644   pp.challenge = kx->ping_challenge;
645   pp.target = kx->peer;
646   do_encrypt (kx, &iv, &pp.target, &pm->target,
647               sizeof (struct PingMessage) - ((void *) &pm->target -
648                                              (void *) pm));
649 }
650
651
652 /**
653  * Start the key exchange with the given peer.
654  *
655  * @param pid identity of the peer to do a key exchange with
656  * @return key exchange information context
657  */
658 struct GSC_KeyExchangeInfo *
659 GSC_KX_start (const struct GNUNET_PeerIdentity *pid)
660 {
661   struct GSC_KeyExchangeInfo *kx;
662
663   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
664               "Initiating key exchange with `%s'\n",
665               GNUNET_i2s (pid));
666   GNUNET_STATISTICS_update (GSC_stats,
667                             gettext_noop ("# key exchanges initiated"), 1,
668                             GNUNET_NO);
669   kx = GNUNET_malloc (sizeof (struct GSC_KeyExchangeInfo));
670   kx->peer = *pid;
671   kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
672   GNUNET_CONTAINER_DLL_insert (kx_head,
673                                kx_tail,
674                                kx);
675   if (0 < GNUNET_CRYPTO_hash_cmp (&pid->hashPubKey,
676                                   &GSC_my_identity.hashPubKey))
677   {
678     /* peer with "lower" identity starts KX, otherwise we typically end up
679        with both peers starting the exchange and transmit the 'set key' 
680        message twice */
681     kx->status = KX_STATE_KEY_SENT;
682     send_key (kx);
683   }
684   return kx;
685 }
686
687
688 /**
689  * Stop key exchange with the given peer.  Clean up key material.
690  *
691  * @param kx key exchange to stop
692  */
693 void
694 GSC_KX_stop (struct GSC_KeyExchangeInfo *kx)
695 {
696   GSC_SESSIONS_end (&kx->peer);
697   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# key exchanges stopped"),
698                             1, GNUNET_NO);
699   if (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
700   {
701     GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
702     kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
703   }
704   if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
705   {
706     GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
707     kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
708   }
709   GNUNET_CONTAINER_DLL_remove (kx_head,
710                                kx_tail,
711                                kx);
712   GNUNET_free (kx);
713 }
714
715
716 /**
717  * Send our PING to the other peer.
718  *
719  * @param kx key exchange context
720  */
721 static void
722 send_ping (struct GSC_KeyExchangeInfo *kx)
723 {
724   GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
725                            MIN_PING_FREQUENCY);
726 }
727
728 /**
729  * We received a SET_KEY message.  Validate and update
730  * our key material and status.
731  *
732  * @param kx key exchange status for the corresponding peer
733  * @param msg the set key message we received
734  */
735 void
736 GSC_KX_handle_ephemeral_key (struct GSC_KeyExchangeInfo *kx,
737                              const struct GNUNET_MessageHeader *msg)
738 {
739   const struct EphemeralKeyMessage *m;
740   struct GNUNET_TIME_Absolute start_t;
741   struct GNUNET_TIME_Absolute end_t;
742   struct GNUNET_TIME_Absolute now;
743   struct GNUNET_PeerIdentity signer_id;
744   enum KxStateMachine sender_status;  
745   uint16_t size;
746   struct GNUNET_HashCode key_material;
747   
748   size = ntohs (msg->size);
749   if (sizeof (struct EphemeralKeyMessage) != size)
750   {
751     GNUNET_break_op (0);
752     return;
753   }
754   m = (const struct EphemeralKeyMessage *) msg;
755   end_t = GNUNET_TIME_absolute_ntoh (m->expiration_time);
756   if ( ( (KX_STATE_KEY_RECEIVED == kx->status) ||
757          (KX_STATE_UP == kx->status) ||
758          (KX_STATE_REKEY_SENT == kx->status) ) &&       
759        (end_t.abs_value_us <= kx->foreign_key_expires.abs_value_us) )
760   {
761     GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# old ephemeral keys ignored"),
762                               1, GNUNET_NO);
763     return;
764   }
765   start_t = GNUNET_TIME_absolute_ntoh (m->creation_time);
766
767   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# ephemeral keys received"),
768                             1, GNUNET_NO);
769
770   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
771               "Core service receives `%s' request from `%4s'.\n", "EPHEMERAL_KEY",
772               GNUNET_i2s (&kx->peer));
773   GNUNET_CRYPTO_hash (&m->origin_public_key,
774                       sizeof (struct GNUNET_CRYPTO_EccPublicSignKey),
775                       &signer_id.hashPubKey);
776   if (0 !=
777       memcmp (&signer_id, &kx->peer,
778               sizeof (struct GNUNET_PeerIdentity)))
779   {    
780     GNUNET_break_op (0);
781     return;
782   }
783   if ((ntohl (m->purpose.size) !=
784        sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
785        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
786        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
787        sizeof (struct GNUNET_CRYPTO_EccPublicSignKey) +
788        sizeof (struct GNUNET_CRYPTO_EccPublicSignKey)) ||
789       (GNUNET_OK !=
790        GNUNET_CRYPTO_ecc_verify (GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY,
791                                  &m->purpose,
792                                  &m->signature, &m->origin_public_key)))
793   {
794     /* invalid signature */
795     GNUNET_break_op (0);
796     return;
797   }
798   now = GNUNET_TIME_absolute_get ();
799   if ( (end_t.abs_value_us < GNUNET_TIME_absolute_subtract (now, REKEY_TOLERANCE).abs_value_us) ||
800        (start_t.abs_value_us > GNUNET_TIME_absolute_add (now, REKEY_TOLERANCE).abs_value_us) )
801   {
802     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
803                 _("Ephemeral key message from peer `%s' rejected as its validity range does not match our system time (%llu not in [%llu,%llu]).\n"),
804                 GNUNET_i2s (&kx->peer),
805                 now.abs_value_us,
806                 start_t.abs_value_us,
807                 end_t.abs_value_us);
808     return;
809   }
810   if (GNUNET_OK !=
811       GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
812                               &m->ephemeral_key,                              
813                               &key_material))
814   {
815     GNUNET_break (0);
816     return;
817   }
818   GNUNET_STATISTICS_update (GSC_stats,
819                             gettext_noop ("# EPHEMERAL_KEY messages decrypted"), 1,
820                             GNUNET_NO);
821   derive_aes_key (&GSC_my_identity,
822                   &kx->peer,
823                   &key_material,
824                   &kx->encrypt_key);
825   derive_aes_key (&kx->peer,
826                   &GSC_my_identity,
827                   &key_material,
828                   &kx->decrypt_key);
829   /* fresh key, reset sequence numbers */
830   kx->last_sequence_number_received = 0;
831   kx->last_packets_bitmap = 0;
832   kx->foreign_key_expires = end_t;
833   setup_fresh_ping (kx);
834
835   /* check if we still need to send the sender our key */
836   sender_status = (enum KxStateMachine) ntohl (m->sender_status);  
837   switch (sender_status)
838   {
839   case KX_STATE_DOWN:
840     GNUNET_break_op (0);
841     break;
842   case KX_STATE_KEY_SENT:
843     /* fine, need to send our key after updating our status, see below */
844     break;
845   case KX_STATE_KEY_RECEIVED:
846   case KX_STATE_UP: 
847   case KX_STATE_REKEY_SENT:
848     /* other peer already got our key */
849     break;
850   default:
851     GNUNET_break (0);
852     break;
853   }
854   /* check if we need to confirm everything is fine via PING + PONG */
855   switch (kx->status)
856   {
857   case KX_STATE_DOWN:
858     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
859     kx->status = KX_STATE_KEY_RECEIVED;
860     if (KX_STATE_KEY_SENT == sender_status)
861       send_key (kx);
862     send_ping (kx);
863     break;
864   case KX_STATE_KEY_SENT:
865     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
866     kx->status = KX_STATE_KEY_RECEIVED;
867     if (KX_STATE_KEY_SENT == sender_status)
868       send_key (kx);
869     send_ping (kx);
870     break;
871   case KX_STATE_KEY_RECEIVED:
872     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
873     if (KX_STATE_KEY_SENT == sender_status)
874       send_key (kx);
875     send_ping (kx);
876     break;
877   case KX_STATE_UP: 
878     kx->status = KX_STATE_REKEY_SENT;
879     if (KX_STATE_KEY_SENT == sender_status)
880       send_key (kx);
881     /* we got a new key, need to reconfirm! */
882     send_ping (kx);
883     break;
884   case KX_STATE_REKEY_SENT:
885     if (KX_STATE_KEY_SENT == sender_status)
886       send_key (kx);
887     /* we got a new key, need to reconfirm! */
888     send_ping (kx);
889     break;
890   default:
891     GNUNET_break (0);
892     break;
893   }
894 }
895
896
897 /**
898  * We received a PING message.  Validate and transmit
899  * a PONG message.
900  *
901  * @param kx key exchange status for the corresponding peer
902  * @param msg the encrypted PING message itself
903  */
904 void
905 GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *kx,
906                     const struct GNUNET_MessageHeader *msg)
907 {
908   const struct PingMessage *m;
909   struct PingMessage t;
910   struct PongMessage tx;
911   struct PongMessage tp;
912   struct GNUNET_CRYPTO_AesInitializationVector iv;
913   uint16_t msize;
914
915   msize = ntohs (msg->size);
916   if (msize != sizeof (struct PingMessage))
917   {
918     GNUNET_break_op (0);
919     return;
920   }
921   GNUNET_STATISTICS_update (GSC_stats,
922                             gettext_noop ("# PING messages received"), 1,
923                             GNUNET_NO);
924   if ( (kx->status != KX_STATE_KEY_RECEIVED) && 
925        (kx->status != KX_STATE_UP) &&
926        (kx->status != KX_STATE_REKEY_SENT))
927   {
928     /* ignore */
929     GNUNET_STATISTICS_update (GSC_stats,
930                               gettext_noop ("# PING messages dropped (out of order)"), 1,
931                               GNUNET_NO);
932     return;
933   }
934   m = (const struct PingMessage *) msg;
935   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
936               "Core service receives `%s' request from `%4s'.\n", "PING",
937               GNUNET_i2s (&kx->peer));
938   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
939   if (GNUNET_OK !=
940       do_decrypt (kx, &iv, &m->target, &t.target,
941                   sizeof (struct PingMessage) - ((void *) &m->target -
942                                                  (void *) m)))
943   {
944     GNUNET_break_op (0);
945     return;
946   }
947   if (0 !=
948       memcmp (&t.target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
949   {
950     char sender[9];
951     char peer[9];
952
953     GNUNET_snprintf (sender, sizeof (sender), "%8s", GNUNET_i2s (&kx->peer));
954     GNUNET_snprintf (peer, sizeof (peer), "%8s", GNUNET_i2s (&t.target));
955     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
956                 _
957                 ("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
958                 sender, GNUNET_i2s (&GSC_my_identity), peer);
959     GNUNET_break_op (0);
960     return;
961   }
962   /* construct PONG */
963   tx.reserved = 0;
964   tx.challenge = t.challenge;
965   tx.target = t.target;
966   tp.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
967   tp.header.size = htons (sizeof (struct PongMessage));
968   tp.iv_seed =
969       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
970   derive_pong_iv (&iv, &kx->encrypt_key, tp.iv_seed, t.challenge, &kx->peer);
971   do_encrypt (kx, &iv, &tx.challenge, &tp.challenge,
972               sizeof (struct PongMessage) - ((void *) &tp.challenge -
973                                              (void *) &tp));
974   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages created"),
975                             1, GNUNET_NO);
976   GSC_NEIGHBOURS_transmit (&kx->peer, &tp.header,
977                            GNUNET_TIME_UNIT_FOREVER_REL /* FIXME: timeout */ );
978 }
979
980
981 /**
982  * Task triggered when a neighbour entry is about to time out
983  * (and we should prevent this by sending a PING).
984  *
985  * @param cls the 'struct GSC_KeyExchangeInfo'
986  * @param tc scheduler context (not used)
987  */
988 static void
989 send_keep_alive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
990 {
991   struct GSC_KeyExchangeInfo *kx = cls;
992   struct GNUNET_TIME_Relative retry;
993   struct GNUNET_TIME_Relative left;
994
995   kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
996   left = GNUNET_TIME_absolute_get_remaining (kx->timeout);
997   if (0 == left.rel_value_us)
998   {
999     GNUNET_STATISTICS_update (GSC_stats,
1000                               gettext_noop ("# sessions terminated by timeout"),
1001                               1, GNUNET_NO);
1002     GSC_SESSIONS_end (&kx->peer);
1003     kx->status = KX_STATE_KEY_SENT;
1004     send_key (kx);
1005     return;
1006   }
1007   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending KEEPALIVE to `%s'\n",
1008               GNUNET_i2s (&kx->peer));
1009   GNUNET_STATISTICS_update (GSC_stats,
1010                             gettext_noop ("# keepalive messages sent"), 1,
1011                             GNUNET_NO);
1012   setup_fresh_ping (kx);
1013   GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
1014                            kx->set_key_retry_frequency);
1015   retry =
1016       GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1017                                 MIN_PING_FREQUENCY);
1018   kx->keep_alive_task =
1019       GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx);
1020 }
1021
1022
1023 /**
1024  * We've seen a valid message from the other peer.
1025  * Update the time when the session would time out
1026  * and delay sending our keep alive message further.
1027  *
1028  * @param kx key exchange where we saw activity
1029  */
1030 static void
1031 update_timeout (struct GSC_KeyExchangeInfo *kx)
1032 {
1033   kx->timeout =
1034       GNUNET_TIME_relative_to_absolute
1035       (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1036   if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1037     GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1038   kx->keep_alive_task =
1039       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
1040                                     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1041                                      2), &send_keep_alive, kx);
1042 }
1043
1044
1045 /**
1046  * We received a PONG message.  Validate and update our status.
1047  *
1048  * @param kx key exchange context for the the PONG
1049  * @param msg the encrypted PONG message itself
1050  */
1051 void
1052 GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx,
1053                     const struct GNUNET_MessageHeader *msg)
1054 {
1055   const struct PongMessage *m;
1056   struct PongMessage t;
1057   struct GNUNET_CRYPTO_AesInitializationVector iv;
1058   uint16_t msize;
1059
1060   msize = ntohs (msg->size);
1061   if (sizeof (struct PongMessage) != msize)
1062   {
1063     GNUNET_break_op (0);
1064     return;
1065   }
1066   GNUNET_STATISTICS_update (GSC_stats,
1067                             gettext_noop ("# PONG messages received"), 1,
1068                             GNUNET_NO);
1069   switch (kx->status)
1070   {
1071   case KX_STATE_DOWN:
1072     GNUNET_STATISTICS_update (GSC_stats,
1073                               gettext_noop ("# PONG messages dropped (connection down)"), 1,
1074                               GNUNET_NO);
1075     return;
1076   case KX_STATE_KEY_SENT:
1077     GNUNET_STATISTICS_update (GSC_stats,
1078                               gettext_noop ("# PONG messages dropped (out of order)"), 1,
1079                               GNUNET_NO);
1080     return;
1081   case KX_STATE_KEY_RECEIVED:
1082     break;
1083   case KX_STATE_UP:
1084     break;
1085   case KX_STATE_REKEY_SENT:
1086     break;
1087   default:
1088     GNUNET_break (0);
1089     return;
1090   }
1091   m = (const struct PongMessage *) msg;
1092   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1093               "Core service receives `%s' response from `%4s'.\n", "PONG",
1094               GNUNET_i2s (&kx->peer));
1095   /* mark as garbage, just to be sure */
1096   memset (&t, 255, sizeof (t));
1097   derive_pong_iv (&iv, &kx->decrypt_key, m->iv_seed, kx->ping_challenge,
1098                   &GSC_my_identity);
1099   if (GNUNET_OK !=
1100       do_decrypt (kx, &iv, &m->challenge, &t.challenge,
1101                   sizeof (struct PongMessage) - ((void *) &m->challenge -
1102                                                  (void *) m)))
1103   {
1104     GNUNET_break_op (0);
1105     return;
1106   }
1107   GNUNET_STATISTICS_update (GSC_stats,
1108                             gettext_noop ("# PONG messages decrypted"), 1,
1109                             GNUNET_NO);
1110   if ((0 != memcmp (&t.target, &kx->peer, sizeof (struct GNUNET_PeerIdentity)))
1111       || (kx->ping_challenge != t.challenge))
1112   {
1113     /* PONG malformed */
1114     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1115                 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
1116                 "PONG", GNUNET_i2s (&kx->peer),
1117                 (unsigned int) kx->ping_challenge);
1118     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1119                 "Received malformed `%s' received from `%4s' with challenge %u\n",
1120                 "PONG", GNUNET_i2s (&t.target), (unsigned int) t.challenge);
1121     return;
1122   }
1123   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PONG from `%s'\n",
1124               GNUNET_i2s (&kx->peer));
1125   /* no need to resend key any longer */
1126   if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
1127   {
1128     GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1129     kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1130   }  
1131   switch (kx->status)
1132   {
1133   case KX_STATE_DOWN:
1134     GNUNET_assert (0);           /* should be impossible */
1135     return;
1136   case KX_STATE_KEY_SENT:
1137     GNUNET_assert (0);           /* should be impossible */
1138     return;
1139   case KX_STATE_KEY_RECEIVED:
1140     GNUNET_STATISTICS_update (GSC_stats,
1141                               gettext_noop
1142                               ("# session keys confirmed via PONG"), 1,
1143                               GNUNET_NO);
1144     kx->status = KX_STATE_UP;
1145     GSC_SESSIONS_create (&kx->peer, kx);
1146     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
1147     update_timeout (kx);
1148     break;
1149   case KX_STATE_UP:
1150     GNUNET_STATISTICS_update (GSC_stats,
1151                               gettext_noop
1152                               ("# timeouts prevented via PONG"), 1,
1153                               GNUNET_NO);
1154     update_timeout (kx);
1155     break;
1156   case KX_STATE_REKEY_SENT:
1157     GNUNET_STATISTICS_update (GSC_stats,
1158                               gettext_noop
1159                               ("# rekey operations confirmed via PONG"), 1,
1160                               GNUNET_NO);
1161     kx->status = KX_STATE_UP;
1162     update_timeout (kx);
1163     break;
1164   default:
1165     GNUNET_break (0);
1166     break;
1167   }
1168 }
1169
1170
1171 /**
1172  * Send our key to the other peer.
1173  *
1174  * @param kx key exchange context
1175  */
1176 static void
1177 send_key (struct GSC_KeyExchangeInfo *kx)
1178 {
1179   GNUNET_assert (KX_STATE_DOWN != kx->status);
1180   if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
1181   {
1182      GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1183      kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1184   }
1185   /* always update sender status in SET KEY message */
1186   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1187               "Sending key to `%s' (my status: %d)\n",
1188               GNUNET_i2s (&kx->peer),
1189               kx->status);
1190   current_ekm.sender_status = htonl ((int32_t) (kx->status));  
1191   GSC_NEIGHBOURS_transmit (&kx->peer, &current_ekm.header,
1192                            kx->set_key_retry_frequency);
1193   kx->retry_set_key_task =
1194       GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
1195                                     &set_key_retry_task, kx);
1196 }
1197
1198
1199 /**
1200  * Encrypt and transmit a message with the given payload.
1201  *
1202  * @param kx key exchange context
1203  * @param payload payload of the message
1204  * @param payload_size number of bytes in 'payload'
1205  */
1206 void
1207 GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
1208                              const void *payload, size_t payload_size)
1209 {
1210   size_t used = payload_size + sizeof (struct EncryptedMessage);
1211   char pbuf[used];              /* plaintext */
1212   char cbuf[used];              /* ciphertext */
1213   struct EncryptedMessage *em;  /* encrypted message */
1214   struct EncryptedMessage *ph;  /* plaintext header */
1215   struct GNUNET_CRYPTO_AesInitializationVector iv;
1216   struct GNUNET_CRYPTO_AuthKey auth_key;
1217
1218   ph = (struct EncryptedMessage *) pbuf;
1219   ph->iv_seed =
1220       htonl (GNUNET_CRYPTO_random_u32
1221              (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
1222   ph->sequence_number = htonl (++kx->last_sequence_number_sent);
1223   ph->reserved = 0;
1224   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1225   memcpy (&ph[1], payload, payload_size);
1226
1227   em = (struct EncryptedMessage *) cbuf;
1228   em->header.size = htons (used);
1229   em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1230   em->iv_seed = ph->iv_seed;
1231   derive_iv (&iv, &kx->encrypt_key, ph->iv_seed, &kx->peer);
1232   GNUNET_assert (GNUNET_OK ==
1233                  do_encrypt (kx, &iv, &ph->sequence_number,
1234                              &em->sequence_number,
1235                              used - ENCRYPTED_HEADER_SIZE));
1236   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Encrypted %u bytes for %s\n",
1237               used - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1238   derive_auth_key (&auth_key, 
1239                    &kx->encrypt_key, 
1240                    ph->iv_seed);
1241   GNUNET_CRYPTO_hmac (&auth_key, &em->sequence_number,
1242                       used - ENCRYPTED_HEADER_SIZE, &em->hmac);
1243   GSC_NEIGHBOURS_transmit (&kx->peer, &em->header,
1244                            GNUNET_TIME_UNIT_FOREVER_REL);
1245 }
1246
1247
1248 /**
1249  * Closure for 'deliver_message'
1250  */
1251 struct DeliverMessageContext
1252 {
1253
1254   /**
1255    * Key exchange context.
1256    */
1257   struct GSC_KeyExchangeInfo *kx;
1258
1259   /**
1260    * Sender of the message.
1261    */
1262   const struct GNUNET_PeerIdentity *peer;
1263 };
1264
1265
1266 /**
1267  * We received an encrypted message.  Decrypt, validate and
1268  * pass on to the appropriate clients.
1269  *
1270  * @param kx key exchange context for encrypting the message
1271  * @param msg encrypted message
1272  */
1273 void
1274 GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *kx,
1275                                  const struct GNUNET_MessageHeader *msg)
1276 {
1277   const struct EncryptedMessage *m;
1278   struct EncryptedMessage *pt;  /* plaintext */
1279   struct GNUNET_HashCode ph;
1280   uint32_t snum;
1281   struct GNUNET_TIME_Absolute t;
1282   struct GNUNET_CRYPTO_AesInitializationVector iv;
1283   struct GNUNET_CRYPTO_AuthKey auth_key;
1284   struct DeliverMessageContext dmc;
1285   uint16_t size = ntohs (msg->size);
1286   char buf[size] GNUNET_ALIGN;
1287
1288   if (size <
1289       sizeof (struct EncryptedMessage) + sizeof (struct GNUNET_MessageHeader))
1290   {
1291     GNUNET_break_op (0);
1292     return;
1293   }
1294   m = (const struct EncryptedMessage *) msg;
1295   if (kx->status != KX_STATE_UP)
1296   {
1297     GNUNET_STATISTICS_update (GSC_stats,
1298                               gettext_noop
1299                               ("# DATA message dropped (out of order)"),
1300                               1, GNUNET_NO);
1301     return;
1302   }
1303   if (0 == GNUNET_TIME_absolute_get_remaining (kx->foreign_key_expires).rel_value_us)
1304   {
1305     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1306                 _("Session to peer `%s' went down due to key expiration (should not happen)\n"),
1307                 GNUNET_i2s (&kx->peer));
1308     GNUNET_STATISTICS_update (GSC_stats,
1309                               gettext_noop ("# sessions terminated by key expiration"),
1310                               1, GNUNET_NO);
1311     GSC_SESSIONS_end (&kx->peer);
1312     if (GNUNET_SCHEDULER_NO_TASK != kx->keep_alive_task)
1313     {
1314       GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1315       kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1316     }
1317     kx->status = KX_STATE_KEY_SENT;
1318     send_key (kx);
1319     return;
1320   }
1321
1322   /* validate hash */
1323   derive_auth_key (&auth_key, &kx->decrypt_key, m->iv_seed);
1324   GNUNET_CRYPTO_hmac (&auth_key, &m->sequence_number,
1325                       size - ENCRYPTED_HEADER_SIZE, &ph);
1326   if (0 != memcmp (&ph, &m->hmac, sizeof (struct GNUNET_HashCode)))
1327   {
1328     /* checksum failed */
1329     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1330                 "Failed checksum validation for a message from `%s'\n", 
1331                 GNUNET_i2s (&kx->peer));
1332     return;
1333   }
1334   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
1335   /* decrypt */
1336   if (GNUNET_OK !=
1337       do_decrypt (kx, &iv, &m->sequence_number, &buf[ENCRYPTED_HEADER_SIZE],
1338                   size - ENCRYPTED_HEADER_SIZE))
1339     return;
1340   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypted %u bytes from %s\n",
1341               size - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1342   pt = (struct EncryptedMessage *) buf;
1343
1344   /* validate sequence number */
1345   snum = ntohl (pt->sequence_number);
1346   if (kx->last_sequence_number_received == snum)
1347   {
1348     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1349                 "Received duplicate message, ignoring.\n");
1350     /* duplicate, ignore */
1351     GNUNET_STATISTICS_update (GSC_stats,
1352                               gettext_noop ("# bytes dropped (duplicates)"),
1353                               size, GNUNET_NO);
1354     return;
1355   }
1356   if ((kx->last_sequence_number_received > snum) &&
1357       (kx->last_sequence_number_received - snum > 32))
1358   {
1359     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1360                 "Received ancient out of sequence message, ignoring.\n");
1361     /* ancient out of sequence, ignore */
1362     GNUNET_STATISTICS_update (GSC_stats,
1363                               gettext_noop
1364                               ("# bytes dropped (out of sequence)"), size,
1365                               GNUNET_NO);
1366     return;
1367   }
1368   if (kx->last_sequence_number_received > snum)
1369   {
1370     unsigned int rotbit = 1 << (kx->last_sequence_number_received - snum - 1);
1371
1372     if ((kx->last_packets_bitmap & rotbit) != 0)
1373     {
1374       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1375                   "Received duplicate message, ignoring.\n");
1376       GNUNET_STATISTICS_update (GSC_stats,
1377                                 gettext_noop ("# bytes dropped (duplicates)"),
1378                                 size, GNUNET_NO);
1379       /* duplicate, ignore */
1380       return;
1381     }
1382     kx->last_packets_bitmap |= rotbit;
1383   }
1384   if (kx->last_sequence_number_received < snum)
1385   {
1386     unsigned int shift = (snum - kx->last_sequence_number_received);
1387
1388     if (shift >= 8 * sizeof (kx->last_packets_bitmap))
1389       kx->last_packets_bitmap = 0;
1390     else
1391       kx->last_packets_bitmap <<= shift;
1392     kx->last_sequence_number_received = snum;
1393   }
1394
1395   /* check timestamp */
1396   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
1397   if (GNUNET_TIME_absolute_get_duration (t).rel_value_us >
1398       MAX_MESSAGE_AGE.rel_value_us)
1399   {
1400     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1401                 "Message received far too old (%s). Content ignored.\n",
1402                 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (t), GNUNET_YES));
1403     GNUNET_STATISTICS_update (GSC_stats,
1404                               gettext_noop
1405                               ("# bytes dropped (ancient message)"), size,
1406                               GNUNET_NO);
1407     return;
1408   }
1409
1410   /* process decrypted message(s) */
1411   update_timeout (kx);
1412   GNUNET_STATISTICS_update (GSC_stats,
1413                             gettext_noop ("# bytes of payload decrypted"),
1414                             size - sizeof (struct EncryptedMessage), GNUNET_NO);
1415   dmc.kx = kx;
1416   dmc.peer = &kx->peer;
1417   if (GNUNET_OK !=
1418       GNUNET_SERVER_mst_receive (mst, &dmc,
1419                                  &buf[sizeof (struct EncryptedMessage)],
1420                                  size - sizeof (struct EncryptedMessage),
1421                                  GNUNET_YES, GNUNET_NO))
1422     GNUNET_break_op (0);
1423 }
1424
1425
1426 /**
1427  * Deliver P2P message to interested clients.
1428  * Invokes send twice, once for clients that want the full message, and once
1429  * for clients that only want the header
1430  *
1431  * @param cls always NULL
1432  * @param client who sent us the message (struct GSC_KeyExchangeInfo)
1433  * @param m the message
1434  */
1435 static int
1436 deliver_message (void *cls, void *client, const struct GNUNET_MessageHeader *m)
1437 {
1438   struct DeliverMessageContext *dmc = client;
1439
1440   if (KX_STATE_UP != dmc->kx->status)
1441   {
1442     GNUNET_STATISTICS_update (GSC_stats,
1443                               gettext_noop
1444                               ("# PAYLOAD dropped (out of order)"),
1445                               1, GNUNET_NO);
1446     return GNUNET_OK;
1447   }
1448   switch (ntohs (m->type))
1449   {
1450   case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP:
1451   case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP:
1452     GSC_SESSIONS_set_typemap (dmc->peer, m);
1453     return GNUNET_OK;
1454   default:
1455     GSC_CLIENTS_deliver_message (dmc->peer, m,
1456                                  ntohs (m->size),
1457                                  GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
1458     GSC_CLIENTS_deliver_message (dmc->peer, m,
1459                                  sizeof (struct GNUNET_MessageHeader),
1460                                  GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
1461   }
1462   return GNUNET_OK;
1463 }
1464
1465
1466 /**
1467  * Setup the message that links the ephemeral key to our persistent
1468  * public key and generate the appropriate signature.
1469  */
1470 static void
1471 sign_ephemeral_key ()
1472 {
1473   current_ekm.header.size = htons (sizeof (struct EphemeralKeyMessage));
1474   current_ekm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY);
1475   current_ekm.sender_status = 0; /* to be set later */
1476   current_ekm.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY);
1477   current_ekm.purpose.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
1478                                     sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1479                                     sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1480                                     sizeof (struct GNUNET_CRYPTO_EccPublicSignKey) +
1481                                     sizeof (struct GNUNET_CRYPTO_EccPublicSignKey));
1482   current_ekm.creation_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1483   if (GNUNET_YES ==
1484       GNUNET_CONFIGURATION_get_value_yesno (GSC_cfg,
1485                                             "core",
1486                                             "USE_EPHEMERAL_KEYS"))
1487   {
1488     current_ekm.expiration_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_add (REKEY_FREQUENCY,
1489                                                                                                                          REKEY_TOLERANCE)));
1490   }
1491   else
1492   {
1493     current_ekm.expiration_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_FOREVER_ABS);
1494   }
1495   GNUNET_CRYPTO_ecc_key_get_public_for_signature (my_ephemeral_key,
1496                                     &current_ekm.ephemeral_key);
1497   current_ekm.origin_public_key = my_public_key;
1498   GNUNET_assert (GNUNET_OK ==
1499                  GNUNET_CRYPTO_ecc_sign (my_private_key,
1500                                          &current_ekm.purpose,
1501                                          &current_ekm.signature));
1502 }
1503
1504
1505 /**
1506  * Task run to trigger rekeying.
1507  *
1508  * @param cls closure, NULL
1509  * @param tc scheduler context
1510  */
1511 static void
1512 do_rekey (void *cls,
1513           const struct GNUNET_SCHEDULER_TaskContext *tc)
1514 {
1515   struct GSC_KeyExchangeInfo *pos;
1516
1517   rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY,
1518                                              &do_rekey,
1519                                              NULL);
1520   if (NULL != my_ephemeral_key)
1521     GNUNET_free (my_ephemeral_key);
1522   my_ephemeral_key = GNUNET_CRYPTO_ecc_key_create ();
1523   GNUNET_assert (NULL != my_ephemeral_key);
1524   sign_ephemeral_key ();
1525   for (pos = kx_head; NULL != pos; pos = pos->next)
1526   {
1527     pos->status = KX_STATE_REKEY_SENT;
1528     send_key (pos);
1529   }
1530 }
1531
1532
1533 /**
1534  * Initialize KX subsystem.
1535  *
1536  * @param pk private key to use for the peer
1537  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1538  */
1539 int
1540 GSC_KX_init (struct GNUNET_CRYPTO_EccPrivateKey *pk)
1541 {
1542   GNUNET_assert (NULL != pk);
1543   my_private_key = pk;
1544   GNUNET_CRYPTO_ecc_key_get_public_for_signature (my_private_key, &my_public_key);
1545   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1546                       &GSC_my_identity.hashPubKey);
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 */