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