- send START first
[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     kx->retry_set_key_task =
607         GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
608                                       &set_key_retry_task, kx);
609     return;
610   }
611   if (peer == NULL)
612   {
613     kx->pitr = NULL;
614     if (kx->public_key != NULL)
615       return;                   /* done here */
616 #if DEBUG_CORE
617     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
618                 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
619                 GNUNET_i2s (&kx->peer));
620 #endif
621     GNUNET_STATISTICS_update (GSC_stats,
622                               gettext_noop
623                               ("# Delayed connecting due to lack of public key"),
624                               1, GNUNET_NO);
625     kx->retry_set_key_task =
626         GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
627                                       &set_key_retry_task, kx);
628     return;
629   }
630   if (kx->public_key != NULL)
631   {
632     /* already have public key, why are we here? */
633     GNUNET_break (0);
634     return;
635   }
636   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->retry_set_key_task);
637   kx->public_key =
638       GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
639   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, kx->public_key))
640   {
641     GNUNET_break (0);
642     GNUNET_free (kx->public_key);
643     kx->public_key = NULL;
644     return;
645   }
646   send_key (kx);
647   if (NULL != kx->skm_received)
648   {
649     skm = kx->skm_received;
650     kx->skm_received = NULL;
651     GSC_KX_handle_set_key (kx, &skm->header);
652     GNUNET_free (skm);
653   }
654 }
655
656
657 /**
658  * Start the key exchange with the given peer.
659  *
660  * @param pid identity of the peer to do a key exchange with
661  * @return key exchange information context
662  */
663 struct GSC_KeyExchangeInfo *
664 GSC_KX_start (const struct GNUNET_PeerIdentity *pid)
665 {
666   struct GSC_KeyExchangeInfo *kx;
667
668 #if DEBUG_CORE
669   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Initiating key exchange with `%s'\n",
670               GNUNET_i2s (pid));
671 #endif
672   GNUNET_STATISTICS_update (GSC_stats,
673                             gettext_noop ("# key exchanges initiated"), 1,
674                             GNUNET_NO);
675   kx = GNUNET_malloc (sizeof (struct GSC_KeyExchangeInfo));
676   kx->peer = *pid;
677   kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
678   kx->pitr =
679       GNUNET_PEERINFO_iterate (peerinfo, pid,
680                                GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */ ,
681                                &process_hello, kx);
682   return kx;
683 }
684
685
686 /**
687  * Stop key exchange with the given peer.  Clean up key material.
688  *
689  * @param kx key exchange to stop
690  */
691 void
692 GSC_KX_stop (struct GSC_KeyExchangeInfo *kx)
693 {
694   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# key exchanges stopped"),
695                             1, GNUNET_NO);
696   if (kx->pitr != NULL)
697   {
698     GNUNET_PEERINFO_iterate_cancel (kx->pitr);
699     kx->pitr = NULL;
700   }
701   if (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
702   {
703     GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
704     kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
705   }
706   if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
707   {
708     GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
709     kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
710   }
711   GNUNET_free_non_null (kx->skm_received);
712   GNUNET_free_non_null (kx->ping_received);
713   GNUNET_free_non_null (kx->pong_received);
714   GNUNET_free_non_null (kx->emsg_received);
715   GNUNET_free_non_null (kx->public_key);
716   GNUNET_free (kx);
717 }
718
719
720 /**
721  * We received a SET_KEY message.  Validate and update
722  * our key material and status.
723  *
724  * @param kx key exchange status for the corresponding peer
725  * @param msg the set key message we received
726  */
727 void
728 GSC_KX_handle_set_key (struct GSC_KeyExchangeInfo *kx,
729                        const struct GNUNET_MessageHeader *msg)
730 {
731   const struct SetKeyMessage *m;
732   struct GNUNET_TIME_Absolute t;
733   struct GNUNET_CRYPTO_AesSessionKey k;
734   struct PingMessage *ping;
735   struct PongMessage *pong;
736   enum KxStateMachine sender_status;
737   uint16_t size;
738
739   size = ntohs (msg->size);
740   if (size != sizeof (struct SetKeyMessage))
741   {
742     GNUNET_break_op (0);
743     return;
744   }
745   m = (const struct SetKeyMessage *) msg;
746   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# session keys received"),
747                             1, GNUNET_NO);
748
749 #if DEBUG_CORE
750   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
751               "Core service receives `%s' request from `%4s'.\n", "SET_KEY",
752               GNUNET_i2s (&kx->peer));
753 #endif
754   if (kx->public_key == NULL)
755   {
756     GNUNET_free_non_null (kx->skm_received);
757     kx->skm_received = (struct SetKeyMessage *) GNUNET_copy_message (msg);
758     return;
759   }
760   if (0 !=
761       memcmp (&m->target, &GSC_my_identity,
762               sizeof (struct GNUNET_PeerIdentity)))
763   {
764     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
765                 _("`%s' is for `%s', not for me.  Ignoring.\n"), "SET_KEY",
766                 GNUNET_i2s (&m->target));
767     return;
768   }
769   if ((ntohl (m->purpose.size) !=
770        sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
771        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
772        sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
773        sizeof (struct GNUNET_PeerIdentity)) ||
774       (GNUNET_OK !=
775        GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY, &m->purpose,
776                                  &m->signature, kx->public_key)))
777   {
778     /* invalid signature */
779     GNUNET_break_op (0);
780     return;
781   }
782   t = GNUNET_TIME_absolute_ntoh (m->creation_time);
783   if (((kx->status == KX_STATE_KEY_RECEIVED) || (kx->status == KX_STATE_UP)) &&
784       (t.abs_value < kx->decrypt_key_created.abs_value))
785   {
786     /* this could rarely happen due to massive re-ordering of
787      * messages on the network level, but is most likely either
788      * a bug or some adversary messing with us.  Report. */
789     GNUNET_break_op (0);
790     return;
791   }
792   if ((GNUNET_CRYPTO_rsa_decrypt
793        (my_private_key, &m->encrypted_key, &k,
794         sizeof (struct GNUNET_CRYPTO_AesSessionKey)) !=
795        sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
796       (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
797   {
798     /* failed to decrypt !? */
799     GNUNET_break_op (0);
800     return;
801   }
802   GNUNET_STATISTICS_update (GSC_stats,
803                             gettext_noop ("# SET_KEY messages decrypted"), 1,
804                             GNUNET_NO);
805 #if DEBUG_CORE
806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received SET_KEY from `%s'\n",
807               GNUNET_i2s (&kx->peer));
808 #endif
809   kx->decrypt_key = k;
810   if (kx->decrypt_key_created.abs_value != t.abs_value)
811   {
812     /* fresh key, reset sequence numbers */
813     kx->last_sequence_number_received = 0;
814     kx->last_packets_bitmap = 0;
815     kx->decrypt_key_created = t;
816   }
817   sender_status = (enum KxStateMachine) ntohl (m->sender_status);
818
819   switch (kx->status)
820   {
821   case KX_STATE_DOWN:
822     kx->status = KX_STATE_KEY_RECEIVED;
823     /* we're not up, so we are already doing 'send_key' */
824     break;
825   case KX_STATE_KEY_SENT:
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_RECEIVED:
830     /* we're not up, so we are already doing 'send_key' */
831     break;
832   case KX_STATE_UP:
833     if ((sender_status == KX_STATE_DOWN) ||
834         (sender_status == KX_STATE_KEY_SENT))
835       send_key (kx);            /* we are up, but other peer is not! */
836     break;
837   default:
838     GNUNET_break (0);
839     break;
840   }
841   if (kx->ping_received != NULL)
842   {
843     ping = kx->ping_received;
844     kx->ping_received = NULL;
845     GSC_KX_handle_ping (kx, &ping->header);
846     GNUNET_free (ping);
847   }
848   if (kx->pong_received != NULL)
849   {
850     pong = kx->pong_received;
851     kx->pong_received = NULL;
852     GSC_KX_handle_pong (kx, &pong->header);
853     GNUNET_free (pong);
854   }
855 }
856
857
858 /**
859  * We received a PING message.  Validate and transmit
860  * a PONG message.
861  *
862  * @param kx key exchange status for the corresponding peer
863  * @param msg the encrypted PING message itself
864  */
865 void
866 GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *kx,
867                     const struct GNUNET_MessageHeader *msg)
868 {
869   const struct PingMessage *m;
870   struct PingMessage t;
871   struct PongMessage tx;
872   struct PongMessage tp;
873   struct GNUNET_CRYPTO_AesInitializationVector iv;
874   uint16_t msize;
875
876   msize = ntohs (msg->size);
877   if (msize != sizeof (struct PingMessage))
878   {
879     GNUNET_break_op (0);
880     return;
881   }
882   GNUNET_STATISTICS_update (GSC_stats,
883                             gettext_noop ("# PING messages received"), 1,
884                             GNUNET_NO);
885   if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP))
886   {
887     /* defer */
888     GNUNET_free_non_null (kx->ping_received);
889     kx->ping_received = (struct PingMessage *) GNUNET_copy_message (msg);
890     return;
891   }
892   m = (const struct PingMessage *) msg;
893 #if DEBUG_CORE
894   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
895               "Core service receives `%s' request from `%4s'.\n", "PING",
896               GNUNET_i2s (&kx->peer));
897 #endif
898   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
899   if (GNUNET_OK !=
900       do_decrypt (kx, &iv, &m->target, &t.target,
901                   sizeof (struct PingMessage) - ((void *) &m->target -
902                                                  (void *) m)))
903   {
904     GNUNET_break_op (0);
905     return;
906   }
907   if (0 !=
908       memcmp (&t.target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
909   {
910     char sender[9];
911     char peer[9];
912
913     GNUNET_snprintf (sender, sizeof (sender), "%8s", GNUNET_i2s (&kx->peer));
914     GNUNET_snprintf (peer, sizeof (peer), "%8s", GNUNET_i2s (&t.target));
915     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
916                 _
917                 ("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
918                 sender, GNUNET_i2s (&GSC_my_identity), peer);
919     GNUNET_break_op (0);
920     return;
921   }
922 #if DEBUG_CORE
923   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PING from `%s'\n",
924               GNUNET_i2s (&kx->peer));
925 #endif
926   /* construct PONG */
927   tx.reserved = GNUNET_BANDWIDTH_VALUE_MAX;
928   tx.challenge = t.challenge;
929   tx.target = t.target;
930   tp.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
931   tp.header.size = htons (sizeof (struct PongMessage));
932   tp.iv_seed =
933       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
934   derive_pong_iv (&iv, &kx->encrypt_key, tp.iv_seed, t.challenge, &kx->peer);
935   do_encrypt (kx, &iv, &tx.challenge, &tp.challenge,
936               sizeof (struct PongMessage) - ((void *) &tp.challenge -
937                                              (void *) &tp));
938   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages created"),
939                             1, GNUNET_NO);
940   GSC_NEIGHBOURS_transmit (&kx->peer, &tp.header,
941                            GNUNET_TIME_UNIT_FOREVER_REL /* FIXME: timeout */ );
942 }
943
944
945 /**
946  * Create a fresh SET KEY message for transmission to the other peer.
947  * Also creates a new key.
948  *
949  * @param kx key exchange context to create SET KEY message for
950  */
951 static void
952 setup_fresh_setkey (struct GSC_KeyExchangeInfo *kx)
953 {
954   struct SetKeyMessage *skm;
955
956   GNUNET_CRYPTO_aes_create_session_key (&kx->encrypt_key);
957   kx->encrypt_key_created = GNUNET_TIME_absolute_get ();
958   skm = &kx->skm;
959   skm->header.size = htons (sizeof (struct SetKeyMessage));
960   skm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
961   skm->purpose.size =
962       htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
963              sizeof (struct GNUNET_TIME_AbsoluteNBO) +
964              sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
965              sizeof (struct GNUNET_PeerIdentity));
966   skm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
967   skm->creation_time = GNUNET_TIME_absolute_hton (kx->encrypt_key_created);
968   skm->target = kx->peer;
969   GNUNET_assert (GNUNET_OK ==
970                  GNUNET_CRYPTO_rsa_encrypt (&kx->encrypt_key,
971                                             sizeof (struct
972                                                     GNUNET_CRYPTO_AesSessionKey),
973                                             kx->public_key,
974                                             &skm->encrypted_key));
975   GNUNET_assert (GNUNET_OK ==
976                  GNUNET_CRYPTO_rsa_sign (my_private_key, &skm->purpose,
977                                          &skm->signature));
978 }
979
980
981 /**
982  * Create a fresh PING message for transmission to the other peer.
983  *
984  * @param kx key exchange context to create PING for
985  */
986 static void
987 setup_fresh_ping (struct GSC_KeyExchangeInfo *kx)
988 {
989   struct PingMessage pp;
990   struct PingMessage *pm;
991   struct GNUNET_CRYPTO_AesInitializationVector iv;
992
993   pm = &kx->ping;
994   pm->header.size = htons (sizeof (struct PingMessage));
995   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
996   pm->iv_seed =
997       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
998   derive_iv (&iv, &kx->encrypt_key, pm->iv_seed, &kx->peer);
999   pp.challenge = kx->ping_challenge;
1000   pp.target = kx->peer;
1001   do_encrypt (kx, &iv, &pp.target, &pm->target,
1002               sizeof (struct PingMessage) - ((void *) &pm->target -
1003                                              (void *) pm));
1004 }
1005
1006
1007 /**
1008  * Task triggered when a neighbour entry is about to time out
1009  * (and we should prevent this by sending a PING).
1010  *
1011  * @param cls the 'struct GSC_KeyExchangeInfo'
1012  * @param tc scheduler context (not used)
1013  */
1014 static void
1015 send_keep_alive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1016 {
1017   struct GSC_KeyExchangeInfo *kx = cls;
1018   struct GNUNET_TIME_Relative retry;
1019   struct GNUNET_TIME_Relative left;
1020
1021   kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1022   left = GNUNET_TIME_absolute_get_remaining (kx->timeout);
1023   if (left.rel_value == 0)
1024   {
1025     GNUNET_STATISTICS_update (GSC_stats,
1026                               gettext_noop ("# sessions terminated by timeout"),
1027                               1, GNUNET_NO);
1028     GSC_SESSIONS_end (&kx->peer);
1029     kx->status = KX_STATE_DOWN;
1030     return;
1031   }
1032 #if DEBUG_CORE
1033   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending KEEPALIVE to `%s'\n",
1034               GNUNET_i2s (&kx->peer));
1035 #endif
1036   GNUNET_STATISTICS_update (GSC_stats,
1037                             gettext_noop ("# keepalive messages sent"), 1,
1038                             GNUNET_NO);
1039   setup_fresh_ping (kx);
1040   GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
1041                            kx->set_key_retry_frequency);
1042   retry =
1043       GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1044                                 MIN_PING_FREQUENCY);
1045   kx->keep_alive_task =
1046       GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx);
1047 }
1048
1049
1050 /**
1051  * We've seen a valid message from the other peer.
1052  * Update the time when the session would time out
1053  * and delay sending our keep alive message further.
1054  *
1055  * @param kx key exchange where we saw activity
1056  */
1057 static void
1058 update_timeout (struct GSC_KeyExchangeInfo *kx)
1059 {
1060   kx->timeout =
1061       GNUNET_TIME_relative_to_absolute
1062       (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1063   if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1064     GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1065   kx->keep_alive_task =
1066       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
1067                                     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1068                                      2), &send_keep_alive, kx);
1069 }
1070
1071
1072 /**
1073  * We received a PONG message.  Validate and update our status.
1074  *
1075  * @param kx key exchange context for the the PONG
1076  * @param msg the encrypted PONG message itself
1077  */
1078 void
1079 GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx,
1080                     const struct GNUNET_MessageHeader *msg)
1081 {
1082   const struct PongMessage *m;
1083   struct PongMessage t;
1084   struct EncryptedMessage *emsg;
1085   struct GNUNET_CRYPTO_AesInitializationVector iv;
1086   uint16_t msize;
1087
1088   msize = ntohs (msg->size);
1089   if (msize != sizeof (struct PongMessage))
1090   {
1091     GNUNET_break_op (0);
1092     return;
1093   }
1094   GNUNET_STATISTICS_update (GSC_stats,
1095                             gettext_noop ("# PONG messages received"), 1,
1096                             GNUNET_NO);
1097   if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP))
1098   {
1099     if (kx->status == KX_STATE_KEY_SENT)
1100     {
1101       GNUNET_free_non_null (kx->pong_received);
1102       kx->pong_received = (struct PongMessage *) GNUNET_copy_message (msg);
1103     }
1104     return;
1105   }
1106   m = (const struct PongMessage *) msg;
1107 #if DEBUG_HANDSHAKE
1108   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1109               "Core service receives `%s' response from `%4s'.\n", "PONG",
1110               GNUNET_i2s (&kx->peer));
1111 #endif
1112   /* mark as garbage, just to be sure */
1113   memset (&t, 255, sizeof (t));
1114   derive_pong_iv (&iv, &kx->decrypt_key, m->iv_seed, kx->ping_challenge,
1115                   &GSC_my_identity);
1116   if (GNUNET_OK !=
1117       do_decrypt (kx, &iv, &m->challenge, &t.challenge,
1118                   sizeof (struct PongMessage) - ((void *) &m->challenge -
1119                                                  (void *) m)))
1120   {
1121     GNUNET_break_op (0);
1122     return;
1123   }
1124   GNUNET_STATISTICS_update (GSC_stats,
1125                             gettext_noop ("# PONG messages decrypted"), 1,
1126                             GNUNET_NO);
1127   if ((0 != memcmp (&t.target, &kx->peer, sizeof (struct GNUNET_PeerIdentity)))
1128       || (kx->ping_challenge != t.challenge))
1129   {
1130     /* PONG malformed */
1131 #if DEBUG_CORE
1132     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1133                 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
1134                 "PONG", GNUNET_i2s (&kx->peer),
1135                 (unsigned int) kx->ping_challenge);
1136     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1137                 "Received malformed `%s' received from `%4s' with challenge %u\n",
1138                 "PONG", GNUNET_i2s (&t.target), (unsigned int) t.challenge);
1139 #endif
1140     return;
1141   }
1142 #if DEBUG_CORE
1143   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PONG from `%s'\n",
1144               GNUNET_i2s (&kx->peer));
1145 #endif
1146   switch (kx->status)
1147   {
1148   case KX_STATE_DOWN:
1149     GNUNET_break (0);           /* should be impossible */
1150     return;
1151   case KX_STATE_KEY_SENT:
1152     GNUNET_break (0);           /* should be impossible */
1153     return;
1154   case KX_STATE_KEY_RECEIVED:
1155     GNUNET_STATISTICS_update (GSC_stats,
1156                               gettext_noop
1157                               ("# session keys confirmed via PONG"), 1,
1158                               GNUNET_NO);
1159     kx->status = KX_STATE_UP;
1160     GSC_SESSIONS_create (&kx->peer, kx);
1161     if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
1162     {
1163       GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1164       kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1165     }
1166     GNUNET_assert (kx->keep_alive_task == GNUNET_SCHEDULER_NO_TASK);
1167     if (kx->emsg_received != NULL)
1168     {
1169       emsg = kx->emsg_received;
1170       kx->emsg_received = NULL;
1171       GSC_KX_handle_encrypted_message (kx, &emsg->header, NULL,
1172                                        0 /* FIXME: ATSI */ );
1173       GNUNET_free (emsg);
1174     }
1175     update_timeout (kx);
1176     break;
1177   case KX_STATE_UP:
1178     update_timeout (kx);
1179     break;
1180   default:
1181     GNUNET_break (0);
1182     break;
1183   }
1184 }
1185
1186
1187 /**
1188  * Send our key (and encrypted PING) to the other peer.
1189  *
1190  * @param kx key exchange context
1191  */
1192 static void
1193 send_key (struct GSC_KeyExchangeInfo *kx)
1194 {
1195   GNUNET_assert (kx->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK);
1196   if (KX_STATE_UP == kx->status)
1197     return;                     /* nothing to do */
1198   if (kx->public_key == NULL)
1199   {
1200     /* lookup public key, then try again */
1201 #if DEBUG_CORE
1202     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1203                 "Trying to obtain public key for `%s'\n",
1204                 GNUNET_i2s (&kx->peer));
1205 #endif
1206     kx->pitr =
1207         GNUNET_PEERINFO_iterate (peerinfo, &kx->peer,
1208                                  GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */ ,
1209                                  &process_hello, kx);
1210     return;
1211   }
1212
1213   /* update status */
1214   switch (kx->status)
1215   {
1216   case KX_STATE_DOWN:
1217     kx->status = KX_STATE_KEY_SENT;
1218     /* setup SET KEY message */
1219     setup_fresh_setkey (kx);
1220     setup_fresh_ping (kx);
1221     GNUNET_STATISTICS_update (GSC_stats,
1222                               gettext_noop
1223                               ("# SET_KEY and PING messages created"), 1,
1224                               GNUNET_NO);
1225     break;
1226   case KX_STATE_KEY_SENT:
1227     break;
1228   case KX_STATE_KEY_RECEIVED:
1229     break;
1230   case KX_STATE_UP:
1231     GNUNET_break (0);
1232     return;
1233   default:
1234     GNUNET_break (0);
1235     return;
1236   }
1237
1238   /* always update sender status in SET KEY message */
1239   kx->skm.sender_status = htonl ((int32_t) kx->status);
1240 #if DEBUG_CORE
1241   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending SET_KEY and PING to `%s'\n",
1242               GNUNET_i2s (&kx->peer));
1243 #endif
1244   GSC_NEIGHBOURS_transmit (&kx->peer, &kx->skm.header,
1245                            kx->set_key_retry_frequency);
1246   GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
1247                            kx->set_key_retry_frequency);
1248   kx->retry_set_key_task =
1249       GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
1250                                     &set_key_retry_task, kx);
1251 }
1252
1253
1254 /**
1255  * Encrypt and transmit a message with the given payload.
1256  *
1257  * @param kx key exchange context
1258  * @param payload payload of the message
1259  * @param payload_size number of bytes in 'payload'
1260  */
1261 void
1262 GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
1263                              const void *payload, size_t payload_size)
1264 {
1265   size_t used = payload_size + sizeof (struct EncryptedMessage);
1266   char pbuf[used];              /* plaintext */
1267   char cbuf[used];              /* ciphertext */
1268   struct EncryptedMessage *em;  /* encrypted message */
1269   struct EncryptedMessage *ph;  /* plaintext header */
1270   struct GNUNET_CRYPTO_AesInitializationVector iv;
1271   struct GNUNET_CRYPTO_AuthKey auth_key;
1272
1273   ph = (struct EncryptedMessage *) pbuf;
1274   ph->iv_seed =
1275       htonl (GNUNET_CRYPTO_random_u32
1276              (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
1277   ph->sequence_number = htonl (++kx->last_sequence_number_sent);
1278   ph->reserved = GNUNET_BANDWIDTH_VALUE_MAX;
1279   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1280   memcpy (&ph[1], payload, payload_size);
1281
1282   em = (struct EncryptedMessage *) cbuf;
1283   em->header.size = htons (used);
1284   em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1285   em->iv_seed = ph->iv_seed;
1286   derive_iv (&iv, &kx->encrypt_key, ph->iv_seed, &kx->peer);
1287   GNUNET_assert (GNUNET_OK ==
1288                  do_encrypt (kx, &iv, &ph->sequence_number,
1289                              &em->sequence_number,
1290                              used - ENCRYPTED_HEADER_SIZE));
1291 #if DEBUG_CORE
1292   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Encrypted %u bytes for %s\n",
1293               used - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1294 #endif
1295   derive_auth_key (&auth_key, &kx->encrypt_key, ph->iv_seed,
1296                    kx->encrypt_key_created);
1297   GNUNET_CRYPTO_hmac (&auth_key, &em->sequence_number,
1298                       used - ENCRYPTED_HEADER_SIZE, &em->hmac);
1299   GSC_NEIGHBOURS_transmit (&kx->peer, &em->header,
1300                            GNUNET_TIME_UNIT_FOREVER_REL);
1301 }
1302
1303
1304 /**
1305  * Closure for 'deliver_message'
1306  */
1307 struct DeliverMessageContext
1308 {
1309
1310   /**
1311    * Performance information for the connection.
1312    */
1313   const struct GNUNET_ATS_Information *atsi;
1314
1315   /**
1316    * Sender of the message.
1317    */
1318   const struct GNUNET_PeerIdentity *peer;
1319
1320   /**
1321    * Number of entries in 'atsi' array.
1322    */
1323   uint32_t atsi_count;
1324 };
1325
1326
1327 /**
1328  * We received an encrypted message.  Decrypt, validate and
1329  * pass on to the appropriate clients.
1330  *
1331  * @param kx key exchange context for encrypting the message
1332  * @param msg encrypted message
1333  * @param atsi performance data
1334  * @param atsi_count number of entries in ats (excluding 0-termination)
1335  */
1336 void
1337 GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *kx,
1338                                  const struct GNUNET_MessageHeader *msg,
1339                                  const struct GNUNET_ATS_Information *atsi,
1340                                  uint32_t atsi_count)
1341 {
1342   const struct EncryptedMessage *m;
1343   struct EncryptedMessage *pt;  /* plaintext */
1344   GNUNET_HashCode ph;
1345   uint32_t snum;
1346   struct GNUNET_TIME_Absolute t;
1347   struct GNUNET_CRYPTO_AesInitializationVector iv;
1348   struct GNUNET_CRYPTO_AuthKey auth_key;
1349   struct DeliverMessageContext dmc;
1350   uint16_t size = ntohs (msg->size);
1351   char buf[size];
1352
1353   if (size <
1354       sizeof (struct EncryptedMessage) + sizeof (struct GNUNET_MessageHeader))
1355   {
1356     GNUNET_break_op (0);
1357     return;
1358   }
1359   m = (const struct EncryptedMessage *) msg;
1360   if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP))
1361   {
1362     GNUNET_STATISTICS_update (GSC_stats,
1363                               gettext_noop
1364                               ("# failed to decrypt message (no session key)"),
1365                               1, GNUNET_NO);
1366     return;
1367   }
1368   if (kx->status == KX_STATE_KEY_RECEIVED)
1369   {
1370     /* defer */
1371     GNUNET_free_non_null (kx->ping_received);
1372     kx->emsg_received = (struct EncryptedMessage *) GNUNET_copy_message (msg);
1373     return;
1374   }
1375   /* validate hash */
1376   derive_auth_key (&auth_key, &kx->decrypt_key, m->iv_seed,
1377                    kx->decrypt_key_created);
1378   GNUNET_CRYPTO_hmac (&auth_key, &m->sequence_number,
1379                       size - ENCRYPTED_HEADER_SIZE, &ph);
1380   if (0 != memcmp (&ph, &m->hmac, sizeof (GNUNET_HashCode)))
1381   {
1382     /* checksum failed */
1383     GNUNET_break_op (0);
1384     return;
1385   }
1386   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
1387   /* decrypt */
1388   if (GNUNET_OK !=
1389       do_decrypt (kx, &iv, &m->sequence_number, &buf[ENCRYPTED_HEADER_SIZE],
1390                   size - ENCRYPTED_HEADER_SIZE))
1391     return;
1392 #if DEBUG_CORE
1393   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypted %u bytes from %s\n",
1394               size - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1395 #endif
1396   pt = (struct EncryptedMessage *) buf;
1397
1398   /* validate sequence number */
1399   snum = ntohl (pt->sequence_number);
1400   if (kx->last_sequence_number_received == snum)
1401   {
1402     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1403                 "Received duplicate message, ignoring.\n");
1404     /* duplicate, ignore */
1405     GNUNET_STATISTICS_update (GSC_stats,
1406                               gettext_noop ("# bytes dropped (duplicates)"),
1407                               size, GNUNET_NO);
1408     return;
1409   }
1410   if ((kx->last_sequence_number_received > snum) &&
1411       (kx->last_sequence_number_received - snum > 32))
1412   {
1413     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1414                 "Received ancient out of sequence message, ignoring.\n");
1415     /* ancient out of sequence, ignore */
1416     GNUNET_STATISTICS_update (GSC_stats,
1417                               gettext_noop
1418                               ("# bytes dropped (out of sequence)"), size,
1419                               GNUNET_NO);
1420     return;
1421   }
1422   if (kx->last_sequence_number_received > snum)
1423   {
1424     unsigned int rotbit = 1 << (kx->last_sequence_number_received - snum - 1);
1425
1426     if ((kx->last_packets_bitmap & rotbit) != 0)
1427     {
1428       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1429                   "Received duplicate message, ignoring.\n");
1430       GNUNET_STATISTICS_update (GSC_stats,
1431                                 gettext_noop ("# bytes dropped (duplicates)"),
1432                                 size, GNUNET_NO);
1433       /* duplicate, ignore */
1434       return;
1435     }
1436     kx->last_packets_bitmap |= rotbit;
1437   }
1438   if (kx->last_sequence_number_received < snum)
1439   {
1440     unsigned int shift = (snum - kx->last_sequence_number_received);
1441
1442     if (shift >= 8 * sizeof (kx->last_packets_bitmap))
1443       kx->last_packets_bitmap = 0;
1444     else
1445       kx->last_packets_bitmap <<= shift;
1446     kx->last_sequence_number_received = snum;
1447   }
1448
1449   /* check timestamp */
1450   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
1451   if (GNUNET_TIME_absolute_get_duration (t).rel_value >
1452       MAX_MESSAGE_AGE.rel_value)
1453   {
1454     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1455                 _("Message received far too old (%llu ms). Content ignored.\n"),
1456                 GNUNET_TIME_absolute_get_duration (t).rel_value);
1457     GNUNET_STATISTICS_update (GSC_stats,
1458                               gettext_noop
1459                               ("# bytes dropped (ancient message)"), size,
1460                               GNUNET_NO);
1461     return;
1462   }
1463
1464   /* process decrypted message(s) */
1465   update_timeout (kx);
1466   GNUNET_STATISTICS_update (GSC_stats,
1467                             gettext_noop ("# bytes of payload decrypted"),
1468                             size - sizeof (struct EncryptedMessage), GNUNET_NO);
1469   dmc.atsi = atsi;
1470   dmc.atsi_count = atsi_count;
1471   dmc.peer = &kx->peer;
1472   if (GNUNET_OK !=
1473       GNUNET_SERVER_mst_receive (mst, &dmc,
1474                                  &buf[sizeof (struct EncryptedMessage)],
1475                                  size - sizeof (struct EncryptedMessage),
1476                                  GNUNET_YES, GNUNET_NO))
1477     GNUNET_break_op (0);
1478 }
1479
1480
1481 /**
1482  * Deliver P2P message to interested clients.
1483  * Invokes send twice, once for clients that want the full message, and once
1484  * for clients that only want the header
1485  *
1486  * @param cls always NULL
1487  * @param client who sent us the message (struct GSC_KeyExchangeInfo)
1488  * @param m the message
1489  */
1490 static void
1491 deliver_message (void *cls, void *client, const struct GNUNET_MessageHeader *m)
1492 {
1493   struct DeliverMessageContext *dmc = client;
1494
1495   switch (ntohs (m->type))
1496   {
1497   case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP:
1498   case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP:
1499     GSC_SESSIONS_set_typemap (dmc->peer, m);
1500     return;
1501   default:
1502     GSC_CLIENTS_deliver_message (dmc->peer, dmc->atsi, dmc->atsi_count, m,
1503                                  ntohs (m->size),
1504                                  GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
1505     GSC_CLIENTS_deliver_message (dmc->peer, dmc->atsi, dmc->atsi_count, m,
1506                                  sizeof (struct GNUNET_MessageHeader),
1507                                  GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
1508   }
1509 }
1510
1511
1512 /**
1513  * Initialize KX subsystem.
1514  *
1515  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1516  */
1517 int
1518 GSC_KX_init ()
1519 {
1520   char *keyfile;
1521
1522   if (GNUNET_OK !=
1523       GNUNET_CONFIGURATION_get_value_filename (GSC_cfg, "GNUNETD", "HOSTKEY",
1524                                                &keyfile))
1525   {
1526     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1527                 _
1528                 ("Core service is lacking HOSTKEY configuration setting.  Exiting.\n"));
1529     return GNUNET_SYSERR;
1530   }
1531   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1532   GNUNET_free (keyfile);
1533   if (my_private_key == NULL)
1534   {
1535     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1536                 _("Core service could not access hostkey.  Exiting.\n"));
1537     return GNUNET_SYSERR;
1538   }
1539   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1540   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1541                       &GSC_my_identity.hashPubKey);
1542   peerinfo = GNUNET_PEERINFO_connect (GSC_cfg);
1543   if (NULL == peerinfo)
1544   {
1545     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1546                 _("Could not access PEERINFO service.  Exiting.\n"));
1547     GNUNET_CRYPTO_rsa_key_free (my_private_key);
1548     my_private_key = NULL;
1549     return GNUNET_SYSERR;
1550   }
1551   mst = GNUNET_SERVER_mst_create (&deliver_message, NULL);
1552   return GNUNET_OK;
1553 }
1554
1555
1556 /**
1557  * Shutdown KX subsystem.
1558  */
1559 void
1560 GSC_KX_done ()
1561 {
1562   if (my_private_key != NULL)
1563   {
1564     GNUNET_CRYPTO_rsa_key_free (my_private_key);
1565     my_private_key = NULL;
1566   }
1567   if (peerinfo != NULL)
1568   {
1569     GNUNET_PEERINFO_disconnect (peerinfo);
1570     peerinfo = NULL;
1571   }
1572   if (mst != NULL)
1573   {
1574     GNUNET_SERVER_mst_destroy (mst);
1575     mst = NULL;
1576   }
1577 }
1578
1579 /* end of gnunet-service-core_kx.c */