2 This file is part of GNUnet.
3 (C) 2009, 2010, 2011 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"
41 * How long do we wait for SET_KEY confirmation initially?
43 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
46 * What is the minimum frequency for a PING message?
48 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
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.
57 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
60 * What is the maximum delay for a SET_KEY message?
62 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
65 GNUNET_NETWORK_STRUCT_BEGIN
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.
75 * Message type is CORE_PING.
77 struct GNUNET_MessageHeader header;
82 uint32_t iv_seed GNUNET_PACKED;
85 * Intended target of the PING, used primarily to check
86 * that decryption actually worked.
88 struct GNUNET_PeerIdentity target;
91 * Random number chosen to make reply harder.
93 uint32_t challenge GNUNET_PACKED;
98 * Response to a PING. Includes data from the original PING.
103 * Message type is CORE_PONG.
105 struct GNUNET_MessageHeader header;
110 uint32_t iv_seed GNUNET_PACKED;
113 * Random number to make faking the reply harder. Must be
114 * first field after header (this is where we start to encrypt!).
116 uint32_t challenge GNUNET_PACKED;
119 * Reserved, always 'GNUNET_BANDWIDTH_VALUE_MAX'.
121 struct GNUNET_BANDWIDTH_Value32NBO reserved;
124 * Intended target of the PING, used primarily to check
125 * that decryption actually worked.
127 struct GNUNET_PeerIdentity target;
132 * Message transmitted to set (or update) a session key.
138 * Message type is either CORE_SET_KEY.
140 struct GNUNET_MessageHeader header;
143 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
145 int32_t sender_status GNUNET_PACKED;
148 * Purpose of the signature, will be
149 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
151 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
154 * At what time was this key created?
156 struct GNUNET_TIME_AbsoluteNBO creation_time;
159 * The encrypted session key.
161 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
164 * Who is the intended recipient?
166 struct GNUNET_PeerIdentity target;
169 * Signature of the stuff above (starting at purpose).
171 struct GNUNET_CRYPTO_RsaSignature signature;
177 * Encapsulation for encrypted messages exchanged between
178 * peers. Followed by the actual encrypted data.
180 struct EncryptedMessage
183 * Message type is either CORE_ENCRYPTED_MESSAGE.
185 struct GNUNET_MessageHeader header;
188 * Random value used for IV generation.
190 uint32_t iv_seed GNUNET_PACKED;
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.
198 GNUNET_HashCode hmac;
201 * Sequence number, in network byte order. This field
202 * must be the first encrypted/decrypted field
204 uint32_t sequence_number GNUNET_PACKED;
207 * Reserved, always 'GNUNET_BANDWIDTH_VALUE_MAX'.
209 struct GNUNET_BANDWIDTH_Value32NBO reserved;
212 * Timestamp. Used to prevent reply of ancient messages
213 * (recent messages are caught with the sequence number).
215 struct GNUNET_TIME_AbsoluteNBO timestamp;
218 GNUNET_NETWORK_STRUCT_END
220 * Number of bytes (at the beginning) of "struct EncryptedMessage"
221 * that are NOT encrypted.
223 #define ENCRYPTED_HEADER_SIZE (offsetof(struct EncryptedMessage, sequence_number))
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).
242 * We've sent our session key.
247 * We've received the other peers session key.
249 KX_STATE_KEY_RECEIVED,
252 * The other peer has confirmed our session key with a message
253 * encrypted with his session key (which we got). Key exchange
261 * Information about the status of a key exchange with another peer.
263 struct GSC_KeyExchangeInfo
266 * Identity of the peer.
268 struct GNUNET_PeerIdentity peer;
271 * SetKeyMessage to transmit (initialized the first
272 * time our status goes past 'KX_STATE_KEY_SENT').
274 struct SetKeyMessage skm;
277 * PING message we transmit to the other peer.
279 struct PingMessage ping;
282 * SetKeyMessage we received and did not process yet.
284 struct SetKeyMessage *skm_received;
287 * PING message we received from the other peer and
288 * did not process yet (or NULL).
290 struct PingMessage *ping_received;
293 * PONG message we received from the other peer and
294 * did not process yet (or NULL).
296 struct PongMessage *pong_received;
299 * Encrypted message we received from the other peer and
300 * did not process yet (or NULL).
302 struct EncryptedMessage *emsg_received;
305 * Non-NULL if we are currently looking up HELLOs for this peer.
308 struct GNUNET_PEERINFO_IteratorContext *pitr;
311 * Public key of the neighbour, NULL if we don't have it yet.
313 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
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.
320 struct PongMessage *pending_pong;
323 * Key we use to encrypt our messages for the other peer
324 * (initialized by us when we do the handshake).
326 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
329 * Key we use to decrypt messages from the other peer
330 * (given to us by the other peer during the handshake).
332 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
335 * At what time did we generate our encryption key?
337 struct GNUNET_TIME_Absolute encrypt_key_created;
340 * At what time did the other peer generate the decryption key?
342 struct GNUNET_TIME_Absolute decrypt_key_created;
345 * When should the session time out (if there are no PONGs)?
347 struct GNUNET_TIME_Absolute timeout;
350 * At what frequency are we currently re-trying SET_KEY messages?
352 struct GNUNET_TIME_Relative set_key_retry_frequency;
355 * ID of task used for re-trying SET_KEY and PING message.
357 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
360 * ID of task used for sending keep-alive pings.
362 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
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)
369 unsigned int last_packets_bitmap;
372 * last sequence number received on this connection (highest)
374 uint32_t last_sequence_number_received;
377 * last sequence number transmitted
379 uint32_t last_sequence_number_sent;
382 * What was our PING challenge number (for this peer)?
384 uint32_t ping_challenge;
387 * What is our connection status?
389 enum KxStateMachine status;
396 * Handle to peerinfo service.
398 static struct GNUNET_PEERINFO_Handle *peerinfo;
403 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
408 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
411 * Our message stream tokenizer (for encrypted payload).
413 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
418 * Derive an authentication key from "set key" information
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)
425 static const char ctx[] = "authentication key";
426 struct GNUNET_TIME_AbsoluteNBO ctbe;
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,
437 * Derive an IV from packet information
440 derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
441 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
442 const struct GNUNET_PeerIdentity *identity)
444 static const char ctx[] = "initialization vector";
446 GNUNET_CRYPTO_aes_derive_iv (iv, skey, &seed, sizeof (seed),
447 &identity->hashPubKey.bits,
448 sizeof (identity->hashPubKey.bits), ctx,
453 * Derive an IV from pong packet information
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)
460 static const char ctx[] = "pong initialization vector";
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);
470 * Encrypt size bytes from in and write the result to out. Use the
471 * key for outbound traffic of the given neighbour.
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
481 do_encrypt (struct GSC_KeyExchangeInfo *kx,
482 const struct GNUNET_CRYPTO_AesInitializationVector *iv,
483 const void *in, void *out, size_t size)
485 if (size != (uint16_t) size)
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,
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,
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.
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
522 do_decrypt (struct GSC_KeyExchangeInfo *kx,
523 const struct GNUNET_CRYPTO_AesInitializationVector *iv,
524 const void *in, void *out, size_t size)
526 if (size != (uint16_t) size)
531 if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP))
534 return GNUNET_SYSERR;
537 GNUNET_CRYPTO_aes_decrypt (in, (uint16_t) size, &kx->decrypt_key, iv,
541 return GNUNET_SYSERR;
543 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes decrypted"), size,
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,
558 * Send our key (and encrypted PING) to the other peer.
560 * @param kx key exchange context
563 send_key (struct GSC_KeyExchangeInfo *kx);
567 * Task that will retry "send_key" if our previous attempt failed.
569 * @param cls our 'struct GSC_KeyExchangeInfo'
570 * @param tc scheduler context
573 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
575 struct GSC_KeyExchangeInfo *kx = cls;
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);
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.
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
595 process_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
596 const struct GNUNET_HELLO_Message *hello, const char *err_msg)
598 struct GSC_KeyExchangeInfo *kx = cls;
599 struct SetKeyMessage *skm;
603 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
604 _("Error in communication with PEERINFO service\n"));
611 if (kx->public_key != NULL)
612 return; /* done here */
614 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
615 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
616 GNUNET_i2s (&kx->peer));
618 GNUNET_STATISTICS_update (GSC_stats,
620 ("# Delayed connecting due to lack of public key"),
622 kx->retry_set_key_task =
623 GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
624 &set_key_retry_task, kx);
627 if (kx->public_key != NULL)
629 /* already have public key, why are we here? */
633 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->retry_set_key_task);
635 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
636 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, kx->public_key))
639 GNUNET_free (kx->public_key);
640 kx->public_key = NULL;
644 if (NULL != kx->skm_received)
646 skm = kx->skm_received;
647 kx->skm_received = NULL;
648 GSC_KX_handle_set_key (kx, &skm->header);
655 * Start the key exchange with the given peer.
657 * @param pid identity of the peer to do a key exchange with
658 * @return key exchange information context
660 struct GSC_KeyExchangeInfo *
661 GSC_KX_start (const struct GNUNET_PeerIdentity *pid)
663 struct GSC_KeyExchangeInfo *kx;
666 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Initiating key exchange with `%s'\n",
669 GNUNET_STATISTICS_update (GSC_stats,
670 gettext_noop ("# key exchanges initiated"), 1,
672 kx = GNUNET_malloc (sizeof (struct GSC_KeyExchangeInfo));
674 kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
676 GNUNET_PEERINFO_iterate (peerinfo, pid,
677 GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */ ,
684 * Stop key exchange with the given peer. Clean up key material.
686 * @param kx key exchange to stop
689 GSC_KX_stop (struct GSC_KeyExchangeInfo *kx)
691 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# key exchanges stopped"),
693 if (kx->pitr != NULL)
695 GNUNET_PEERINFO_iterate_cancel (kx->pitr);
698 if (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
700 GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
701 kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
703 if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
705 GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
706 kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
708 GNUNET_free_non_null (kx->skm_received);
709 GNUNET_free_non_null (kx->ping_received);
710 GNUNET_free_non_null (kx->pong_received);
711 GNUNET_free_non_null (kx->emsg_received);
712 GNUNET_free_non_null (kx->public_key);
718 * We received a SET_KEY message. Validate and update
719 * our key material and status.
721 * @param kx key exchange status for the corresponding peer
722 * @param msg the set key message we received
725 GSC_KX_handle_set_key (struct GSC_KeyExchangeInfo *kx,
726 const struct GNUNET_MessageHeader *msg)
728 const struct SetKeyMessage *m;
729 struct GNUNET_TIME_Absolute t;
730 struct GNUNET_CRYPTO_AesSessionKey k;
731 struct PingMessage *ping;
732 struct PongMessage *pong;
733 enum KxStateMachine sender_status;
736 size = ntohs (msg->size);
737 if (size != sizeof (struct SetKeyMessage))
742 m = (const struct SetKeyMessage *) msg;
743 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# session keys received"),
747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
748 "Core service receives `%s' request from `%4s'.\n", "SET_KEY",
749 GNUNET_i2s (&kx->peer));
751 if (kx->public_key == NULL)
753 GNUNET_free_non_null (kx->skm_received);
754 kx->skm_received = (struct SetKeyMessage *) GNUNET_copy_message (msg);
758 memcmp (&m->target, &GSC_my_identity,
759 sizeof (struct GNUNET_PeerIdentity)))
761 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
762 _("`%s' is for `%s', not for me. Ignoring.\n"), "SET_KEY",
763 GNUNET_i2s (&m->target));
766 if ((ntohl (m->purpose.size) !=
767 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
768 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
769 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
770 sizeof (struct GNUNET_PeerIdentity)) ||
772 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY, &m->purpose,
773 &m->signature, kx->public_key)))
775 /* invalid signature */
779 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
780 if (((kx->status == KX_STATE_KEY_RECEIVED) || (kx->status == KX_STATE_UP)) &&
781 (t.abs_value < kx->decrypt_key_created.abs_value))
783 /* this could rarely happen due to massive re-ordering of
784 * messages on the network level, but is most likely either
785 * a bug or some adversary messing with us. Report. */
789 if ((GNUNET_CRYPTO_rsa_decrypt
790 (my_private_key, &m->encrypted_key, &k,
791 sizeof (struct GNUNET_CRYPTO_AesSessionKey)) !=
792 sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
793 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
795 /* failed to decrypt !? */
799 GNUNET_STATISTICS_update (GSC_stats,
800 gettext_noop ("# SET_KEY messages decrypted"), 1,
803 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received SET_KEY from `%s'\n",
804 GNUNET_i2s (&kx->peer));
807 if (kx->decrypt_key_created.abs_value != t.abs_value)
809 /* fresh key, reset sequence numbers */
810 kx->last_sequence_number_received = 0;
811 kx->last_packets_bitmap = 0;
812 kx->decrypt_key_created = t;
814 sender_status = (enum KxStateMachine) ntohl (m->sender_status);
819 kx->status = KX_STATE_KEY_RECEIVED;
820 /* we're not up, so we are already doing 'send_key' */
822 case KX_STATE_KEY_SENT:
823 kx->status = KX_STATE_KEY_RECEIVED;
824 /* we're not up, so we are already doing 'send_key' */
826 case KX_STATE_KEY_RECEIVED:
827 /* we're not up, so we are already doing 'send_key' */
830 if ((sender_status == KX_STATE_DOWN) ||
831 (sender_status == KX_STATE_KEY_SENT))
832 send_key (kx); /* we are up, but other peer is not! */
838 if (kx->ping_received != NULL)
840 ping = kx->ping_received;
841 kx->ping_received = NULL;
842 GSC_KX_handle_ping (kx, &ping->header);
845 if (kx->pong_received != NULL)
847 pong = kx->pong_received;
848 kx->pong_received = NULL;
849 GSC_KX_handle_pong (kx, &pong->header);
856 * We received a PING message. Validate and transmit
859 * @param kx key exchange status for the corresponding peer
860 * @param msg the encrypted PING message itself
863 GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *kx,
864 const struct GNUNET_MessageHeader *msg)
866 const struct PingMessage *m;
867 struct PingMessage t;
868 struct PongMessage tx;
869 struct PongMessage tp;
870 struct GNUNET_CRYPTO_AesInitializationVector iv;
873 msize = ntohs (msg->size);
874 if (msize != sizeof (struct PingMessage))
879 GNUNET_STATISTICS_update (GSC_stats,
880 gettext_noop ("# PING messages received"), 1,
882 if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP))
885 GNUNET_free_non_null (kx->ping_received);
886 kx->ping_received = (struct PingMessage *) GNUNET_copy_message (msg);
889 m = (const struct PingMessage *) msg;
891 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
892 "Core service receives `%s' request from `%4s'.\n", "PING",
893 GNUNET_i2s (&kx->peer));
895 derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
897 do_decrypt (kx, &iv, &m->target, &t.target,
898 sizeof (struct PingMessage) - ((void *) &m->target -
905 memcmp (&t.target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
910 GNUNET_snprintf (sender, sizeof (sender), "%8s", GNUNET_i2s (&kx->peer));
911 GNUNET_snprintf (peer, sizeof (peer), "%8s", GNUNET_i2s (&t.target));
912 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
914 ("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
915 sender, GNUNET_i2s (&GSC_my_identity), peer);
920 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PING from `%s'\n",
921 GNUNET_i2s (&kx->peer));
924 tx.reserved = GNUNET_BANDWIDTH_VALUE_MAX;
925 tx.challenge = t.challenge;
926 tx.target = t.target;
927 tp.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
928 tp.header.size = htons (sizeof (struct PongMessage));
930 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
931 derive_pong_iv (&iv, &kx->encrypt_key, tp.iv_seed, t.challenge, &kx->peer);
932 do_encrypt (kx, &iv, &tx.challenge, &tp.challenge,
933 sizeof (struct PongMessage) - ((void *) &tp.challenge -
935 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages created"),
937 GSC_NEIGHBOURS_transmit (&kx->peer, &tp.header,
938 GNUNET_TIME_UNIT_FOREVER_REL /* FIXME: timeout */ );
943 * Create a fresh SET KEY message for transmission to the other peer.
944 * Also creates a new key.
946 * @param kx key exchange context to create SET KEY message for
949 setup_fresh_setkey (struct GSC_KeyExchangeInfo *kx)
951 struct SetKeyMessage *skm;
953 GNUNET_CRYPTO_aes_create_session_key (&kx->encrypt_key);
954 kx->encrypt_key_created = GNUNET_TIME_absolute_get ();
956 skm->header.size = htons (sizeof (struct SetKeyMessage));
957 skm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
959 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
960 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
961 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
962 sizeof (struct GNUNET_PeerIdentity));
963 skm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
964 skm->creation_time = GNUNET_TIME_absolute_hton (kx->encrypt_key_created);
965 skm->target = kx->peer;
966 GNUNET_assert (GNUNET_OK ==
967 GNUNET_CRYPTO_rsa_encrypt (&kx->encrypt_key,
969 GNUNET_CRYPTO_AesSessionKey),
971 &skm->encrypted_key));
972 GNUNET_assert (GNUNET_OK ==
973 GNUNET_CRYPTO_rsa_sign (my_private_key, &skm->purpose,
979 * Create a fresh PING message for transmission to the other peer.
981 * @param kx key exchange context to create PING for
984 setup_fresh_ping (struct GSC_KeyExchangeInfo *kx)
986 struct PingMessage pp;
987 struct PingMessage *pm;
988 struct GNUNET_CRYPTO_AesInitializationVector iv;
991 pm->header.size = htons (sizeof (struct PingMessage));
992 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
994 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
995 derive_iv (&iv, &kx->encrypt_key, pm->iv_seed, &kx->peer);
996 pp.challenge = kx->ping_challenge;
997 pp.target = kx->peer;
998 do_encrypt (kx, &iv, &pp.target, &pm->target,
999 sizeof (struct PingMessage) - ((void *) &pm->target -
1005 * Task triggered when a neighbour entry is about to time out
1006 * (and we should prevent this by sending a PING).
1008 * @param cls the 'struct GSC_KeyExchangeInfo'
1009 * @param tc scheduler context (not used)
1012 send_keep_alive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1014 struct GSC_KeyExchangeInfo *kx = cls;
1015 struct GNUNET_TIME_Relative retry;
1016 struct GNUNET_TIME_Relative left;
1018 kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1019 left = GNUNET_TIME_absolute_get_remaining (kx->timeout);
1020 if (left.rel_value == 0)
1022 GNUNET_STATISTICS_update (GSC_stats,
1023 gettext_noop ("# sessions terminated by timeout"),
1025 GSC_SESSIONS_end (&kx->peer);
1026 kx->status = KX_STATE_DOWN;
1030 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending KEEPALIVE to `%s'\n",
1031 GNUNET_i2s (&kx->peer));
1033 GNUNET_STATISTICS_update (GSC_stats,
1034 gettext_noop ("# keepalive messages sent"), 1,
1036 setup_fresh_ping (kx);
1037 GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
1038 kx->set_key_retry_frequency);
1040 GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1041 MIN_PING_FREQUENCY);
1042 kx->keep_alive_task =
1043 GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx);
1048 * We've seen a valid message from the other peer.
1049 * Update the time when the session would time out
1050 * and delay sending our keep alive message further.
1052 * @param kx key exchange where we saw activity
1055 update_timeout (struct GSC_KeyExchangeInfo *kx)
1058 GNUNET_TIME_relative_to_absolute
1059 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1060 if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1061 GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1062 kx->keep_alive_task =
1063 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
1064 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1065 2), &send_keep_alive, kx);
1070 * We received a PONG message. Validate and update our status.
1072 * @param kx key exchange context for the the PONG
1073 * @param msg the encrypted PONG message itself
1076 GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx,
1077 const struct GNUNET_MessageHeader *msg)
1079 const struct PongMessage *m;
1080 struct PongMessage t;
1081 struct EncryptedMessage *emsg;
1082 struct GNUNET_CRYPTO_AesInitializationVector iv;
1085 msize = ntohs (msg->size);
1086 if (msize != sizeof (struct PongMessage))
1088 GNUNET_break_op (0);
1091 GNUNET_STATISTICS_update (GSC_stats,
1092 gettext_noop ("# PONG messages received"), 1,
1094 if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP))
1096 if (kx->status == KX_STATE_KEY_SENT)
1098 GNUNET_free_non_null (kx->pong_received);
1099 kx->pong_received = (struct PongMessage *) GNUNET_copy_message (msg);
1103 m = (const struct PongMessage *) msg;
1105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1106 "Core service receives `%s' response from `%4s'.\n", "PONG",
1107 GNUNET_i2s (&kx->peer));
1109 /* mark as garbage, just to be sure */
1110 memset (&t, 255, sizeof (t));
1111 derive_pong_iv (&iv, &kx->decrypt_key, m->iv_seed, kx->ping_challenge,
1114 do_decrypt (kx, &iv, &m->challenge, &t.challenge,
1115 sizeof (struct PongMessage) - ((void *) &m->challenge -
1118 GNUNET_break_op (0);
1121 GNUNET_STATISTICS_update (GSC_stats,
1122 gettext_noop ("# PONG messages decrypted"), 1,
1124 if ((0 != memcmp (&t.target, &kx->peer, sizeof (struct GNUNET_PeerIdentity)))
1125 || (kx->ping_challenge != t.challenge))
1127 /* PONG malformed */
1129 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1130 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
1131 "PONG", GNUNET_i2s (&kx->peer),
1132 (unsigned int) kx->ping_challenge);
1133 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1134 "Received malformed `%s' received from `%4s' with challenge %u\n",
1135 "PONG", GNUNET_i2s (&t.target), (unsigned int) t.challenge);
1140 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PONG from `%s'\n",
1141 GNUNET_i2s (&kx->peer));
1146 GNUNET_break (0); /* should be impossible */
1148 case KX_STATE_KEY_SENT:
1149 GNUNET_break (0); /* should be impossible */
1151 case KX_STATE_KEY_RECEIVED:
1152 GNUNET_STATISTICS_update (GSC_stats,
1154 ("# session keys confirmed via PONG"), 1,
1156 kx->status = KX_STATE_UP;
1157 GSC_SESSIONS_create (&kx->peer, kx);
1158 GNUNET_assert (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK);
1159 GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1160 kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1161 GNUNET_assert (kx->keep_alive_task == GNUNET_SCHEDULER_NO_TASK);
1162 if (kx->emsg_received != NULL)
1164 emsg = kx->emsg_received;
1165 kx->emsg_received = NULL;
1166 GSC_KX_handle_encrypted_message (kx, &emsg->header, NULL,
1167 0 /* FIXME: ATSI */ );
1170 update_timeout (kx);
1173 update_timeout (kx);
1183 * Send our key (and encrypted PING) to the other peer.
1185 * @param kx key exchange context
1188 send_key (struct GSC_KeyExchangeInfo *kx)
1190 GNUNET_assert (kx->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK);
1191 if (KX_STATE_UP == kx->status)
1192 return; /* nothing to do */
1193 if (kx->public_key == NULL)
1195 /* lookup public key, then try again */
1197 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1198 "Trying to obtain public key for `%s'\n",
1199 GNUNET_i2s (&kx->peer));
1202 GNUNET_PEERINFO_iterate (peerinfo, &kx->peer,
1203 GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */ ,
1204 &process_hello, kx);
1212 kx->status = KX_STATE_KEY_SENT;
1213 /* setup SET KEY message */
1214 setup_fresh_setkey (kx);
1215 setup_fresh_ping (kx);
1216 GNUNET_STATISTICS_update (GSC_stats,
1218 ("# SET_KEY and PING messages created"), 1,
1221 case KX_STATE_KEY_SENT:
1223 case KX_STATE_KEY_RECEIVED:
1233 /* always update sender status in SET KEY message */
1234 kx->skm.sender_status = htonl ((int32_t) kx->status);
1236 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending SET_KEY and PING to `%s'\n",
1237 GNUNET_i2s (&kx->peer));
1239 GSC_NEIGHBOURS_transmit (&kx->peer, &kx->skm.header,
1240 kx->set_key_retry_frequency);
1241 GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
1242 kx->set_key_retry_frequency);
1243 kx->retry_set_key_task =
1244 GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
1245 &set_key_retry_task, kx);
1250 * Encrypt and transmit a message with the given payload.
1252 * @param kx key exchange context
1253 * @param payload payload of the message
1254 * @param payload_size number of bytes in 'payload'
1257 GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
1258 const void *payload, size_t payload_size)
1260 size_t used = payload_size + sizeof (struct EncryptedMessage);
1261 char pbuf[used]; /* plaintext */
1262 char cbuf[used]; /* ciphertext */
1263 struct EncryptedMessage *em; /* encrypted message */
1264 struct EncryptedMessage *ph; /* plaintext header */
1265 struct GNUNET_CRYPTO_AesInitializationVector iv;
1266 struct GNUNET_CRYPTO_AuthKey auth_key;
1268 ph = (struct EncryptedMessage *) pbuf;
1270 htonl (GNUNET_CRYPTO_random_u32
1271 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
1272 ph->sequence_number = htonl (++kx->last_sequence_number_sent);
1273 ph->reserved = GNUNET_BANDWIDTH_VALUE_MAX;
1274 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1275 memcpy (&ph[1], payload, payload_size);
1277 em = (struct EncryptedMessage *) cbuf;
1278 em->header.size = htons (used);
1279 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1280 em->iv_seed = ph->iv_seed;
1281 derive_iv (&iv, &kx->encrypt_key, ph->iv_seed, &kx->peer);
1282 GNUNET_assert (GNUNET_OK ==
1283 do_encrypt (kx, &iv, &ph->sequence_number,
1284 &em->sequence_number,
1285 used - ENCRYPTED_HEADER_SIZE));
1287 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Encrypted %u bytes for %s\n",
1288 used - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1290 derive_auth_key (&auth_key, &kx->encrypt_key, ph->iv_seed,
1291 kx->encrypt_key_created);
1292 GNUNET_CRYPTO_hmac (&auth_key, &em->sequence_number,
1293 used - ENCRYPTED_HEADER_SIZE, &em->hmac);
1294 GSC_NEIGHBOURS_transmit (&kx->peer, &em->header,
1295 GNUNET_TIME_UNIT_FOREVER_REL);
1300 * Closure for 'deliver_message'
1302 struct DeliverMessageContext
1306 * Performance information for the connection.
1308 const struct GNUNET_ATS_Information *atsi;
1311 * Sender of the message.
1313 const struct GNUNET_PeerIdentity *peer;
1316 * Number of entries in 'atsi' array.
1318 uint32_t atsi_count;
1323 * We received an encrypted message. Decrypt, validate and
1324 * pass on to the appropriate clients.
1326 * @param kx key exchange context for encrypting the message
1327 * @param msg encrypted message
1328 * @param atsi performance data
1329 * @param atsi_count number of entries in ats (excluding 0-termination)
1332 GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *kx,
1333 const struct GNUNET_MessageHeader *msg,
1334 const struct GNUNET_ATS_Information *atsi,
1335 uint32_t atsi_count)
1337 const struct EncryptedMessage *m;
1338 struct EncryptedMessage *pt; /* plaintext */
1341 struct GNUNET_TIME_Absolute t;
1342 struct GNUNET_CRYPTO_AesInitializationVector iv;
1343 struct GNUNET_CRYPTO_AuthKey auth_key;
1344 struct DeliverMessageContext dmc;
1345 uint16_t size = ntohs (msg->size);
1349 sizeof (struct EncryptedMessage) + sizeof (struct GNUNET_MessageHeader))
1351 GNUNET_break_op (0);
1354 m = (const struct EncryptedMessage *) msg;
1355 if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP))
1357 GNUNET_STATISTICS_update (GSC_stats,
1359 ("# failed to decrypt message (no session key)"),
1363 if (kx->status == KX_STATE_KEY_RECEIVED)
1366 GNUNET_free_non_null (kx->ping_received);
1367 kx->emsg_received = (struct EncryptedMessage *) GNUNET_copy_message (msg);
1371 derive_auth_key (&auth_key, &kx->decrypt_key, m->iv_seed,
1372 kx->decrypt_key_created);
1373 GNUNET_CRYPTO_hmac (&auth_key, &m->sequence_number,
1374 size - ENCRYPTED_HEADER_SIZE, &ph);
1375 if (0 != memcmp (&ph, &m->hmac, sizeof (GNUNET_HashCode)))
1377 /* checksum failed */
1378 GNUNET_break_op (0);
1381 derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
1384 do_decrypt (kx, &iv, &m->sequence_number, &buf[ENCRYPTED_HEADER_SIZE],
1385 size - ENCRYPTED_HEADER_SIZE))
1388 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypted %u bytes from %s\n",
1389 size - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1391 pt = (struct EncryptedMessage *) buf;
1393 /* validate sequence number */
1394 snum = ntohl (pt->sequence_number);
1395 if (kx->last_sequence_number_received == snum)
1397 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1398 "Received duplicate message, ignoring.\n");
1399 /* duplicate, ignore */
1400 GNUNET_STATISTICS_update (GSC_stats,
1401 gettext_noop ("# bytes dropped (duplicates)"),
1405 if ((kx->last_sequence_number_received > snum) &&
1406 (kx->last_sequence_number_received - snum > 32))
1408 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1409 "Received ancient out of sequence message, ignoring.\n");
1410 /* ancient out of sequence, ignore */
1411 GNUNET_STATISTICS_update (GSC_stats,
1413 ("# bytes dropped (out of sequence)"), size,
1417 if (kx->last_sequence_number_received > snum)
1419 unsigned int rotbit = 1 << (kx->last_sequence_number_received - snum - 1);
1421 if ((kx->last_packets_bitmap & rotbit) != 0)
1423 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1424 "Received duplicate message, ignoring.\n");
1425 GNUNET_STATISTICS_update (GSC_stats,
1426 gettext_noop ("# bytes dropped (duplicates)"),
1428 /* duplicate, ignore */
1431 kx->last_packets_bitmap |= rotbit;
1433 if (kx->last_sequence_number_received < snum)
1435 unsigned int shift = (snum - kx->last_sequence_number_received);
1437 if (shift >= 8 * sizeof (kx->last_packets_bitmap))
1438 kx->last_packets_bitmap = 0;
1440 kx->last_packets_bitmap <<= shift;
1441 kx->last_sequence_number_received = snum;
1444 /* check timestamp */
1445 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
1446 if (GNUNET_TIME_absolute_get_duration (t).rel_value >
1447 MAX_MESSAGE_AGE.rel_value)
1449 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1450 _("Message received far too old (%llu ms). Content ignored.\n"),
1451 GNUNET_TIME_absolute_get_duration (t).rel_value);
1452 GNUNET_STATISTICS_update (GSC_stats,
1454 ("# bytes dropped (ancient message)"), size,
1459 /* process decrypted message(s) */
1460 update_timeout (kx);
1461 GNUNET_STATISTICS_update (GSC_stats,
1462 gettext_noop ("# bytes of payload decrypted"),
1463 size - sizeof (struct EncryptedMessage), GNUNET_NO);
1465 dmc.atsi_count = atsi_count;
1466 dmc.peer = &kx->peer;
1468 GNUNET_SERVER_mst_receive (mst, &dmc,
1469 &buf[sizeof (struct EncryptedMessage)],
1470 size - sizeof (struct EncryptedMessage),
1471 GNUNET_YES, GNUNET_NO))
1472 GNUNET_break_op (0);
1477 * Deliver P2P message to interested clients.
1478 * Invokes send twice, once for clients that want the full message, and once
1479 * for clients that only want the header
1481 * @param cls always NULL
1482 * @param client who sent us the message (struct GSC_KeyExchangeInfo)
1483 * @param m the message
1486 deliver_message (void *cls, void *client, const struct GNUNET_MessageHeader *m)
1488 struct DeliverMessageContext *dmc = client;
1490 switch (ntohs (m->type))
1492 case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP:
1493 case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP:
1494 GSC_SESSIONS_set_typemap (dmc->peer, m);
1497 GSC_CLIENTS_deliver_message (dmc->peer, dmc->atsi, dmc->atsi_count, m,
1499 GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
1500 GSC_CLIENTS_deliver_message (dmc->peer, dmc->atsi, dmc->atsi_count, m,
1501 sizeof (struct GNUNET_MessageHeader),
1502 GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
1508 * Initialize KX subsystem.
1510 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1518 GNUNET_CONFIGURATION_get_value_filename (GSC_cfg, "GNUNETD", "HOSTKEY",
1521 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1523 ("Core service is lacking HOSTKEY configuration setting. Exiting.\n"));
1524 return GNUNET_SYSERR;
1526 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1527 GNUNET_free (keyfile);
1528 if (my_private_key == NULL)
1530 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1531 _("Core service could not access hostkey. Exiting.\n"));
1532 return GNUNET_SYSERR;
1534 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1535 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1536 &GSC_my_identity.hashPubKey);
1537 peerinfo = GNUNET_PEERINFO_connect (GSC_cfg);
1538 if (NULL == peerinfo)
1540 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1541 _("Could not access PEERINFO service. Exiting.\n"));
1542 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1543 my_private_key = NULL;
1544 return GNUNET_SYSERR;
1546 mst = GNUNET_SERVER_mst_create (&deliver_message, NULL);
1552 * Shutdown KX subsystem.
1557 if (my_private_key != NULL)
1559 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1560 my_private_key = NULL;
1562 if (peerinfo != NULL)
1564 GNUNET_PEERINFO_disconnect (peerinfo);
1569 GNUNET_SERVER_mst_destroy (mst);
1574 /* end of gnunet-service-core_kx.c */