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