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)
66 * We're sending an (encrypted) PING to the other peer to check if he
67 * can decrypt. The other peer should respond with a PONG with the
68 * same content, except this time encrypted with the receiver's key.
73 * Message type is CORE_PING.
75 struct GNUNET_MessageHeader header;
80 uint32_t iv_seed GNUNET_PACKED;
83 * Intended target of the PING, used primarily to check
84 * that decryption actually worked.
86 struct GNUNET_PeerIdentity target;
89 * Random number chosen to make reply harder.
91 uint32_t challenge GNUNET_PACKED;
96 * Response to a PING. Includes data from the original PING
97 * plus initial bandwidth quota information.
102 * Message type is CORE_PONG.
104 struct GNUNET_MessageHeader header;
109 uint32_t iv_seed GNUNET_PACKED;
112 * Random number to make faking the reply harder. Must be
113 * first field after header (this is where we start to encrypt!).
115 uint32_t challenge GNUNET_PACKED;
118 * Desired bandwidth (how much we should send to this
119 * peer / how much is the sender willing to receive).
121 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
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 * Desired bandwidth (how much we should send to this peer / how
208 * much is the sender willing to receive)?
210 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
213 * Timestamp. Used to prevent reply of ancient messages
214 * (recent messages are caught with the sequence number).
216 struct GNUNET_TIME_AbsoluteNBO timestamp;
221 * Number of bytes (at the beginning) of "struct EncryptedMessage"
222 * that are NOT encrypted.
224 #define ENCRYPTED_HEADER_SIZE (offsetof(struct EncryptedMessage, sequence_number))
228 * State machine for our P2P encryption handshake. Everyone starts in
229 * "DOWN", if we receive the other peer's key (other peer initiated)
230 * we start in state RECEIVED (since we will immediately send our
231 * own); otherwise we start in SENT. If we get back a PONG from
232 * within either state, we move up to CONFIRMED (the PONG will always
233 * be sent back encrypted with the key we sent to the other peer).
243 * We've sent our session key.
248 * We've received the other peers session key.
250 KX_STATE_KEY_RECEIVED,
253 * The other peer has confirmed our session key with a message
254 * encrypted with his session key (which we got). Key exchange
262 * Information about the status of a key exchange with another peer.
264 struct GSC_KeyExchangeInfo
267 * Identity of the peer.
269 struct GNUNET_PeerIdentity peer;
272 * SetKeyMessage to transmit (initialized the first
273 * time our status goes past 'KX_STATE_KEY_SENT').
275 struct SetKeyMessage skm;
278 * PING message we transmit to the other peer.
280 struct PingMessage ping;
283 * SetKeyMessage we received and did not process yet.
285 struct SetKeyMessage *skm_received;
288 * PING message we received from the other peer and
289 * did not process yet (or NULL).
291 struct PingMessage *ping_received;
294 * PONG message we received from the other peer and
295 * did not process yet (or NULL).
297 struct PongMessage *pong_received;
300 * Non-NULL if we are currently looking up HELLOs for this peer.
303 struct GNUNET_PEERINFO_IteratorContext *pitr;
306 * Public key of the neighbour, NULL if we don't have it yet.
308 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
311 * We received a PONG message before we got the "public_key"
312 * (or the SET_KEY). We keep it here until we have a key
313 * to decrypt it. NULL if no PONG is pending.
315 struct PongMessage *pending_pong;
318 * Key we use to encrypt our messages for the other peer
319 * (initialized by us when we do the handshake).
321 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
324 * Key we use to decrypt messages from the other peer
325 * (given to us by the other peer during the handshake).
327 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
330 * At what time did we generate our encryption key?
332 struct GNUNET_TIME_Absolute encrypt_key_created;
335 * At what time did the other peer generate the decryption key?
337 struct GNUNET_TIME_Absolute decrypt_key_created;
340 * When should the session time out (if there are no PONGs)?
342 struct GNUNET_TIME_Absolute timeout;
345 * At what frequency are we currently re-trying SET_KEY messages?
347 struct GNUNET_TIME_Relative set_key_retry_frequency;
350 * ID of task used for re-trying SET_KEY and PING message.
352 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
355 * ID of task used for sending keep-alive pings.
357 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
360 * Bit map indicating which of the 32 sequence numbers before the last
361 * were received (good for accepting out-of-order packets and
362 * estimating reliability of the connection)
364 unsigned int last_packets_bitmap;
367 * last sequence number received on this connection (highest)
369 uint32_t last_sequence_number_received;
372 * last sequence number transmitted
374 uint32_t last_sequence_number_sent;
377 * What was our PING challenge number (for this peer)?
379 uint32_t ping_challenge;
382 * What is our connection status?
384 enum KxStateMachine status;
391 * Handle to peerinfo service.
393 static struct GNUNET_PEERINFO_Handle *peerinfo;
398 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
403 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
406 * Our message stream tokenizer (for encrypted payload).
408 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
413 * Derive an authentication key from "set key" information
416 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
417 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
418 struct GNUNET_TIME_Absolute creation_time)
420 static const char ctx[] = "authentication key";
421 struct GNUNET_TIME_AbsoluteNBO ctbe;
424 ctbe = GNUNET_TIME_absolute_hton (creation_time);
425 GNUNET_CRYPTO_hmac_derive_key (akey, skey, &seed, sizeof (seed), &skey->key,
426 sizeof (skey->key), &ctbe, sizeof (ctbe), ctx,
432 * Derive an IV from packet information
435 derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
436 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
437 const struct GNUNET_PeerIdentity *identity)
439 static const char ctx[] = "initialization vector";
441 GNUNET_CRYPTO_aes_derive_iv (iv, skey, &seed, sizeof (seed),
442 &identity->hashPubKey.bits,
443 sizeof (identity->hashPubKey.bits), ctx,
448 * Derive an IV from pong packet information
451 derive_pong_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
452 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
453 uint32_t challenge, const struct GNUNET_PeerIdentity *identity)
455 static const char ctx[] = "pong initialization vector";
457 GNUNET_CRYPTO_aes_derive_iv (iv, skey, &seed, sizeof (seed),
458 &identity->hashPubKey.bits,
459 sizeof (identity->hashPubKey.bits), &challenge,
460 sizeof (challenge), ctx, sizeof (ctx), NULL);
465 * Encrypt size bytes from in and write the result to out. Use the
466 * key for outbound traffic of the given neighbour.
468 * @param kx key information context
469 * @param iv initialization vector to use
470 * @param in ciphertext
471 * @param out plaintext
472 * @param size size of in/out
473 * @return GNUNET_OK on success
476 do_encrypt (struct GSC_KeyExchangeInfo *kx,
477 const struct GNUNET_CRYPTO_AesInitializationVector *iv,
478 const void *in, void *out, size_t size)
480 if (size != (uint16_t) size)
485 GNUNET_assert (size ==
486 GNUNET_CRYPTO_aes_encrypt (in, (uint16_t) size,
487 &kx->encrypt_key, iv, out));
488 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes encrypted"), size,
491 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
492 "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
493 (unsigned int) size, GNUNET_i2s (&kx->peer),
494 (unsigned int) kx->encrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
505 * Decrypt size bytes from in and write the result to out. Use the
506 * key for inbound traffic of the given neighbour. This function does
507 * NOT do any integrity-checks on the result.
509 * @param kx key information context
510 * @param iv initialization vector to use
511 * @param in ciphertext
512 * @param out plaintext
513 * @param size size of in/out
514 * @return GNUNET_OK on success
517 do_decrypt (struct GSC_KeyExchangeInfo *kx,
518 const struct GNUNET_CRYPTO_AesInitializationVector *iv,
519 const void *in, void *out, size_t size)
521 if (size != (uint16_t) size)
526 if ((kx->status != KX_STATE_KEY_RECEIVED) &&
527 (kx->status != KX_STATE_UP))
530 return GNUNET_SYSERR;
533 GNUNET_CRYPTO_aes_decrypt (in, (uint16_t) size, &kx->decrypt_key, iv, out))
536 return GNUNET_SYSERR;
538 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes decrypted"), size,
541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
542 "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
543 (unsigned int) size, GNUNET_i2s (&kx->peer),
544 (unsigned int) kx->decrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
553 * Send our key (and encrypted PING) to the other peer.
555 * @param kx key exchange context
558 send_key (struct GSC_KeyExchangeInfo *kx);
562 * Task that will retry "send_key" if our previous attempt failed.
564 * @param cls our 'struct GSC_KeyExchangeInfo'
565 * @param tc scheduler context
568 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
570 struct GSC_KeyExchangeInfo *kx = cls;
572 kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
573 kx->set_key_retry_frequency = GNUNET_TIME_relative_multiply (kx->set_key_retry_frequency, 2);
579 * PEERINFO is giving us a HELLO for a peer. Add the public key to
580 * the neighbour's struct and continue with the key exchange. Or, if
581 * we did not get a HELLO, just do nothing.
583 * @param cls the 'struct GSC_KeyExchangeInfo' to retry sending the key for
584 * @param peer the peer for which this is the HELLO
585 * @param hello HELLO message of that peer
586 * @param err_msg NULL if successful, otherwise contains error message
589 process_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
590 const struct GNUNET_HELLO_Message *hello,
593 struct GSC_KeyExchangeInfo *kx = cls;
594 struct SetKeyMessage *skm;
596 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->retry_set_key_task);
599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
600 _("Error in communication with PEERINFO service\n"));
607 if (kx->public_key != NULL)
608 return; /* done here */
610 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
611 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
612 GNUNET_i2s (&kx->peer));
614 GNUNET_STATISTICS_update (GSC_stats,
616 ("# Delayed connecting due to lack of public key"),
618 kx->retry_set_key_task =
619 GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
620 &set_key_retry_task, kx);
623 if (kx->public_key != NULL)
625 /* already have public key, why are we here? */
630 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
631 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, kx->public_key))
634 GNUNET_free (kx->public_key);
635 kx->public_key = NULL;
639 if (NULL != kx->skm_received)
641 skm = kx->skm_received;
642 kx->skm_received = NULL;
643 GSC_KX_handle_set_key (kx, &skm->header);
650 * Start the key exchange with the given peer.
652 * @param pid identity of the peer to do a key exchange with
653 * @return key exchange information context
655 struct GSC_KeyExchangeInfo *
656 GSC_KX_start (const struct GNUNET_PeerIdentity *pid)
658 struct GSC_KeyExchangeInfo *kx;
660 kx = GNUNET_malloc (sizeof (struct GSC_KeyExchangeInfo));
662 kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
663 kx->pitr = GNUNET_PEERINFO_iterate (peerinfo,
665 GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */,
673 * Stop key exchange with the given peer. Clean up key material.
675 * @param kx key exchange to stop
678 GSC_KX_stop (struct GSC_KeyExchangeInfo *kx)
680 if (kx->pitr != NULL)
682 GNUNET_PEERINFO_iterate_cancel (kx->pitr);
685 if (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
687 GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
688 kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
690 if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
692 GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
693 kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
695 GNUNET_free_non_null (kx->skm_received);
696 GNUNET_free_non_null (kx->ping_received);
697 GNUNET_free_non_null (kx->pong_received);
698 GNUNET_free_non_null (kx->public_key);
704 * We received a SET_KEY message. Validate and update
705 * our key material and status.
707 * @param kx key exchange status for the corresponding peer
708 * @param msg the set key message we received
711 GSC_KX_handle_set_key (struct GSC_KeyExchangeInfo *kx,
712 const struct GNUNET_MessageHeader *msg)
714 const struct SetKeyMessage *m;
715 struct GNUNET_TIME_Absolute t;
716 struct GNUNET_CRYPTO_AesSessionKey k;
717 struct PingMessage *ping;
718 struct PongMessage *pong;
719 enum KxStateMachine sender_status;
722 size = ntohs (msg->size);
723 if (size != sizeof (struct SetKeyMessage))
728 m = (const struct SetKeyMessage*) msg;
729 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# session keys received"),
733 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
734 "Core service receives `%s' request from `%4s'.\n", "SET_KEY",
735 GNUNET_i2s (&kx->peer));
737 if (kx->public_key == NULL)
739 GNUNET_free_non_null (kx->skm_received);
740 kx->skm_received = GNUNET_copy_message (msg);
744 memcmp (&m->target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
746 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
747 _("`%s' is for `%s', not for me. Ignoring.\n"),
748 "SET_KEY", GNUNET_i2s (&m->target));
751 if ((ntohl (m->purpose.size) !=
752 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
753 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
754 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
755 sizeof (struct GNUNET_PeerIdentity)) ||
757 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY, &m->purpose,
758 &m->signature, kx->public_key)))
760 /* invalid signature */
764 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
765 if (((kx->status == KX_STATE_KEY_RECEIVED) ||
766 (kx->status == KX_STATE_UP)) &&
767 (t.abs_value < kx->decrypt_key_created.abs_value))
769 /* this could rarely happen due to massive re-ordering of
770 * messages on the network level, but is most likely either
771 * a bug or some adversary messing with us. Report. */
775 if ((GNUNET_CRYPTO_rsa_decrypt
776 (my_private_key, &m->encrypted_key, &k,
777 sizeof (struct GNUNET_CRYPTO_AesSessionKey)) !=
778 sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
779 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
781 /* failed to decrypt !? */
785 GNUNET_STATISTICS_update (GSC_stats,
786 gettext_noop ("# SET_KEY messages decrypted"), 1,
789 if (kx->decrypt_key_created.abs_value != t.abs_value)
791 /* fresh key, reset sequence numbers */
792 kx->last_sequence_number_received = 0;
793 kx->last_packets_bitmap = 0;
794 kx->decrypt_key_created = t;
796 sender_status = (enum KxStateMachine) ntohl (m->sender_status);
801 kx->status = KX_STATE_KEY_RECEIVED;
802 /* we're not up, so we are already doing 'send_key' */
804 case KX_STATE_KEY_SENT:
805 kx->status = KX_STATE_KEY_RECEIVED;
806 /* we're not up, so we are already doing 'send_key' */
808 case KX_STATE_KEY_RECEIVED:
809 /* we're not up, so we are already doing 'send_key' */
812 if ( (sender_status == KX_STATE_DOWN) ||
813 (sender_status == KX_STATE_KEY_SENT) )
814 send_key (kx); /* we are up, but other peer is not! */
820 if (kx->ping_received != NULL)
822 ping = kx->ping_received;
823 kx->ping_received = NULL;
824 GSC_KX_handle_ping (kx, &ping->header);
827 if (kx->pong_received != NULL)
829 pong = kx->pong_received;
830 kx->pong_received = NULL;
831 GSC_KX_handle_pong (kx, &pong->header);
838 * We received a PING message. Validate and transmit
841 * @param kx key exchange status for the corresponding peer
842 * @param msg the encrypted PING message itself
845 GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *kx,
846 const struct GNUNET_MessageHeader *msg)
848 const struct PingMessage *m;
849 struct PingMessage t;
850 struct PongMessage tx;
851 struct PongMessage tp;
852 struct GNUNET_CRYPTO_AesInitializationVector iv;
855 msize = ntohs (msg->size);
856 if (msize != sizeof (struct PingMessage))
861 GNUNET_STATISTICS_update (GSC_stats,
862 gettext_noop ("# PING messages received"),
864 if ( (kx->status != KX_STATE_KEY_RECEIVED) &&
865 (kx->status != KX_STATE_UP) )
868 GNUNET_free_non_null (kx->ping_received);
869 kx->ping_received = GNUNET_copy_message (msg);
872 m = (const struct PingMessage*) msg;
874 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
875 "Core service receives `%s' request from `%4s'.\n", "PING",
876 GNUNET_i2s (&kx->peer));
878 derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
880 do_decrypt (kx, &iv, &m->target, &t.target,
881 sizeof (struct PingMessage) - ((void *) &m->target -
888 memcmp (&t.target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
893 GNUNET_snprintf (sender, sizeof (sender), "%8s", GNUNET_i2s (&kx->peer));
894 GNUNET_snprintf (peer, sizeof (peer), "%8s", GNUNET_i2s (&t.target));
895 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
896 _("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
897 sender, GNUNET_i2s (&GSC_my_identity), peer);
902 tx.inbound_bw_limit = kx->bw_in; // FIXME!
903 tx.challenge = t.challenge;
904 tx.target = t.target;
905 tp.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
906 tp.header.size = htons (sizeof (struct PongMessage));
908 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
909 derive_pong_iv (&iv, &kx->encrypt_key, tp.iv_seed, t.challenge, &kx->peer);
910 do_encrypt (kx, &iv, &tx.challenge, &tp.challenge,
911 sizeof (struct PongMessage) - ((void *) &tp.challenge -
913 GNUNET_STATISTICS_update (GSC_stats,
914 gettext_noop ("# PONG messages created"), 1,
916 GSC_NEIGHBOURS_transmit (&kx->peer,
918 GNUNET_TIME_UNIT_FOREVER_REL /* FIXME: timeout */);
923 * Create a fresh SET KEY message for transmission to the other peer.
924 * Also creates a new key.
926 * @param kx key exchange context to create SET KEY message for
929 setup_fresh_setkey (struct GSC_KeyExchangeInfo *kx)
931 struct SetKeyMessage *skm;
933 GNUNET_CRYPTO_aes_create_session_key (&kx->encrypt_key);
934 kx->encrypt_key_created = GNUNET_TIME_absolute_get ();
936 skm->header.size = htons (sizeof (struct SetKeyMessage));
937 skm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
939 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
940 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
941 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
942 sizeof (struct GNUNET_PeerIdentity));
943 skm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
944 skm->creation_time = GNUNET_TIME_absolute_hton (kx->encrypt_key_created);
945 skm->target = kx->peer;
946 GNUNET_assert (GNUNET_OK ==
947 GNUNET_CRYPTO_rsa_encrypt (&kx->encrypt_key,
949 GNUNET_CRYPTO_AesSessionKey),
950 kx->public_key, &skm->encrypted_key));
951 GNUNET_assert (GNUNET_OK ==
952 GNUNET_CRYPTO_rsa_sign (my_private_key, &skm->purpose,
958 * Create a fresh PING message for transmission to the other peer.
960 * @param kx key exchange context to create PING for
963 setup_fresh_ping (struct GSC_KeyExchangeInfo *kx)
965 struct PingMessage pp;
966 struct PingMessage *pm;
967 struct GNUNET_CRYPTO_AesInitializationVector iv;
970 pm->header.size = htons (sizeof (struct PingMessage));
971 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
973 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
974 derive_iv (&iv, &kx->encrypt_key, pm->iv_seed, &kx->peer);
975 pp.challenge = kx->ping_challenge;
976 pp.target = kx->peer;
977 do_encrypt (kx, &iv, &pp.target, &pm->target,
978 sizeof (struct PingMessage) - ((void *) &pm->target -
984 * Task triggered when a neighbour entry is about to time out
985 * (and we should prevent this by sending a PING).
987 * @param cls the 'struct GSC_KeyExchangeInfo'
988 * @param tc scheduler context (not used)
991 send_keep_alive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
993 struct GSC_KeyExchangeInfo *kx = cls;
994 struct GNUNET_TIME_Relative retry;
995 struct GNUNET_TIME_Relative left;
997 kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
998 left = GNUNET_TIME_absolute_get_remaining (kx->timeout);
999 if (left.rel_value == 0)
1001 GSC_SESSIONS_end (&kx->peer);
1002 kx->status = KX_STATE_DOWN;
1005 setup_fresh_ping (kx);
1006 GSC_NEIGHBOURS_transmit (&kx->peer,
1008 kx->set_key_retry_frequency);
1010 GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1011 MIN_PING_FREQUENCY);
1012 kx->keep_alive_task =
1013 GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx);
1018 * We've seen a valid message from the other peer.
1019 * Update the time when the session would time out
1020 * and delay sending our keep alive message further.
1022 * @param kx key exchange where we saw activity
1025 update_timeout (struct GSC_KeyExchangeInfo *kx)
1027 kx->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1028 if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1029 GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1030 kx->keep_alive_task =
1031 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
1032 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1033 2), &send_keep_alive, kx);
1038 * We received a PONG message. Validate and update our status.
1040 * @param kx key exchange context for the the PONG
1041 * @param m the encrypted PONG message itself
1044 GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx, const struct GNUNET_MessageHeader *msg)
1046 const struct PongMessage *m;
1047 struct PongMessage t;
1048 struct GNUNET_CRYPTO_AesInitializationVector iv;
1051 msize = ntohs (msg->size);
1052 if (msize != sizeof (struct PongMessage))
1054 GNUNET_break_op (0);
1057 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages received"),
1060 if ( (kx->status != KX_STATE_KEY_RECEIVED) &&
1061 (kx->status != KX_STATE_UP) )
1063 if (kx->status == KX_STATE_KEY_SENT)
1065 GNUNET_free_non_null (kx->pong_received);
1066 kx->pong_received = GNUNET_copy_message (msg);
1070 m = (const struct PongMessage*) msg;
1072 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1073 "Core service receives `%s' response from `%4s'.\n", "PONG",
1074 GNUNET_i2s (&kx->peer));
1076 /* mark as garbage, just to be sure */
1077 memset (&t, 255, sizeof (t));
1078 derive_pong_iv (&iv, &kx->decrypt_key, m->iv_seed, kx->ping_challenge,
1081 do_decrypt (kx, &iv, &m->challenge, &t.challenge,
1082 sizeof (struct PongMessage) - ((void *) &m->challenge -
1085 GNUNET_break_op (0);
1088 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages decrypted"),
1090 if ((0 != memcmp (&t.target, &kx->peer, sizeof (struct GNUNET_PeerIdentity)))
1091 || (kx->ping_challenge != t.challenge))
1093 /* PONG malformed */
1095 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1096 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
1097 "PONG", GNUNET_i2s (&kx->peer),
1098 (unsigned int) kx->ping_challenge);
1099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1100 "Received malformed `%s' received from `%4s' with challenge %u\n",
1101 "PONG", GNUNET_i2s (&t.target), (unsigned int) t.challenge);
1108 GNUNET_break (0); /* should be impossible */
1110 case KX_STATE_KEY_SENT:
1111 GNUNET_break (0); /* should be impossible */
1113 case KX_STATE_KEY_RECEIVED:
1114 GNUNET_STATISTICS_update (GSC_stats,
1116 ("# Session keys confirmed via PONG"), 1,
1118 kx->status = KX_STATE_UP;
1119 GSC_SESSIONS_create (&kx->peer, kx);
1120 GNUNET_assert (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK);
1121 GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1122 kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1123 GNUNET_assert (kx->keep_alive_task == GNUNET_SCHEDULER_NO_TASK);
1124 update_timeout (kx);
1127 update_timeout (kx);
1137 * Send our key (and encrypted PING) to the other peer.
1139 * @param kx key exchange context
1142 send_key (struct GSC_KeyExchangeInfo *kx)
1144 GNUNET_assert (kx->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK);
1145 if (KX_STATE_UP == kx->status)
1146 return; /* nothing to do */
1147 if (kx->public_key == NULL)
1149 /* lookup public key, then try again */
1151 GNUNET_PEERINFO_iterate (peerinfo, &kx->peer,
1152 GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */,
1153 &process_hello, kx);
1161 kx->status = KX_STATE_KEY_SENT;
1162 /* setup SET KEY message */
1163 setup_fresh_setkey (kx);
1164 setup_fresh_ping (kx);
1165 GNUNET_STATISTICS_update (GSC_stats,
1167 ("# SET_KEY and PING messages created"), 1,
1170 case KX_STATE_KEY_SENT:
1172 case KX_STATE_KEY_RECEIVED:
1182 /* always update sender status in SET KEY message */
1183 kx->skm.sender_status = htonl ((int32_t) kx->status);
1185 GSC_NEIGHBOURS_transmit (&kx->peer,
1187 kx->set_key_retry_frequency);
1188 GSC_NEIGHBOURS_transmit (&kx->peer,
1190 kx->set_key_retry_frequency);
1191 kx->retry_set_key_task =
1192 GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
1193 &set_key_retry_task, kx);
1198 * Encrypt and transmit a message with the given payload.
1200 * @param kx key exchange context
1201 * @param bw_in bandwidth limit to transmit to the other peer;
1202 * the other peer shall not send us more than the
1204 * @param payload payload of the message
1205 * @param payload_size number of bytes in 'payload'
1208 GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
1209 struct GNUNET_BANDWIDTH_Value32NBO bw_in,
1210 const void *payload,
1211 size_t payload_size)
1213 size_t used = payload_size + sizeof (struct EncryptedMessage);
1214 char pbuf[used]; /* plaintext */
1215 char cbuf[used]; /* ciphertext */
1216 struct EncryptedMessage *em; /* encrypted message */
1217 struct EncryptedMessage *ph; /* plaintext header */
1218 struct GNUNET_CRYPTO_AesInitializationVector iv;
1219 struct GNUNET_CRYPTO_AuthKey auth_key;
1221 #if DEBUG_CORE_QUOTA
1222 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1223 "Sending %u b/s as new limit to peer `%4s'\n",
1224 (unsigned int) ntohl (bw_in.value__),
1225 GNUNET_i2s (&kx->peer));
1227 ph = (struct EncryptedMessage*) pbuf;
1229 htonl (GNUNET_CRYPTO_random_u32
1230 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
1231 ph->sequence_number = htonl (++kx->last_sequence_number_sent);
1232 ph->inbound_bw_limit = bw_in;
1233 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1234 memcpy (&ph[1], payload, payload_size);
1236 em = (struct EncryptedMessage *) cbuf;
1237 em->header.size = htons (used);
1238 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1239 em->iv_seed = ph->iv_seed;
1240 derive_iv (&iv, &kx->encrypt_key, ph->iv_seed, &kx->peer);
1241 GNUNET_assert (GNUNET_OK ==
1242 do_encrypt (kx, &iv, &ph->sequence_number, &em->sequence_number,
1243 used - ENCRYPTED_HEADER_SIZE));
1244 derive_auth_key (&auth_key, &kx->encrypt_key, ph->iv_seed,
1245 kx->encrypt_key_created);
1246 GNUNET_CRYPTO_hmac (&auth_key, &em->sequence_number,
1247 used - ENCRYPTED_HEADER_SIZE, &em->hmac);
1248 GSC_NEIGHBOURS_transmit (&kx->peer,
1250 GNUNET_TIME_UNIT_FOREVER_REL);
1255 * Closure for 'deliver_message'
1257 struct DeliverMessageContext
1261 * Performance information for the connection.
1263 const struct GNUNET_TRANSPORT_ATS_Information *atsi;
1266 * Sender of the message.
1268 const struct GNUNET_PeerIdentity *peer;
1271 * Number of entries in 'atsi' array.
1273 uint32_t atsi_count;
1278 * We received an encrypted message. Decrypt, validate and
1279 * pass on to the appropriate clients.
1281 * @param kx key exchange context for encrypting the message
1282 * @param m encrypted message
1283 * @param atsi performance data
1284 * @param atsi_count number of entries in ats (excluding 0-termination)
1287 GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *kx,
1288 const struct GNUNET_MessageHeader *msg,
1289 const struct GNUNET_TRANSPORT_ATS_Information *atsi,
1290 uint32_t atsi_count)
1292 const struct EncryptedMessage *m;
1293 struct EncryptedMessage *pt; /* plaintext */
1296 struct GNUNET_TIME_Absolute t;
1297 struct GNUNET_CRYPTO_AesInitializationVector iv;
1298 struct GNUNET_CRYPTO_AuthKey auth_key;
1299 struct DeliverMessageContext dmc;
1300 uint16_t size = ntohs (msg->size);
1304 sizeof (struct EncryptedMessage) + sizeof (struct GNUNET_MessageHeader))
1306 GNUNET_break_op (0);
1309 m = (const struct EncryptedMessage*) msg;
1310 if ( (kx->status != KX_STATE_KEY_RECEIVED) &&
1311 (kx->status != KX_STATE_UP) )
1313 GNUNET_STATISTICS_update (GSC_stats,
1315 ("# failed to decrypt message (no session key)"),
1320 derive_auth_key (&auth_key, &kx->decrypt_key, m->iv_seed,
1321 kx->decrypt_key_created);
1322 GNUNET_CRYPTO_hmac (&auth_key, &m->sequence_number,
1323 size - ENCRYPTED_HEADER_SIZE, &ph);
1324 if (0 != memcmp (&ph, &m->hmac, sizeof (GNUNET_HashCode)))
1326 /* checksum failed */
1327 GNUNET_break_op (0);
1330 derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
1333 do_decrypt (kx, &iv, &m->sequence_number, &buf[ENCRYPTED_HEADER_SIZE],
1334 size - ENCRYPTED_HEADER_SIZE))
1336 pt = (struct EncryptedMessage *) buf;
1338 /* validate sequence number */
1339 snum = ntohl (pt->sequence_number);
1340 if (kx->last_sequence_number_received == snum)
1342 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1343 "Received duplicate message, ignoring.\n");
1344 /* duplicate, ignore */
1345 GNUNET_STATISTICS_update (GSC_stats,
1346 gettext_noop ("# bytes dropped (duplicates)"),
1350 if ((kx->last_sequence_number_received > snum) &&
1351 (kx->last_sequence_number_received - snum > 32))
1353 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1354 "Received ancient out of sequence message, ignoring.\n");
1355 /* ancient out of sequence, ignore */
1356 GNUNET_STATISTICS_update (GSC_stats,
1358 ("# bytes dropped (out of sequence)"), size,
1362 if (kx->last_sequence_number_received > snum)
1364 unsigned int rotbit = 1 << (kx->last_sequence_number_received - snum - 1);
1366 if ((kx->last_packets_bitmap & rotbit) != 0)
1368 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1369 "Received duplicate message, ignoring.\n");
1370 GNUNET_STATISTICS_update (GSC_stats,
1371 gettext_noop ("# bytes dropped (duplicates)"),
1373 /* duplicate, ignore */
1376 kx->last_packets_bitmap |= rotbit;
1378 if (kx->last_sequence_number_received < snum)
1380 unsigned int shift = (snum - kx->last_sequence_number_received);
1382 if (shift >= 8 * sizeof (kx->last_packets_bitmap))
1383 kx->last_packets_bitmap = 0;
1385 kx->last_packets_bitmap <<= shift;
1386 kx->last_sequence_number_received = snum;
1389 /* check timestamp */
1390 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
1391 if (GNUNET_TIME_absolute_get_duration (t).rel_value >
1392 MAX_MESSAGE_AGE.rel_value)
1394 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1395 _("Message received far too old (%llu ms). Content ignored.\n"),
1396 GNUNET_TIME_absolute_get_duration (t).rel_value);
1397 GNUNET_STATISTICS_update (GSC_stats,
1399 ("# bytes dropped (ancient message)"), size,
1404 /* process decrypted message(s) */
1405 update_timeout (kx);
1406 GSC_SESSIONS_update (&kx->peer,
1407 pt->inbound_bw_limit);
1408 GNUNET_STATISTICS_update (GSC_stats,
1409 gettext_noop ("# bytes of payload decrypted"),
1410 size - sizeof (struct EncryptedMessage), GNUNET_NO);
1412 dmc.atsi_count = atsi_count;
1413 dmc.peer = &kx->peer;
1415 GNUNET_SERVER_mst_receive (mst, &dmc, &buf[sizeof (struct EncryptedMessage)],
1416 size - sizeof (struct EncryptedMessage),
1417 GNUNET_YES, GNUNET_NO))
1418 GNUNET_break_op (0);
1423 * Deliver P2P message to interested clients.
1424 * Invokes send twice, once for clients that want the full message, and once
1425 * for clients that only want the header
1427 * @param cls always NULL
1428 * @param client who sent us the message (struct GSC_KeyExchangeInfo)
1429 * @param m the message
1432 deliver_message (void *cls, void *client, const struct GNUNET_MessageHeader *m)
1434 struct DeliverMessageContext *dmc = client;
1436 GSC_CLIENTS_deliver_message (dmc->peer,
1437 dmc->atsi, dmc->atsi_count,
1440 GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
1441 GSC_CLIENTS_deliver_message (dmc->peer,
1442 dmc->atsi, dmc->atsi_count,
1444 sizeof (struct GNUNET_MessageHeader),
1445 GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
1450 * Initialize KX subsystem.
1452 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1460 GNUNET_CONFIGURATION_get_value_filename (GSC_cfg, "GNUNETD", "HOSTKEY",
1463 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1464 _("Core service is lacking HOSTKEY configuration setting. Exiting.\n"));
1465 return GNUNET_SYSERR;
1467 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1468 GNUNET_free (keyfile);
1469 if (my_private_key == NULL)
1471 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1472 _("Core service could not access hostkey. Exiting.\n"));
1473 return GNUNET_SYSERR;
1475 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1476 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1477 &GSC_my_identity.hashPubKey);
1478 peerinfo = GNUNET_PEERINFO_connect (GSC_cfg);
1479 if (NULL == peerinfo)
1481 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1482 _("Could not access PEERINFO service. Exiting.\n"));
1483 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1484 my_private_key = NULL;
1485 return GNUNET_SYSERR;
1487 mst = GNUNET_SERVER_mst_create (&deliver_message, NULL);
1493 * Shutdown KX subsystem.
1498 if (my_private_key != NULL)
1500 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1501 my_private_key = NULL;
1503 if (peerinfo != NULL)
1505 GNUNET_PEERINFO_disconnect (peerinfo);
1510 GNUNET_SERVER_mst_destroy (mst);
1515 /* end of gnunet-service-core_kx.c */