2 This file is part of GNUnet.
3 (C) 2009, 2010, 2011, 2012 Christian Grothoff (and other contributing authors)
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.
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.
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.
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
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"
42 * Set to GNUNET_YES to perform some slightly expensive internal invariant checks.
44 #define EXTRA_CHECKS GNUNET_YES
47 * How long do we wait for SET_KEY confirmation initially?
49 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
52 * What is the minimum frequency for a PING message?
54 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
57 * How often do we rekey?
59 #define REKEY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 90)
63 * What is the maximum age of a message for us to consider processing
64 * it? Note that this looks at the timestamp used by the other peer,
65 * so clock skew between machines does come into play here. So this
66 * should be picked high enough so that a little bit of clock skew
67 * does not prevent peers from connecting to us.
69 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
72 * What is the maximum delay for a SET_KEY message?
74 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
77 GNUNET_NETWORK_STRUCT_BEGIN
80 * We're sending an (encrypted) PING to the other peer to check if he
81 * can decrypt. The other peer should respond with a PONG with the
82 * same content, except this time encrypted with the receiver's key.
87 * Message type is CORE_PING.
89 struct GNUNET_MessageHeader header;
94 uint32_t iv_seed GNUNET_PACKED;
97 * Intended target of the PING, used primarily to check
98 * that decryption actually worked.
100 struct GNUNET_PeerIdentity target;
103 * Random number chosen to make reply harder.
105 uint32_t challenge GNUNET_PACKED;
110 * Response to a PING. Includes data from the original PING.
115 * Message type is CORE_PONG.
117 struct GNUNET_MessageHeader header;
122 uint32_t iv_seed GNUNET_PACKED;
125 * Random number to make faking the reply harder. Must be
126 * first field after header (this is where we start to encrypt!).
128 uint32_t challenge GNUNET_PACKED;
131 * Reserved, always 'GNUNET_BANDWIDTH_VALUE_MAX'.
133 struct GNUNET_BANDWIDTH_Value32NBO reserved;
136 * Intended target of the PING, used primarily to check
137 * that decryption actually worked.
139 struct GNUNET_PeerIdentity target;
144 * Message transmitted to set (or update) a session key.
150 * Message type is either CORE_SET_KEY.
152 struct GNUNET_MessageHeader header;
155 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
157 int32_t sender_status GNUNET_PACKED;
160 * Purpose of the signature, will be
161 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
163 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
166 * At what time was this key created?
168 struct GNUNET_TIME_AbsoluteNBO creation_time;
171 * The encrypted session key.
173 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
176 * Who is the intended recipient?
178 struct GNUNET_PeerIdentity target;
181 * Signature of the stuff above (starting at purpose).
183 struct GNUNET_CRYPTO_RsaSignature signature;
189 * Encapsulation for encrypted messages exchanged between
190 * peers. Followed by the actual encrypted data.
192 struct EncryptedMessage
195 * Message type is either CORE_ENCRYPTED_MESSAGE.
197 struct GNUNET_MessageHeader header;
200 * Random value used for IV generation.
202 uint32_t iv_seed GNUNET_PACKED;
205 * MAC of the encrypted message (starting at 'sequence_number'),
206 * used to verify message integrity. Everything after this value
207 * (excluding this value itself) will be encrypted and authenticated.
208 * ENCRYPTED_HEADER_SIZE must be set to the offset of the *next* field.
210 struct GNUNET_HashCode hmac;
213 * Sequence number, in network byte order. This field
214 * must be the first encrypted/decrypted field
216 uint32_t sequence_number GNUNET_PACKED;
219 * Reserved, always 'GNUNET_BANDWIDTH_VALUE_MAX'.
221 struct GNUNET_BANDWIDTH_Value32NBO reserved;
224 * Timestamp. Used to prevent reply of ancient messages
225 * (recent messages are caught with the sequence number).
227 struct GNUNET_TIME_AbsoluteNBO timestamp;
230 GNUNET_NETWORK_STRUCT_END
234 * Number of bytes (at the beginning) of "struct EncryptedMessage"
235 * that are NOT encrypted.
237 #define ENCRYPTED_HEADER_SIZE (offsetof(struct EncryptedMessage, sequence_number))
241 * State machine for our P2P encryption handshake. Everyone starts in
242 * "DOWN", if we receive the other peer's key (other peer initiated)
243 * we start in state RECEIVED (since we will immediately send our
244 * own); otherwise we start in SENT. If we get back a PONG from
245 * within either state, we move up to CONFIRMED (the PONG will always
246 * be sent back encrypted with the key we sent to the other peer).
256 * We've sent our session key.
261 * We've received the other peers session key.
263 KX_STATE_KEY_RECEIVED,
266 * The other peer has confirmed our session key with a message
267 * encrypted with his session key (which we got). Key exchange
273 * We're rekeying, so we have received the other peer's session
274 * key, but he didn't get ours yet.
279 * We're rekeying but have not yet received confirmation for our new
280 * key from the other peer.
287 * Information about the status of a key exchange with another peer.
289 struct GSC_KeyExchangeInfo
292 * Identity of the peer.
294 struct GNUNET_PeerIdentity peer;
297 * SetKeyMessage to transmit (initialized the first
298 * time our status goes past 'KX_STATE_KEY_SENT').
300 struct SetKeyMessage skm;
303 * PING message we transmit to the other peer.
305 struct PingMessage ping;
308 * SetKeyMessage we received and did not process yet.
310 struct SetKeyMessage *skm_received;
313 * PING message we received from the other peer and
314 * did not process yet (or NULL).
316 struct PingMessage *ping_received;
319 * PONG message we received from the other peer and
320 * did not process yet (or NULL).
322 struct PongMessage *pong_received;
325 * Encrypted message we received from the other peer and
326 * did not process yet (or NULL).
328 struct EncryptedMessage *emsg_received;
331 * Non-NULL if we are currently looking up HELLOs for this peer.
334 struct GNUNET_PEERINFO_IteratorContext *pitr;
337 * Public key of the neighbour, NULL if we don't have it yet.
339 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
342 * We received a PONG message before we got the "public_key"
343 * (or the SET_KEY). We keep it here until we have a key
344 * to decrypt it. NULL if no PONG is pending.
346 struct PongMessage *pending_pong;
349 * Key we use to encrypt our messages for the other peer
350 * (initialized by us when we do the handshake).
352 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
355 * Key we use to decrypt messages from the other peer
356 * (given to us by the other peer during the handshake).
358 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
361 * At what time did we generate our encryption key?
363 struct GNUNET_TIME_Absolute encrypt_key_created;
366 * At what time did the other peer generate the decryption key?
368 struct GNUNET_TIME_Absolute decrypt_key_created;
371 * When should the session time out (if there are no PONGs)?
373 struct GNUNET_TIME_Absolute timeout;
376 * At what frequency are we currently re-trying SET_KEY messages?
378 struct GNUNET_TIME_Relative set_key_retry_frequency;
381 * ID of task used for re-trying SET_KEY and PING message.
383 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
386 * ID of task used for sending keep-alive pings.
388 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
391 * Bit map indicating which of the 32 sequence numbers before the last
392 * were received (good for accepting out-of-order packets and
393 * estimating reliability of the connection)
395 unsigned int last_packets_bitmap;
398 * last sequence number received on this connection (highest)
400 uint32_t last_sequence_number_received;
403 * last sequence number transmitted
405 uint32_t last_sequence_number_sent;
408 * What was our PING challenge number (for this peer)?
410 uint32_t ping_challenge;
413 * What is our connection status?
415 enum KxStateMachine status;
421 * Handle to peerinfo service.
423 static struct GNUNET_PEERINFO_Handle *peerinfo;
428 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
433 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
436 * Our message stream tokenizer (for encrypted payload).
438 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
443 * Check internal invariants of the given KX record.
445 * @param kx record to check
446 * @param file filename for error reporting
447 * @param line line number for error reporting
450 check_kx_record (struct GSC_KeyExchangeInfo *kx,
454 struct GNUNET_HashCode hc;
456 if (NULL == kx->public_key)
458 GNUNET_CRYPTO_hash (kx->public_key, sizeof (*kx->public_key), &hc);
459 GNUNET_assert_at (0 == memcmp (&hc, &kx->peer, sizeof (struct GNUNET_HashCode)), file, line);
464 * Check internal invariants of the given KX record.
466 * @param kx record to check
468 #define CHECK_KX(kx) check_kx_record(kx, __FILE__, __LINE__)
474 * Derive an authentication key from "set key" information
476 * @param akey authentication key to derive
477 * @param skey session key to use
478 * @param seed seed to use
479 * @param creation_time creation time to use
482 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
483 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
484 struct GNUNET_TIME_Absolute creation_time)
486 static const char ctx[] = "authentication key";
487 struct GNUNET_TIME_AbsoluteNBO ctbe;
489 ctbe = GNUNET_TIME_absolute_hton (creation_time);
490 GNUNET_CRYPTO_hmac_derive_key (akey, skey, &seed, sizeof (seed), &skey->key,
491 sizeof (skey->key), &ctbe, sizeof (ctbe), ctx,
497 * Derive an IV from packet information
499 * @param iv initialization vector to initialize
500 * @param skey session key to use
501 * @param seed seed to use
502 * @param identity identity of the other peer to use
505 derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
506 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
507 const struct GNUNET_PeerIdentity *identity)
509 static const char ctx[] = "initialization vector";
511 GNUNET_CRYPTO_aes_derive_iv (iv, skey, &seed, sizeof (seed),
512 &identity->hashPubKey.bits,
513 sizeof (identity->hashPubKey.bits), ctx,
519 * Derive an IV from pong packet information
521 * @param iv initialization vector to initialize
522 * @param skey session key to use
523 * @param seed seed to use
524 * @param challenge nonce to use
525 * @param identity identity of the other peer to use
528 derive_pong_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
529 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
530 uint32_t challenge, const struct GNUNET_PeerIdentity *identity)
532 static const char ctx[] = "pong initialization vector";
534 GNUNET_CRYPTO_aes_derive_iv (iv, skey, &seed, sizeof (seed),
535 &identity->hashPubKey.bits,
536 sizeof (identity->hashPubKey.bits), &challenge,
537 sizeof (challenge), ctx, sizeof (ctx), NULL);
542 * Encrypt size bytes from in and write the result to out. Use the
543 * key for outbound traffic of the given neighbour.
545 * @param kx key information context
546 * @param iv initialization vector to use
547 * @param in ciphertext
548 * @param out plaintext
549 * @param size size of in/out
550 * @return GNUNET_OK on success
553 do_encrypt (struct GSC_KeyExchangeInfo *kx,
554 const struct GNUNET_CRYPTO_AesInitializationVector *iv,
555 const void *in, void *out, size_t size)
557 if (size != (uint16_t) size)
562 GNUNET_assert (size ==
563 GNUNET_CRYPTO_aes_encrypt (in, (uint16_t) size,
564 &kx->encrypt_key, iv, out));
565 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes encrypted"), size,
567 /* the following is too sensitive to write to log files by accident,
568 so we require manual intervention to get this one... */
570 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
571 "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
572 (unsigned int) size, GNUNET_i2s (&kx->peer),
573 (unsigned int) kx->encrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
582 * Decrypt size bytes from in and write the result to out. Use the
583 * key for inbound traffic of the given neighbour. This function does
584 * NOT do any integrity-checks on the result.
586 * @param kx key information context
587 * @param iv initialization vector to use
588 * @param in ciphertext
589 * @param out plaintext
590 * @param size size of in/out
591 * @return GNUNET_OK on success
594 do_decrypt (struct GSC_KeyExchangeInfo *kx,
595 const struct GNUNET_CRYPTO_AesInitializationVector *iv,
596 const void *in, void *out, size_t size)
598 if (size != (uint16_t) size)
603 if ( (kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP) &&
604 (kx->status != KX_STATE_REKEY_SENT) &&
605 (kx->status != KX_STATE_REKEY) )
608 return GNUNET_SYSERR;
611 GNUNET_CRYPTO_aes_decrypt (in, (uint16_t) size, &kx->decrypt_key, iv,
615 return GNUNET_SYSERR;
617 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes decrypted"), size,
619 /* the following is too sensitive to write to log files by accident,
620 so we require manual intervention to get this one... */
622 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
623 "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
624 (unsigned int) size, GNUNET_i2s (&kx->peer),
625 (unsigned int) kx->decrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
634 * Send our key (and encrypted PING) to the other peer.
636 * @param kx key exchange context
639 send_key (struct GSC_KeyExchangeInfo *kx);
643 * Task that will retry "send_key" if our previous attempt failed.
645 * @param cls our 'struct GSC_KeyExchangeInfo'
646 * @param tc scheduler context
649 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
651 struct GSC_KeyExchangeInfo *kx = cls;
653 kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
654 kx->set_key_retry_frequency =
655 GNUNET_TIME_relative_multiply (kx->set_key_retry_frequency, 2);
661 * PEERINFO is giving us a HELLO for a peer. Add the public key to
662 * the neighbour's struct and continue with the key exchange. Or, if
663 * we did not get a HELLO, just do nothing.
665 * @param cls the 'struct GSC_KeyExchangeInfo' to retry sending the key for
666 * @param peer the peer for which this is the HELLO
667 * @param hello HELLO message of that peer
668 * @param err_msg NULL if successful, otherwise contains error message
671 process_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
672 const struct GNUNET_HELLO_Message *hello, const char *err_msg)
674 struct GSC_KeyExchangeInfo *kx = cls;
675 struct SetKeyMessage *skm;
680 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
681 _("Error in communication with PEERINFO service\n"));
683 if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
684 GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
685 kx->retry_set_key_task =
686 GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
687 &set_key_retry_task, kx);
693 if (NULL != kx->public_key)
694 return; /* done here */
695 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
696 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
697 GNUNET_i2s (&kx->peer));
698 GNUNET_STATISTICS_update (GSC_stats,
700 ("# Delayed connecting due to lack of public key"),
702 if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
703 GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
704 kx->retry_set_key_task =
705 GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
706 &set_key_retry_task, kx);
709 GNUNET_break (0 == memcmp (peer, &kx->peer, sizeof (struct GNUNET_PeerIdentity)));
710 if (NULL != kx->public_key)
712 /* already have public key, why are we here? */
716 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->retry_set_key_task);
718 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
719 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, kx->public_key))
722 GNUNET_free (kx->public_key);
723 kx->public_key = NULL;
729 if (NULL != kx->skm_received)
731 skm = kx->skm_received;
732 kx->skm_received = NULL;
733 GSC_KX_handle_set_key (kx, &skm->header);
740 * Start the key exchange with the given peer.
742 * @param pid identity of the peer to do a key exchange with
743 * @return key exchange information context
745 struct GSC_KeyExchangeInfo *
746 GSC_KX_start (const struct GNUNET_PeerIdentity *pid)
748 struct GSC_KeyExchangeInfo *kx;
750 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Initiating key exchange with `%s'\n",
752 GNUNET_STATISTICS_update (GSC_stats,
753 gettext_noop ("# key exchanges initiated"), 1,
755 kx = GNUNET_malloc (sizeof (struct GSC_KeyExchangeInfo));
757 kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
759 GNUNET_PEERINFO_iterate (peerinfo, pid,
760 GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */ ,
768 * Stop key exchange with the given peer. Clean up key material.
770 * @param kx key exchange to stop
773 GSC_KX_stop (struct GSC_KeyExchangeInfo *kx)
775 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# key exchanges stopped"),
777 if (NULL != kx->pitr)
779 GNUNET_PEERINFO_iterate_cancel (kx->pitr);
782 if (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
784 GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
785 kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
787 if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
789 GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
790 kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
792 GNUNET_free_non_null (kx->skm_received);
793 GNUNET_free_non_null (kx->ping_received);
794 GNUNET_free_non_null (kx->pong_received);
795 GNUNET_free_non_null (kx->emsg_received);
796 GNUNET_free_non_null (kx->public_key);
802 * We received a SET_KEY message. Validate and update
803 * our key material and status.
805 * @param kx key exchange status for the corresponding peer
806 * @param msg the set key message we received
809 GSC_KX_handle_set_key (struct GSC_KeyExchangeInfo *kx,
810 const struct GNUNET_MessageHeader *msg)
812 const struct SetKeyMessage *m;
813 struct GNUNET_TIME_Absolute t;
814 struct GNUNET_CRYPTO_AesSessionKey k;
815 struct PingMessage *ping;
816 struct PongMessage *pong;
817 enum KxStateMachine sender_status;
821 size = ntohs (msg->size);
822 if (size != sizeof (struct SetKeyMessage))
827 m = (const struct SetKeyMessage *) msg;
828 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# session keys received"),
831 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
832 "Core service receives `%s' request from `%4s'.\n", "SET_KEY",
833 GNUNET_i2s (&kx->peer));
834 if (NULL == kx->public_key)
836 GNUNET_free_non_null (kx->skm_received);
837 kx->skm_received = (struct SetKeyMessage *) GNUNET_copy_message (msg);
841 memcmp (&m->target, &GSC_my_identity,
842 sizeof (struct GNUNET_PeerIdentity)))
844 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
845 _("`%s' is for `%s', not for me. Ignoring.\n"), "SET_KEY",
846 GNUNET_i2s (&m->target));
849 if ((ntohl (m->purpose.size) !=
850 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
851 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
852 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
853 sizeof (struct GNUNET_PeerIdentity)) ||
855 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY, &m->purpose,
856 &m->signature, kx->public_key)))
858 /* invalid signature */
863 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
864 if (((kx->status == KX_STATE_KEY_RECEIVED) || (kx->status == KX_STATE_UP)) &&
865 (t.abs_value < kx->decrypt_key_created.abs_value))
867 /* this could rarely happen due to massive re-ordering of
868 * messages on the network level, but is most likely either
869 * a bug or some adversary messing with us. Report. */
873 if ((GNUNET_CRYPTO_rsa_decrypt
874 (my_private_key, &m->encrypted_key, &k,
875 sizeof (struct GNUNET_CRYPTO_AesSessionKey)) !=
876 sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
877 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
879 /* failed to decrypt !? */
880 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
881 "Invalid key %x decrypted by %s from message %u (origin: %s)\n",
882 (unsigned int) GNUNET_CRYPTO_crc32_n (&k, sizeof (struct GNUNET_CRYPTO_AesSessionKey)),
883 GNUNET_i2s (&GSC_my_identity),
884 (unsigned int) GNUNET_CRYPTO_crc32_n (&m->encrypted_key, sizeof (struct GNUNET_CRYPTO_RsaEncryptedData)),
885 GNUNET_h2s (&kx->peer.hashPubKey));
889 GNUNET_STATISTICS_update (GSC_stats,
890 gettext_noop ("# SET_KEY messages decrypted"), 1,
892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received SET_KEY from `%s'\n",
893 GNUNET_i2s (&kx->peer));
895 if (kx->decrypt_key_created.abs_value != t.abs_value)
897 /* fresh key, reset sequence numbers */
898 kx->last_sequence_number_received = 0;
899 kx->last_packets_bitmap = 0;
900 kx->decrypt_key_created = t;
902 sender_status = (enum KxStateMachine) ntohl (m->sender_status);
906 kx->status = KX_STATE_KEY_RECEIVED;
907 /* we're not up, so we are already doing 'send_key' */
909 case KX_STATE_KEY_SENT:
910 kx->status = KX_STATE_KEY_RECEIVED;
911 /* we're not up, so we are already doing 'send_key' */
913 case KX_STATE_KEY_RECEIVED:
914 /* we're not up, so we are already doing 'send_key' */
917 if ((sender_status == KX_STATE_DOWN) ||
918 (sender_status == KX_STATE_KEY_SENT))
919 send_key (kx); /* we are up, but other peer is not! */
922 if ((sender_status == KX_STATE_DOWN) ||
923 (sender_status == KX_STATE_KEY_SENT))
924 send_key (kx); /* we are up, but other peer is not! */
926 case KX_STATE_REKEY_SENT:
927 if ((sender_status == KX_STATE_DOWN) ||
928 (sender_status == KX_STATE_KEY_SENT))
929 send_key (kx); /* we are up, but other peer is not! */
935 if (NULL != kx->ping_received)
937 ping = kx->ping_received;
938 kx->ping_received = NULL;
939 GSC_KX_handle_ping (kx, &ping->header);
942 if (NULL != kx->pong_received)
944 pong = kx->pong_received;
945 kx->pong_received = NULL;
946 GSC_KX_handle_pong (kx, &pong->header);
953 * We received a PING message. Validate and transmit
956 * @param kx key exchange status for the corresponding peer
957 * @param msg the encrypted PING message itself
960 GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *kx,
961 const struct GNUNET_MessageHeader *msg)
963 const struct PingMessage *m;
964 struct PingMessage t;
965 struct PongMessage tx;
966 struct PongMessage tp;
967 struct GNUNET_CRYPTO_AesInitializationVector iv;
970 msize = ntohs (msg->size);
971 if (msize != sizeof (struct PingMessage))
976 GNUNET_STATISTICS_update (GSC_stats,
977 gettext_noop ("# PING messages received"), 1,
979 if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP) &&
980 (kx->status != KX_STATE_REKEY_SENT))
983 GNUNET_free_non_null (kx->ping_received);
984 kx->ping_received = (struct PingMessage *) GNUNET_copy_message (msg);
987 m = (const struct PingMessage *) msg;
988 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
989 "Core service receives `%s' request from `%4s'.\n", "PING",
990 GNUNET_i2s (&kx->peer));
991 derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
993 do_decrypt (kx, &iv, &m->target, &t.target,
994 sizeof (struct PingMessage) - ((void *) &m->target -
1001 memcmp (&t.target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
1006 GNUNET_snprintf (sender, sizeof (sender), "%8s", GNUNET_i2s (&kx->peer));
1007 GNUNET_snprintf (peer, sizeof (peer), "%8s", GNUNET_i2s (&t.target));
1008 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1010 ("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
1011 sender, GNUNET_i2s (&GSC_my_identity), peer);
1012 GNUNET_break_op (0);
1015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PING from `%s'\n",
1016 GNUNET_i2s (&kx->peer));
1017 /* construct PONG */
1018 tx.reserved = GNUNET_BANDWIDTH_VALUE_MAX;
1019 tx.challenge = t.challenge;
1020 tx.target = t.target;
1021 tp.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
1022 tp.header.size = htons (sizeof (struct PongMessage));
1024 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1025 derive_pong_iv (&iv, &kx->encrypt_key, tp.iv_seed, t.challenge, &kx->peer);
1026 do_encrypt (kx, &iv, &tx.challenge, &tp.challenge,
1027 sizeof (struct PongMessage) - ((void *) &tp.challenge -
1029 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages created"),
1031 GSC_NEIGHBOURS_transmit (&kx->peer, &tp.header,
1032 GNUNET_TIME_UNIT_FOREVER_REL /* FIXME: timeout */ );
1037 * Create a fresh SET KEY message for transmission to the other peer.
1038 * Also creates a new key.
1040 * @param kx key exchange context to create SET KEY message for
1043 setup_fresh_setkey (struct GSC_KeyExchangeInfo *kx)
1045 struct SetKeyMessage *skm;
1047 GNUNET_CRYPTO_aes_create_session_key (&kx->encrypt_key);
1048 kx->encrypt_key_created = GNUNET_TIME_absolute_get ();
1050 skm->header.size = htons (sizeof (struct SetKeyMessage));
1051 skm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
1053 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1054 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1055 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
1056 sizeof (struct GNUNET_PeerIdentity));
1057 skm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
1058 skm->creation_time = GNUNET_TIME_absolute_hton (kx->encrypt_key_created);
1059 skm->target = kx->peer;
1061 GNUNET_assert (GNUNET_OK ==
1062 GNUNET_CRYPTO_rsa_encrypt (&kx->encrypt_key,
1064 GNUNET_CRYPTO_AesSessionKey),
1066 &skm->encrypted_key));
1067 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1068 "Encrypting key %x for %s resulting in message %u (origin: %s)\n",
1069 (unsigned int) GNUNET_CRYPTO_crc32_n (&kx->encrypt_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey)),
1070 GNUNET_i2s (&kx->peer),
1071 (unsigned int) GNUNET_CRYPTO_crc32_n (&skm->encrypted_key, sizeof (struct GNUNET_CRYPTO_RsaEncryptedData)),
1072 GNUNET_h2s (&GSC_my_identity.hashPubKey));
1074 GNUNET_assert (GNUNET_OK ==
1075 GNUNET_CRYPTO_rsa_sign (my_private_key, &skm->purpose,
1081 * Create a fresh PING message for transmission to the other peer.
1083 * @param kx key exchange context to create PING for
1086 setup_fresh_ping (struct GSC_KeyExchangeInfo *kx)
1088 struct PingMessage pp;
1089 struct PingMessage *pm;
1090 struct GNUNET_CRYPTO_AesInitializationVector iv;
1093 pm->header.size = htons (sizeof (struct PingMessage));
1094 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1096 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1097 derive_iv (&iv, &kx->encrypt_key, pm->iv_seed, &kx->peer);
1098 pp.challenge = kx->ping_challenge;
1099 pp.target = kx->peer;
1100 do_encrypt (kx, &iv, &pp.target, &pm->target,
1101 sizeof (struct PingMessage) - ((void *) &pm->target -
1107 * Task triggered when a neighbour entry is about to time out
1108 * (and we should prevent this by sending a PING).
1110 * @param cls the 'struct GSC_KeyExchangeInfo'
1111 * @param tc scheduler context (not used)
1114 send_keep_alive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1116 struct GSC_KeyExchangeInfo *kx = cls;
1117 struct GNUNET_TIME_Relative retry;
1118 struct GNUNET_TIME_Relative left;
1120 kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1121 left = GNUNET_TIME_absolute_get_remaining (kx->timeout);
1122 if (0 == left.rel_value)
1124 GNUNET_STATISTICS_update (GSC_stats,
1125 gettext_noop ("# sessions terminated by timeout"),
1127 GSC_SESSIONS_end (&kx->peer);
1128 kx->status = KX_STATE_DOWN;
1132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending KEEPALIVE to `%s'\n",
1133 GNUNET_i2s (&kx->peer));
1134 GNUNET_STATISTICS_update (GSC_stats,
1135 gettext_noop ("# keepalive messages sent"), 1,
1137 setup_fresh_ping (kx);
1138 GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
1139 kx->set_key_retry_frequency);
1141 GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1142 MIN_PING_FREQUENCY);
1143 kx->keep_alive_task =
1144 GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx);
1149 * We've seen a valid message from the other peer.
1150 * Update the time when the session would time out
1151 * and delay sending our keep alive message further.
1153 * @param kx key exchange where we saw activity
1156 update_timeout (struct GSC_KeyExchangeInfo *kx)
1159 GNUNET_TIME_relative_to_absolute
1160 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1161 if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1162 GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1163 kx->keep_alive_task =
1164 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
1165 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1166 2), &send_keep_alive, kx);
1171 * Trigger rekeying event.
1173 * @param cls the 'struct GSC_KeyExchangeInfo'
1174 * @param tc schedule context (unused)
1177 trigger_rekey (void *cls,
1178 const struct GNUNET_SCHEDULER_TaskContext *tc)
1180 struct GSC_KeyExchangeInfo *kx = cls;
1182 GNUNET_break (KX_STATE_UP == kx->status);
1183 kx->status = KX_STATE_REKEY;
1184 kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
1185 kx->retry_set_key_task =
1186 GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
1187 &set_key_retry_task, kx);
1192 * Schedule rekey operation.
1194 * @param kx key exchange to schedule rekey for
1197 schedule_rekey (struct GSC_KeyExchangeInfo *kx)
1199 struct GNUNET_TIME_Relative rdelay;
1201 if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
1202 GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1203 rdelay = REKEY_FREQUENCY;
1204 /* randomize rekey frequency by one minute to avoid synchronization */
1205 rdelay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1207 kx->retry_set_key_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY,
1214 * We received a PONG message. Validate and update our status.
1216 * @param kx key exchange context for the the PONG
1217 * @param msg the encrypted PONG message itself
1220 GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx,
1221 const struct GNUNET_MessageHeader *msg)
1223 const struct PongMessage *m;
1224 struct PongMessage t;
1225 struct EncryptedMessage *emsg;
1226 struct GNUNET_CRYPTO_AesInitializationVector iv;
1229 msize = ntohs (msg->size);
1230 if (sizeof (struct PongMessage) != msize)
1232 GNUNET_break_op (0);
1235 GNUNET_STATISTICS_update (GSC_stats,
1236 gettext_noop ("# PONG messages received"), 1,
1242 case KX_STATE_KEY_SENT:
1243 GNUNET_free_non_null (kx->pong_received);
1244 kx->pong_received = (struct PongMessage *) GNUNET_copy_message (msg);
1246 case KX_STATE_KEY_RECEIVED:
1250 case KX_STATE_REKEY:
1252 case KX_STATE_REKEY_SENT:
1258 m = (const struct PongMessage *) msg;
1259 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1260 "Core service receives `%s' response from `%4s'.\n", "PONG",
1261 GNUNET_i2s (&kx->peer));
1262 /* mark as garbage, just to be sure */
1263 memset (&t, 255, sizeof (t));
1264 derive_pong_iv (&iv, &kx->decrypt_key, m->iv_seed, kx->ping_challenge,
1267 do_decrypt (kx, &iv, &m->challenge, &t.challenge,
1268 sizeof (struct PongMessage) - ((void *) &m->challenge -
1271 GNUNET_break_op (0);
1274 GNUNET_STATISTICS_update (GSC_stats,
1275 gettext_noop ("# PONG messages decrypted"), 1,
1277 if ((0 != memcmp (&t.target, &kx->peer, sizeof (struct GNUNET_PeerIdentity)))
1278 || (kx->ping_challenge != t.challenge))
1280 /* PONG malformed */
1281 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1282 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
1283 "PONG", GNUNET_i2s (&kx->peer),
1284 (unsigned int) kx->ping_challenge);
1285 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1286 "Received malformed `%s' received from `%4s' with challenge %u\n",
1287 "PONG", GNUNET_i2s (&t.target), (unsigned int) t.challenge);
1290 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PONG from `%s'\n",
1291 GNUNET_i2s (&kx->peer));
1295 GNUNET_break (0); /* should be impossible */
1297 case KX_STATE_KEY_SENT:
1298 GNUNET_break (0); /* should be impossible */
1300 case KX_STATE_KEY_RECEIVED:
1301 GNUNET_STATISTICS_update (GSC_stats,
1303 ("# session keys confirmed via PONG"), 1,
1305 kx->status = KX_STATE_UP;
1306 GSC_SESSIONS_create (&kx->peer, kx);
1308 schedule_rekey (kx);
1309 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->keep_alive_task);
1310 if (NULL != kx->emsg_received)
1312 emsg = kx->emsg_received;
1313 kx->emsg_received = NULL;
1314 GSC_KX_handle_encrypted_message (kx, &emsg->header, NULL,
1315 0 /* FIXME: ATSI */ );
1318 update_timeout (kx);
1321 update_timeout (kx);
1323 case KX_STATE_REKEY:
1324 update_timeout (kx);
1326 case KX_STATE_REKEY_SENT:
1327 GNUNET_STATISTICS_update (GSC_stats,
1329 ("# rekey operations confirmed via PONG"), 1,
1331 kx->status = KX_STATE_UP;
1332 schedule_rekey (kx);
1333 update_timeout (kx);
1343 * Send our key (and encrypted PING) to the other peer.
1345 * @param kx key exchange context
1348 send_key (struct GSC_KeyExchangeInfo *kx)
1351 if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
1353 GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1354 kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1356 if (KX_STATE_UP == kx->status)
1357 return; /* nothing to do */
1358 if (NULL == kx->public_key)
1360 if (NULL != kx->pitr)
1362 /* lookup public key, then try again */
1363 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1364 "Trying to obtain public key for `%s'\n",
1365 GNUNET_i2s (&kx->peer));
1367 GNUNET_PEERINFO_iterate (peerinfo, &kx->peer,
1368 GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */ ,
1369 &process_hello, kx);
1377 kx->status = KX_STATE_KEY_SENT;
1378 /* setup SET KEY message */
1379 setup_fresh_setkey (kx);
1380 setup_fresh_ping (kx);
1381 GNUNET_STATISTICS_update (GSC_stats,
1383 ("# SET_KEY and PING messages created"), 1,
1386 case KX_STATE_KEY_SENT:
1388 case KX_STATE_KEY_RECEIVED:
1393 case KX_STATE_REKEY:
1394 kx->status = KX_STATE_REKEY_SENT;
1395 /* setup fresh SET KEY message */
1396 setup_fresh_setkey (kx);
1397 setup_fresh_ping (kx);
1398 GNUNET_STATISTICS_update (GSC_stats,
1400 ("# SET_KEY and PING messages created"), 1,
1402 GNUNET_STATISTICS_update (GSC_stats,
1404 ("# REKEY operations performed"), 1,
1407 case KX_STATE_REKEY_SENT:
1414 /* always update sender status in SET KEY message */
1415 /* Not sending rekey sent state to be compatible with GNUnet 0.9.2 */
1416 kx->skm.sender_status = htonl ((int32_t) ((kx->status == KX_STATE_REKEY_SENT) ?
1417 KX_STATE_KEY_RECEIVED : kx->status));
1418 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending SET_KEY and PING to `%s'\n",
1419 GNUNET_i2s (&kx->peer));
1420 GSC_NEIGHBOURS_transmit (&kx->peer, &kx->skm.header,
1421 kx->set_key_retry_frequency);
1422 GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
1423 kx->set_key_retry_frequency);
1424 kx->retry_set_key_task =
1425 GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
1426 &set_key_retry_task, kx);
1431 * Encrypt and transmit a message with the given payload.
1433 * @param kx key exchange context
1434 * @param payload payload of the message
1435 * @param payload_size number of bytes in 'payload'
1438 GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
1439 const void *payload, size_t payload_size)
1441 size_t used = payload_size + sizeof (struct EncryptedMessage);
1442 char pbuf[used]; /* plaintext */
1443 char cbuf[used]; /* ciphertext */
1444 struct EncryptedMessage *em; /* encrypted message */
1445 struct EncryptedMessage *ph; /* plaintext header */
1446 struct GNUNET_CRYPTO_AesInitializationVector iv;
1447 struct GNUNET_CRYPTO_AuthKey auth_key;
1449 ph = (struct EncryptedMessage *) pbuf;
1451 htonl (GNUNET_CRYPTO_random_u32
1452 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
1453 ph->sequence_number = htonl (++kx->last_sequence_number_sent);
1454 ph->reserved = GNUNET_BANDWIDTH_VALUE_MAX;
1455 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1456 memcpy (&ph[1], payload, payload_size);
1458 em = (struct EncryptedMessage *) cbuf;
1459 em->header.size = htons (used);
1460 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1461 em->iv_seed = ph->iv_seed;
1462 derive_iv (&iv, &kx->encrypt_key, ph->iv_seed, &kx->peer);
1463 GNUNET_assert (GNUNET_OK ==
1464 do_encrypt (kx, &iv, &ph->sequence_number,
1465 &em->sequence_number,
1466 used - ENCRYPTED_HEADER_SIZE));
1467 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Encrypted %u bytes for %s\n",
1468 used - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1469 derive_auth_key (&auth_key, &kx->encrypt_key, ph->iv_seed,
1470 kx->encrypt_key_created);
1471 GNUNET_CRYPTO_hmac (&auth_key, &em->sequence_number,
1472 used - ENCRYPTED_HEADER_SIZE, &em->hmac);
1473 GSC_NEIGHBOURS_transmit (&kx->peer, &em->header,
1474 GNUNET_TIME_UNIT_FOREVER_REL);
1479 * Closure for 'deliver_message'
1481 struct DeliverMessageContext
1485 * Performance information for the connection.
1487 const struct GNUNET_ATS_Information *atsi;
1490 * Sender of the message.
1492 const struct GNUNET_PeerIdentity *peer;
1495 * Number of entries in 'atsi' array.
1497 uint32_t atsi_count;
1502 * We received an encrypted message. Decrypt, validate and
1503 * pass on to the appropriate clients.
1505 * @param kx key exchange context for encrypting the message
1506 * @param msg encrypted message
1507 * @param atsi performance data
1508 * @param atsi_count number of entries in ats (excluding 0-termination)
1511 GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *kx,
1512 const struct GNUNET_MessageHeader *msg,
1513 const struct GNUNET_ATS_Information *atsi,
1514 uint32_t atsi_count)
1516 const struct EncryptedMessage *m;
1517 struct EncryptedMessage *pt; /* plaintext */
1518 struct GNUNET_HashCode ph;
1520 struct GNUNET_TIME_Absolute t;
1521 struct GNUNET_CRYPTO_AesInitializationVector iv;
1522 struct GNUNET_CRYPTO_AuthKey auth_key;
1523 struct DeliverMessageContext dmc;
1524 uint16_t size = ntohs (msg->size);
1525 char buf[size] GNUNET_ALIGN;
1528 sizeof (struct EncryptedMessage) + sizeof (struct GNUNET_MessageHeader))
1530 GNUNET_break_op (0);
1533 m = (const struct EncryptedMessage *) msg;
1534 if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP) &&
1535 (kx->status != KX_STATE_REKEY_SENT) )
1537 GNUNET_STATISTICS_update (GSC_stats,
1539 ("# failed to decrypt message (no session key)"),
1543 if (KX_STATE_KEY_RECEIVED == kx->status)
1546 GNUNET_free_non_null (kx->emsg_received);
1547 kx->emsg_received = (struct EncryptedMessage *) GNUNET_copy_message (msg);
1551 derive_auth_key (&auth_key, &kx->decrypt_key, m->iv_seed,
1552 kx->decrypt_key_created);
1553 GNUNET_CRYPTO_hmac (&auth_key, &m->sequence_number,
1554 size - ENCRYPTED_HEADER_SIZE, &ph);
1555 if (0 != memcmp (&ph, &m->hmac, sizeof (struct GNUNET_HashCode)))
1557 /* checksum failed */
1558 GNUNET_break_op (0);
1561 derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
1564 do_decrypt (kx, &iv, &m->sequence_number, &buf[ENCRYPTED_HEADER_SIZE],
1565 size - ENCRYPTED_HEADER_SIZE))
1567 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypted %u bytes from %s\n",
1568 size - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1569 pt = (struct EncryptedMessage *) buf;
1571 /* validate sequence number */
1572 snum = ntohl (pt->sequence_number);
1573 if (kx->last_sequence_number_received == snum)
1575 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1576 "Received duplicate message, ignoring.\n");
1577 /* duplicate, ignore */
1578 GNUNET_STATISTICS_update (GSC_stats,
1579 gettext_noop ("# bytes dropped (duplicates)"),
1583 if ((kx->last_sequence_number_received > snum) &&
1584 (kx->last_sequence_number_received - snum > 32))
1586 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1587 "Received ancient out of sequence message, ignoring.\n");
1588 /* ancient out of sequence, ignore */
1589 GNUNET_STATISTICS_update (GSC_stats,
1591 ("# bytes dropped (out of sequence)"), size,
1595 if (kx->last_sequence_number_received > snum)
1597 unsigned int rotbit = 1 << (kx->last_sequence_number_received - snum - 1);
1599 if ((kx->last_packets_bitmap & rotbit) != 0)
1601 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1602 "Received duplicate message, ignoring.\n");
1603 GNUNET_STATISTICS_update (GSC_stats,
1604 gettext_noop ("# bytes dropped (duplicates)"),
1606 /* duplicate, ignore */
1609 kx->last_packets_bitmap |= rotbit;
1611 if (kx->last_sequence_number_received < snum)
1613 unsigned int shift = (snum - kx->last_sequence_number_received);
1615 if (shift >= 8 * sizeof (kx->last_packets_bitmap))
1616 kx->last_packets_bitmap = 0;
1618 kx->last_packets_bitmap <<= shift;
1619 kx->last_sequence_number_received = snum;
1622 /* check timestamp */
1623 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
1624 if (GNUNET_TIME_absolute_get_duration (t).rel_value >
1625 MAX_MESSAGE_AGE.rel_value)
1627 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1628 _("Message received far too old (%llu ms). Content ignored.\n"),
1629 GNUNET_TIME_absolute_get_duration (t).rel_value);
1630 GNUNET_STATISTICS_update (GSC_stats,
1632 ("# bytes dropped (ancient message)"), size,
1637 /* process decrypted message(s) */
1638 update_timeout (kx);
1639 GNUNET_STATISTICS_update (GSC_stats,
1640 gettext_noop ("# bytes of payload decrypted"),
1641 size - sizeof (struct EncryptedMessage), GNUNET_NO);
1643 dmc.atsi_count = atsi_count;
1644 dmc.peer = &kx->peer;
1646 GNUNET_SERVER_mst_receive (mst, &dmc,
1647 &buf[sizeof (struct EncryptedMessage)],
1648 size - sizeof (struct EncryptedMessage),
1649 GNUNET_YES, GNUNET_NO))
1650 GNUNET_break_op (0);
1655 * Deliver P2P message to interested clients.
1656 * Invokes send twice, once for clients that want the full message, and once
1657 * for clients that only want the header
1659 * @param cls always NULL
1660 * @param client who sent us the message (struct GSC_KeyExchangeInfo)
1661 * @param m the message
1664 deliver_message (void *cls, void *client, const struct GNUNET_MessageHeader *m)
1666 struct DeliverMessageContext *dmc = client;
1668 switch (ntohs (m->type))
1670 case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP:
1671 case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP:
1672 GSC_SESSIONS_set_typemap (dmc->peer, m);
1675 GSC_CLIENTS_deliver_message (dmc->peer, dmc->atsi, dmc->atsi_count, m,
1677 GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
1678 GSC_CLIENTS_deliver_message (dmc->peer, dmc->atsi, dmc->atsi_count, m,
1679 sizeof (struct GNUNET_MessageHeader),
1680 GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
1687 * Initialize KX subsystem.
1689 * @param pk private key to use for the peer
1690 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1693 GSC_KX_init (struct GNUNET_CRYPTO_RsaPrivateKey *pk)
1695 my_private_key = pk;
1696 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1697 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1698 &GSC_my_identity.hashPubKey);
1699 peerinfo = GNUNET_PEERINFO_connect (GSC_cfg);
1700 if (NULL == peerinfo)
1702 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1703 _("Could not access PEERINFO service. Exiting.\n"));
1704 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1705 my_private_key = NULL;
1706 return GNUNET_SYSERR;
1708 mst = GNUNET_SERVER_mst_create (&deliver_message, NULL);
1714 * Shutdown KX subsystem.
1719 if (NULL != my_private_key)
1721 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1722 my_private_key = NULL;
1724 if (NULL != peerinfo)
1726 GNUNET_PEERINFO_disconnect (peerinfo);
1731 GNUNET_SERVER_mst_destroy (mst);
1736 /* end of gnunet-service-core_kx.c */