-fix leak
[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_YES
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_log (GNUNET_ERROR_TYPE_ERROR,
881                 "Invalid key %x decrypted by %s from message %u (origin: %s)\n",
882                 (unsigned int) GNUNET_CRYPTO_crc32_n (&k, sizeof (struct GNUNET_CRYPTO_AesSessionKey)),
883                 GNUNET_i2s (&GSC_my_identity),
884                 (unsigned int) GNUNET_CRYPTO_crc32_n (&m->encrypted_key, sizeof (struct GNUNET_CRYPTO_RsaEncryptedData)),
885                 GNUNET_h2s (&kx->peer.hashPubKey));
886     GNUNET_break_op (0);
887     return;
888   }
889   GNUNET_STATISTICS_update (GSC_stats,
890                             gettext_noop ("# SET_KEY messages decrypted"), 1,
891                             GNUNET_NO);
892   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received SET_KEY from `%s'\n",
893               GNUNET_i2s (&kx->peer));
894   kx->decrypt_key = k;
895   if (kx->decrypt_key_created.abs_value != t.abs_value)
896   {
897     /* fresh key, reset sequence numbers */
898     kx->last_sequence_number_received = 0;
899     kx->last_packets_bitmap = 0;
900     kx->decrypt_key_created = t;
901   }
902   sender_status = (enum KxStateMachine) ntohl (m->sender_status);
903   switch (kx->status)
904   {
905   case KX_STATE_DOWN:
906     kx->status = KX_STATE_KEY_RECEIVED;
907     /* we're not up, so we are already doing 'send_key' */
908     break;
909   case KX_STATE_KEY_SENT:
910     kx->status = KX_STATE_KEY_RECEIVED;
911     /* we're not up, so we are already doing 'send_key' */
912     break;
913   case KX_STATE_KEY_RECEIVED:
914     /* we're not up, so we are already doing 'send_key' */
915     break;
916   case KX_STATE_UP: 
917     if ((sender_status == KX_STATE_DOWN) ||
918         (sender_status == KX_STATE_KEY_SENT))
919       send_key (kx);            /* we are up, but other peer is not! */
920     break;
921   case KX_STATE_REKEY:
922     if ((sender_status == KX_STATE_DOWN) ||
923         (sender_status == KX_STATE_KEY_SENT))
924       send_key (kx);            /* we are up, but other peer is not! */
925     break;
926   case KX_STATE_REKEY_SENT:
927     if ((sender_status == KX_STATE_DOWN) ||
928         (sender_status == KX_STATE_KEY_SENT))
929       send_key (kx);            /* we are up, but other peer is not! */
930     break;
931   default:
932     GNUNET_break (0);
933     break;
934   }
935   if (NULL != kx->ping_received)
936   {
937     ping = kx->ping_received;
938     kx->ping_received = NULL;
939     GSC_KX_handle_ping (kx, &ping->header);
940     GNUNET_free (ping);
941   }
942   if (NULL != kx->pong_received)
943   {
944     pong = kx->pong_received;
945     kx->pong_received = NULL;
946     GSC_KX_handle_pong (kx, &pong->header);
947     GNUNET_free (pong);
948   }
949 }
950
951
952 /**
953  * We received a PING message.  Validate and transmit
954  * a PONG message.
955  *
956  * @param kx key exchange status for the corresponding peer
957  * @param msg the encrypted PING message itself
958  */
959 void
960 GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *kx,
961                     const struct GNUNET_MessageHeader *msg)
962 {
963   const struct PingMessage *m;
964   struct PingMessage t;
965   struct PongMessage tx;
966   struct PongMessage tp;
967   struct GNUNET_CRYPTO_AesInitializationVector iv;
968   uint16_t msize;
969
970   msize = ntohs (msg->size);
971   if (msize != sizeof (struct PingMessage))
972   {
973     GNUNET_break_op (0);
974     return;
975   }
976   GNUNET_STATISTICS_update (GSC_stats,
977                             gettext_noop ("# PING messages received"), 1,
978                             GNUNET_NO);
979   if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP) &&
980       (kx->status != KX_STATE_REKEY_SENT))
981   {
982     /* defer */
983     GNUNET_free_non_null (kx->ping_received);
984     kx->ping_received = (struct PingMessage *) GNUNET_copy_message (msg);
985     return;
986   }
987   m = (const struct PingMessage *) msg;
988   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
989               "Core service receives `%s' request from `%4s'.\n", "PING",
990               GNUNET_i2s (&kx->peer));
991   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
992   if (GNUNET_OK !=
993       do_decrypt (kx, &iv, &m->target, &t.target,
994                   sizeof (struct PingMessage) - ((void *) &m->target -
995                                                  (void *) m)))
996   {
997     GNUNET_break_op (0);
998     return;
999   }
1000   if (0 !=
1001       memcmp (&t.target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
1002   {
1003     char sender[9];
1004     char peer[9];
1005
1006     GNUNET_snprintf (sender, sizeof (sender), "%8s", GNUNET_i2s (&kx->peer));
1007     GNUNET_snprintf (peer, sizeof (peer), "%8s", GNUNET_i2s (&t.target));
1008     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1009                 _
1010                 ("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
1011                 sender, GNUNET_i2s (&GSC_my_identity), peer);
1012     GNUNET_break_op (0);
1013     return;
1014   }
1015   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PING from `%s'\n",
1016               GNUNET_i2s (&kx->peer));
1017   /* construct PONG */
1018   tx.reserved = GNUNET_BANDWIDTH_VALUE_MAX;
1019   tx.challenge = t.challenge;
1020   tx.target = t.target;
1021   tp.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
1022   tp.header.size = htons (sizeof (struct PongMessage));
1023   tp.iv_seed =
1024       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1025   derive_pong_iv (&iv, &kx->encrypt_key, tp.iv_seed, t.challenge, &kx->peer);
1026   do_encrypt (kx, &iv, &tx.challenge, &tp.challenge,
1027               sizeof (struct PongMessage) - ((void *) &tp.challenge -
1028                                              (void *) &tp));
1029   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages created"),
1030                             1, GNUNET_NO);
1031   GSC_NEIGHBOURS_transmit (&kx->peer, &tp.header,
1032                            GNUNET_TIME_UNIT_FOREVER_REL /* FIXME: timeout */ );
1033 }
1034
1035
1036 /**
1037  * Create a fresh SET KEY message for transmission to the other peer.
1038  * Also creates a new key.
1039  *
1040  * @param kx key exchange context to create SET KEY message for
1041  */
1042 static void
1043 setup_fresh_setkey (struct GSC_KeyExchangeInfo *kx)
1044 {
1045   struct SetKeyMessage *skm;
1046
1047   GNUNET_CRYPTO_aes_create_session_key (&kx->encrypt_key);
1048   kx->encrypt_key_created = GNUNET_TIME_absolute_get ();
1049   skm = &kx->skm;
1050   skm->header.size = htons (sizeof (struct SetKeyMessage));
1051   skm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
1052   skm->purpose.size =
1053       htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1054              sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1055              sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
1056              sizeof (struct GNUNET_PeerIdentity));
1057   skm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
1058   skm->creation_time = GNUNET_TIME_absolute_hton (kx->encrypt_key_created);
1059   skm->target = kx->peer;
1060   CHECK_KX (kx);
1061   GNUNET_assert (GNUNET_OK ==
1062                  GNUNET_CRYPTO_rsa_encrypt (&kx->encrypt_key,
1063                                             sizeof (struct
1064                                                     GNUNET_CRYPTO_AesSessionKey),
1065                                             kx->public_key,
1066                                             &skm->encrypted_key));
1067   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1068               "Encrypting key %x for %s resulting in message %u (origin: %s)\n",
1069               (unsigned int) GNUNET_CRYPTO_crc32_n (&kx->encrypt_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey)),
1070               GNUNET_i2s (&kx->peer),
1071               (unsigned int) GNUNET_CRYPTO_crc32_n (&skm->encrypted_key, sizeof (struct GNUNET_CRYPTO_RsaEncryptedData)),
1072               GNUNET_h2s (&GSC_my_identity.hashPubKey));
1073
1074   GNUNET_assert (GNUNET_OK ==
1075                  GNUNET_CRYPTO_rsa_sign (my_private_key, &skm->purpose,
1076                                          &skm->signature));
1077 }
1078
1079
1080 /**
1081  * Create a fresh PING message for transmission to the other peer.
1082  *
1083  * @param kx key exchange context to create PING for
1084  */
1085 static void
1086 setup_fresh_ping (struct GSC_KeyExchangeInfo *kx)
1087 {
1088   struct PingMessage pp;
1089   struct PingMessage *pm;
1090   struct GNUNET_CRYPTO_AesInitializationVector iv;
1091
1092   pm = &kx->ping;
1093   pm->header.size = htons (sizeof (struct PingMessage));
1094   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1095   pm->iv_seed =
1096       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1097   derive_iv (&iv, &kx->encrypt_key, pm->iv_seed, &kx->peer);
1098   pp.challenge = kx->ping_challenge;
1099   pp.target = kx->peer;
1100   do_encrypt (kx, &iv, &pp.target, &pm->target,
1101               sizeof (struct PingMessage) - ((void *) &pm->target -
1102                                              (void *) pm));
1103 }
1104
1105
1106 /**
1107  * Task triggered when a neighbour entry is about to time out
1108  * (and we should prevent this by sending a PING).
1109  *
1110  * @param cls the 'struct GSC_KeyExchangeInfo'
1111  * @param tc scheduler context (not used)
1112  */
1113 static void
1114 send_keep_alive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1115 {
1116   struct GSC_KeyExchangeInfo *kx = cls;
1117   struct GNUNET_TIME_Relative retry;
1118   struct GNUNET_TIME_Relative left;
1119
1120   kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1121   left = GNUNET_TIME_absolute_get_remaining (kx->timeout);
1122   if (0 == left.rel_value)
1123   {
1124     GNUNET_STATISTICS_update (GSC_stats,
1125                               gettext_noop ("# sessions terminated by timeout"),
1126                               1, GNUNET_NO);
1127     GSC_SESSIONS_end (&kx->peer);
1128     kx->status = KX_STATE_DOWN;
1129     return;
1130   }
1131   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending KEEPALIVE to `%s'\n",
1132               GNUNET_i2s (&kx->peer));
1133   GNUNET_STATISTICS_update (GSC_stats,
1134                             gettext_noop ("# keepalive messages sent"), 1,
1135                             GNUNET_NO);
1136   setup_fresh_ping (kx);
1137   GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
1138                            kx->set_key_retry_frequency);
1139   retry =
1140       GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1141                                 MIN_PING_FREQUENCY);
1142   kx->keep_alive_task =
1143       GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx);
1144 }
1145
1146
1147 /**
1148  * We've seen a valid message from the other peer.
1149  * Update the time when the session would time out
1150  * and delay sending our keep alive message further.
1151  *
1152  * @param kx key exchange where we saw activity
1153  */
1154 static void
1155 update_timeout (struct GSC_KeyExchangeInfo *kx)
1156 {
1157   kx->timeout =
1158       GNUNET_TIME_relative_to_absolute
1159       (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1160   if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1161     GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1162   kx->keep_alive_task =
1163       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
1164                                     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1165                                      2), &send_keep_alive, kx);
1166 }
1167
1168
1169 /**
1170  * Trigger rekeying event.
1171  * 
1172  * @param cls the 'struct GSC_KeyExchangeInfo'
1173  * @param tc schedule context (unused)
1174  */
1175 static void
1176 trigger_rekey (void *cls,
1177                const struct GNUNET_SCHEDULER_TaskContext *tc)
1178 {
1179   struct GSC_KeyExchangeInfo *kx = cls;
1180   
1181   kx->status = KX_STATE_REKEY;
1182   kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
1183   kx->retry_set_key_task =
1184     GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
1185                                   &set_key_retry_task, kx);
1186 }
1187
1188
1189 /**
1190  * Schedule rekey operation.
1191  *
1192  * @param kx key exchange to schedule rekey for
1193  */
1194 static void
1195 schedule_rekey (struct GSC_KeyExchangeInfo *kx)
1196 {
1197   struct GNUNET_TIME_Relative rdelay;
1198
1199   if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)  
1200     GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1201   rdelay = REKEY_FREQUENCY;
1202   /* randomize rekey frequency by one minute to avoid synchronization */
1203   rdelay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1204                                                 60 * 1000);
1205   kx->retry_set_key_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY,
1206                                                          &trigger_rekey,
1207                                                          kx);   
1208 }
1209
1210
1211 /**
1212  * We received a PONG message.  Validate and update our status.
1213  *
1214  * @param kx key exchange context for the the PONG
1215  * @param msg the encrypted PONG message itself
1216  */
1217 void
1218 GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx,
1219                     const struct GNUNET_MessageHeader *msg)
1220 {
1221   const struct PongMessage *m;
1222   struct PongMessage t;
1223   struct EncryptedMessage *emsg;
1224   struct GNUNET_CRYPTO_AesInitializationVector iv;
1225   uint16_t msize;
1226
1227   msize = ntohs (msg->size);
1228   if (sizeof (struct PongMessage) != msize)
1229   {
1230     GNUNET_break_op (0);
1231     return;
1232   }
1233   GNUNET_STATISTICS_update (GSC_stats,
1234                             gettext_noop ("# PONG messages received"), 1,
1235                             GNUNET_NO);
1236   switch (kx->status)
1237   {
1238   case KX_STATE_DOWN:
1239     return;
1240   case KX_STATE_KEY_SENT:
1241     GNUNET_free_non_null (kx->pong_received);
1242     kx->pong_received = (struct PongMessage *) GNUNET_copy_message (msg);    
1243     return;
1244   case KX_STATE_KEY_RECEIVED:
1245     break;
1246   case KX_STATE_UP:
1247     break;
1248   case KX_STATE_REKEY:
1249     break;
1250   case KX_STATE_REKEY_SENT:
1251     break;
1252   default:
1253     GNUNET_break (0);
1254     return;
1255   }
1256   m = (const struct PongMessage *) msg;
1257   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1258               "Core service receives `%s' response from `%4s'.\n", "PONG",
1259               GNUNET_i2s (&kx->peer));
1260   /* mark as garbage, just to be sure */
1261   memset (&t, 255, sizeof (t));
1262   derive_pong_iv (&iv, &kx->decrypt_key, m->iv_seed, kx->ping_challenge,
1263                   &GSC_my_identity);
1264   if (GNUNET_OK !=
1265       do_decrypt (kx, &iv, &m->challenge, &t.challenge,
1266                   sizeof (struct PongMessage) - ((void *) &m->challenge -
1267                                                  (void *) m)))
1268   {
1269     GNUNET_break_op (0);
1270     return;
1271   }
1272   GNUNET_STATISTICS_update (GSC_stats,
1273                             gettext_noop ("# PONG messages decrypted"), 1,
1274                             GNUNET_NO);
1275   if ((0 != memcmp (&t.target, &kx->peer, sizeof (struct GNUNET_PeerIdentity)))
1276       || (kx->ping_challenge != t.challenge))
1277   {
1278     /* PONG malformed */
1279     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1280                 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
1281                 "PONG", GNUNET_i2s (&kx->peer),
1282                 (unsigned int) kx->ping_challenge);
1283     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1284                 "Received malformed `%s' received from `%4s' with challenge %u\n",
1285                 "PONG", GNUNET_i2s (&t.target), (unsigned int) t.challenge);
1286     return;
1287   }
1288   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PONG from `%s'\n",
1289               GNUNET_i2s (&kx->peer));
1290   switch (kx->status)
1291   {
1292   case KX_STATE_DOWN:
1293     GNUNET_break (0);           /* should be impossible */
1294     return;
1295   case KX_STATE_KEY_SENT:
1296     GNUNET_break (0);           /* should be impossible */
1297     return;
1298   case KX_STATE_KEY_RECEIVED:
1299     GNUNET_STATISTICS_update (GSC_stats,
1300                               gettext_noop
1301                               ("# session keys confirmed via PONG"), 1,
1302                               GNUNET_NO);
1303     kx->status = KX_STATE_UP;
1304     GSC_SESSIONS_create (&kx->peer, kx);
1305     CHECK_KX (kx);
1306     schedule_rekey (kx);
1307     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
1308     if (NULL != kx->emsg_received)
1309     {
1310       emsg = kx->emsg_received;
1311       kx->emsg_received = NULL;
1312       GSC_KX_handle_encrypted_message (kx, &emsg->header, NULL,
1313                                        0 /* FIXME: ATSI */ );
1314       GNUNET_free (emsg);
1315     }
1316     update_timeout (kx);
1317     break;
1318   case KX_STATE_UP:
1319     update_timeout (kx);
1320     break;
1321   case KX_STATE_REKEY:
1322     update_timeout (kx);
1323     break;
1324   case KX_STATE_REKEY_SENT:
1325     GNUNET_STATISTICS_update (GSC_stats,
1326                               gettext_noop
1327                               ("# rekey operations confirmed via PONG"), 1,
1328                               GNUNET_NO);
1329     kx->status = KX_STATE_UP;
1330     schedule_rekey (kx);
1331     update_timeout (kx);
1332     break;
1333   default:
1334     GNUNET_break (0);
1335     break;
1336   }
1337 }
1338
1339
1340 /**
1341  * Send our key (and encrypted PING) to the other peer.
1342  *
1343  * @param kx key exchange context
1344  */
1345 static void
1346 send_key (struct GSC_KeyExchangeInfo *kx)
1347 {
1348   CHECK_KX (kx);
1349   if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
1350   {
1351      GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1352      kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1353   }
1354   if (KX_STATE_UP == kx->status)
1355     return;                     /* nothing to do */
1356   if (NULL == kx->public_key)
1357   {
1358     /* lookup public key, then try again */
1359     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1360                 "Trying to obtain public key for `%s'\n",
1361                 GNUNET_i2s (&kx->peer));
1362     kx->pitr =
1363         GNUNET_PEERINFO_iterate (peerinfo, &kx->peer,
1364                                  GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */ ,
1365                                  &process_hello, kx);
1366     return;
1367   }
1368
1369   /* update status */
1370   switch (kx->status)
1371   {
1372   case KX_STATE_DOWN:
1373     kx->status = KX_STATE_KEY_SENT;
1374     /* setup SET KEY message */
1375     setup_fresh_setkey (kx);
1376     setup_fresh_ping (kx);
1377     GNUNET_STATISTICS_update (GSC_stats,
1378                               gettext_noop
1379                               ("# SET_KEY and PING messages created"), 1,
1380                               GNUNET_NO);
1381     break;
1382   case KX_STATE_KEY_SENT:
1383     break;
1384   case KX_STATE_KEY_RECEIVED:
1385     break;
1386   case KX_STATE_UP:
1387     GNUNET_break (0);
1388     return;
1389   case KX_STATE_REKEY:
1390     kx->status = KX_STATE_REKEY_SENT;
1391     /* setup fresh SET KEY message */
1392     setup_fresh_setkey (kx);
1393     setup_fresh_ping (kx);
1394     GNUNET_STATISTICS_update (GSC_stats,
1395                               gettext_noop
1396                               ("# SET_KEY and PING messages created"), 1,
1397                               GNUNET_NO);
1398     GNUNET_STATISTICS_update (GSC_stats,
1399                               gettext_noop
1400                               ("# REKEY operations performed"), 1,
1401                               GNUNET_NO);
1402     break;
1403   case KX_STATE_REKEY_SENT:
1404     break;
1405   default:
1406     GNUNET_break (0);
1407     return;
1408   }
1409
1410   /* always update sender status in SET KEY message */
1411   /* Not sending rekey sent state to be compatible with GNUnet 0.9.2 */
1412   kx->skm.sender_status = htonl ((int32_t) ((kx->status == KX_STATE_REKEY_SENT) ? 
1413                                             KX_STATE_KEY_RECEIVED : kx->status));  
1414   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending SET_KEY and PING to `%s'\n",
1415               GNUNET_i2s (&kx->peer));
1416   GSC_NEIGHBOURS_transmit (&kx->peer, &kx->skm.header,
1417                            kx->set_key_retry_frequency);
1418   GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
1419                            kx->set_key_retry_frequency);
1420   kx->retry_set_key_task =
1421       GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
1422                                     &set_key_retry_task, kx);
1423 }
1424
1425
1426 /**
1427  * Encrypt and transmit a message with the given payload.
1428  *
1429  * @param kx key exchange context
1430  * @param payload payload of the message
1431  * @param payload_size number of bytes in 'payload'
1432  */
1433 void
1434 GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
1435                              const void *payload, size_t payload_size)
1436 {
1437   size_t used = payload_size + sizeof (struct EncryptedMessage);
1438   char pbuf[used];              /* plaintext */
1439   char cbuf[used];              /* ciphertext */
1440   struct EncryptedMessage *em;  /* encrypted message */
1441   struct EncryptedMessage *ph;  /* plaintext header */
1442   struct GNUNET_CRYPTO_AesInitializationVector iv;
1443   struct GNUNET_CRYPTO_AuthKey auth_key;
1444
1445   ph = (struct EncryptedMessage *) pbuf;
1446   ph->iv_seed =
1447       htonl (GNUNET_CRYPTO_random_u32
1448              (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
1449   ph->sequence_number = htonl (++kx->last_sequence_number_sent);
1450   ph->reserved = GNUNET_BANDWIDTH_VALUE_MAX;
1451   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1452   memcpy (&ph[1], payload, payload_size);
1453
1454   em = (struct EncryptedMessage *) cbuf;
1455   em->header.size = htons (used);
1456   em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1457   em->iv_seed = ph->iv_seed;
1458   derive_iv (&iv, &kx->encrypt_key, ph->iv_seed, &kx->peer);
1459   GNUNET_assert (GNUNET_OK ==
1460                  do_encrypt (kx, &iv, &ph->sequence_number,
1461                              &em->sequence_number,
1462                              used - ENCRYPTED_HEADER_SIZE));
1463   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Encrypted %u bytes for %s\n",
1464               used - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1465   derive_auth_key (&auth_key, &kx->encrypt_key, ph->iv_seed,
1466                    kx->encrypt_key_created);
1467   GNUNET_CRYPTO_hmac (&auth_key, &em->sequence_number,
1468                       used - ENCRYPTED_HEADER_SIZE, &em->hmac);
1469   GSC_NEIGHBOURS_transmit (&kx->peer, &em->header,
1470                            GNUNET_TIME_UNIT_FOREVER_REL);
1471 }
1472
1473
1474 /**
1475  * Closure for 'deliver_message'
1476  */
1477 struct DeliverMessageContext
1478 {
1479
1480   /**
1481    * Performance information for the connection.
1482    */
1483   const struct GNUNET_ATS_Information *atsi;
1484
1485   /**
1486    * Sender of the message.
1487    */
1488   const struct GNUNET_PeerIdentity *peer;
1489
1490   /**
1491    * Number of entries in 'atsi' array.
1492    */
1493   uint32_t atsi_count;
1494 };
1495
1496
1497 /**
1498  * We received an encrypted message.  Decrypt, validate and
1499  * pass on to the appropriate clients.
1500  *
1501  * @param kx key exchange context for encrypting the message
1502  * @param msg encrypted message
1503  * @param atsi performance data
1504  * @param atsi_count number of entries in ats (excluding 0-termination)
1505  */
1506 void
1507 GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *kx,
1508                                  const struct GNUNET_MessageHeader *msg,
1509                                  const struct GNUNET_ATS_Information *atsi,
1510                                  uint32_t atsi_count)
1511 {
1512   const struct EncryptedMessage *m;
1513   struct EncryptedMessage *pt;  /* plaintext */
1514   GNUNET_HashCode ph;
1515   uint32_t snum;
1516   struct GNUNET_TIME_Absolute t;
1517   struct GNUNET_CRYPTO_AesInitializationVector iv;
1518   struct GNUNET_CRYPTO_AuthKey auth_key;
1519   struct DeliverMessageContext dmc;
1520   uint16_t size = ntohs (msg->size);
1521   char buf[size] GNUNET_ALIGN;
1522
1523   if (size <
1524       sizeof (struct EncryptedMessage) + sizeof (struct GNUNET_MessageHeader))
1525   {
1526     GNUNET_break_op (0);
1527     return;
1528   }
1529   m = (const struct EncryptedMessage *) msg;
1530   if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP) &&
1531       (kx->status != KX_STATE_REKEY_SENT) )
1532   {
1533     GNUNET_STATISTICS_update (GSC_stats,
1534                               gettext_noop
1535                               ("# failed to decrypt message (no session key)"),
1536                               1, GNUNET_NO);
1537     return;
1538   }
1539   if (KX_STATE_KEY_RECEIVED == kx->status)
1540   {
1541     /* defer */
1542     GNUNET_free_non_null (kx->emsg_received);
1543     kx->emsg_received = (struct EncryptedMessage *) GNUNET_copy_message (msg);
1544     return;
1545   }
1546   /* validate hash */
1547   derive_auth_key (&auth_key, &kx->decrypt_key, m->iv_seed,
1548                    kx->decrypt_key_created);
1549   GNUNET_CRYPTO_hmac (&auth_key, &m->sequence_number,
1550                       size - ENCRYPTED_HEADER_SIZE, &ph);
1551   if (0 != memcmp (&ph, &m->hmac, sizeof (GNUNET_HashCode)))
1552   {
1553     /* checksum failed */
1554     GNUNET_break_op (0);
1555     return;
1556   }
1557   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
1558   /* decrypt */
1559   if (GNUNET_OK !=
1560       do_decrypt (kx, &iv, &m->sequence_number, &buf[ENCRYPTED_HEADER_SIZE],
1561                   size - ENCRYPTED_HEADER_SIZE))
1562     return;
1563   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypted %u bytes from %s\n",
1564               size - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1565   pt = (struct EncryptedMessage *) buf;
1566
1567   /* validate sequence number */
1568   snum = ntohl (pt->sequence_number);
1569   if (kx->last_sequence_number_received == snum)
1570   {
1571     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1572                 "Received duplicate message, ignoring.\n");
1573     /* duplicate, ignore */
1574     GNUNET_STATISTICS_update (GSC_stats,
1575                               gettext_noop ("# bytes dropped (duplicates)"),
1576                               size, GNUNET_NO);
1577     return;
1578   }
1579   if ((kx->last_sequence_number_received > snum) &&
1580       (kx->last_sequence_number_received - snum > 32))
1581   {
1582     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1583                 "Received ancient out of sequence message, ignoring.\n");
1584     /* ancient out of sequence, ignore */
1585     GNUNET_STATISTICS_update (GSC_stats,
1586                               gettext_noop
1587                               ("# bytes dropped (out of sequence)"), size,
1588                               GNUNET_NO);
1589     return;
1590   }
1591   if (kx->last_sequence_number_received > snum)
1592   {
1593     unsigned int rotbit = 1 << (kx->last_sequence_number_received - snum - 1);
1594
1595     if ((kx->last_packets_bitmap & rotbit) != 0)
1596     {
1597       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1598                   "Received duplicate message, ignoring.\n");
1599       GNUNET_STATISTICS_update (GSC_stats,
1600                                 gettext_noop ("# bytes dropped (duplicates)"),
1601                                 size, GNUNET_NO);
1602       /* duplicate, ignore */
1603       return;
1604     }
1605     kx->last_packets_bitmap |= rotbit;
1606   }
1607   if (kx->last_sequence_number_received < snum)
1608   {
1609     unsigned int shift = (snum - kx->last_sequence_number_received);
1610
1611     if (shift >= 8 * sizeof (kx->last_packets_bitmap))
1612       kx->last_packets_bitmap = 0;
1613     else
1614       kx->last_packets_bitmap <<= shift;
1615     kx->last_sequence_number_received = snum;
1616   }
1617
1618   /* check timestamp */
1619   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
1620   if (GNUNET_TIME_absolute_get_duration (t).rel_value >
1621       MAX_MESSAGE_AGE.rel_value)
1622   {
1623     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1624                 _("Message received far too old (%llu ms). Content ignored.\n"),
1625                 GNUNET_TIME_absolute_get_duration (t).rel_value);
1626     GNUNET_STATISTICS_update (GSC_stats,
1627                               gettext_noop
1628                               ("# bytes dropped (ancient message)"), size,
1629                               GNUNET_NO);
1630     return;
1631   }
1632
1633   /* process decrypted message(s) */
1634   update_timeout (kx);
1635   GNUNET_STATISTICS_update (GSC_stats,
1636                             gettext_noop ("# bytes of payload decrypted"),
1637                             size - sizeof (struct EncryptedMessage), GNUNET_NO);
1638   dmc.atsi = atsi;
1639   dmc.atsi_count = atsi_count;
1640   dmc.peer = &kx->peer;
1641   if (GNUNET_OK !=
1642       GNUNET_SERVER_mst_receive (mst, &dmc,
1643                                  &buf[sizeof (struct EncryptedMessage)],
1644                                  size - sizeof (struct EncryptedMessage),
1645                                  GNUNET_YES, GNUNET_NO))
1646     GNUNET_break_op (0);
1647 }
1648
1649
1650 /**
1651  * Deliver P2P message to interested clients.
1652  * Invokes send twice, once for clients that want the full message, and once
1653  * for clients that only want the header
1654  *
1655  * @param cls always NULL
1656  * @param client who sent us the message (struct GSC_KeyExchangeInfo)
1657  * @param m the message
1658  */
1659 static void
1660 deliver_message (void *cls, void *client, const struct GNUNET_MessageHeader *m)
1661 {
1662   struct DeliverMessageContext *dmc = client;
1663
1664   switch (ntohs (m->type))
1665   {
1666   case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP:
1667   case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP:
1668     GSC_SESSIONS_set_typemap (dmc->peer, m);
1669     return;
1670   default:
1671     GSC_CLIENTS_deliver_message (dmc->peer, dmc->atsi, dmc->atsi_count, m,
1672                                  ntohs (m->size),
1673                                  GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
1674     GSC_CLIENTS_deliver_message (dmc->peer, dmc->atsi, dmc->atsi_count, m,
1675                                  sizeof (struct GNUNET_MessageHeader),
1676                                  GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
1677   }
1678 }
1679
1680
1681 /**
1682  * Initialize KX subsystem.
1683  *
1684  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1685  */
1686 int
1687 GSC_KX_init ()
1688 {
1689   char *keyfile;
1690
1691   if (GNUNET_OK !=
1692       GNUNET_CONFIGURATION_get_value_filename (GSC_cfg, "GNUNETD", "HOSTKEY",
1693                                                &keyfile))
1694   {
1695     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1696                 _
1697                 ("Core service is lacking HOSTKEY configuration setting.  Exiting.\n"));
1698     return GNUNET_SYSERR;
1699   }
1700   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1701   GNUNET_free (keyfile);
1702   if (NULL == my_private_key)
1703   {
1704     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1705                 _("Core service could not access hostkey.  Exiting.\n"));
1706     return GNUNET_SYSERR;
1707   }
1708   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1709   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1710                       &GSC_my_identity.hashPubKey);
1711   peerinfo = GNUNET_PEERINFO_connect (GSC_cfg);
1712   if (NULL == peerinfo)
1713   {
1714     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1715                 _("Could not access PEERINFO service.  Exiting.\n"));
1716     GNUNET_CRYPTO_rsa_key_free (my_private_key);
1717     my_private_key = NULL;
1718     return GNUNET_SYSERR;
1719   }
1720   mst = GNUNET_SERVER_mst_create (&deliver_message, NULL);
1721   return GNUNET_OK;
1722 }
1723
1724
1725 /**
1726  * Shutdown KX subsystem.
1727  */
1728 void
1729 GSC_KX_done ()
1730 {
1731   if (NULL != my_private_key)
1732   {
1733     GNUNET_CRYPTO_rsa_key_free (my_private_key);
1734     my_private_key = NULL;
1735   }
1736   if (NULL != peerinfo)
1737   {
1738     GNUNET_PEERINFO_disconnect (peerinfo);
1739     peerinfo = NULL;
1740   }
1741   if (NULL != mst)
1742   {
1743     GNUNET_SERVER_mst_destroy (mst);
1744     mst = NULL;
1745   }
1746 }
1747
1748 /* end of gnunet-service-core_kx.c */