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