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