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.
101 * Message type is CORE_PONG.
103 struct GNUNET_MessageHeader header;
108 uint32_t iv_seed GNUNET_PACKED;
111 * Random number to make faking the reply harder. Must be
112 * first field after header (this is where we start to encrypt!).
114 uint32_t challenge GNUNET_PACKED;
117 * Reserved, always 'GNUNET_BANDWIDTH_VALUE_MAX'.
119 struct GNUNET_BANDWIDTH_Value32NBO reserved;
122 * Intended target of the PING, used primarily to check
123 * that decryption actually worked.
125 struct GNUNET_PeerIdentity target;
130 * Message transmitted to set (or update) a session key.
136 * Message type is either CORE_SET_KEY.
138 struct GNUNET_MessageHeader header;
141 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
143 int32_t sender_status GNUNET_PACKED;
146 * Purpose of the signature, will be
147 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
149 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
152 * At what time was this key created?
154 struct GNUNET_TIME_AbsoluteNBO creation_time;
157 * The encrypted session key.
159 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
162 * Who is the intended recipient?
164 struct GNUNET_PeerIdentity target;
167 * Signature of the stuff above (starting at purpose).
169 struct GNUNET_CRYPTO_RsaSignature signature;
175 * Encapsulation for encrypted messages exchanged between
176 * peers. Followed by the actual encrypted data.
178 struct EncryptedMessage
181 * Message type is either CORE_ENCRYPTED_MESSAGE.
183 struct GNUNET_MessageHeader header;
186 * Random value used for IV generation.
188 uint32_t iv_seed GNUNET_PACKED;
191 * MAC of the encrypted message (starting at 'sequence_number'),
192 * used to verify message integrity. Everything after this value
193 * (excluding this value itself) will be encrypted and authenticated.
194 * ENCRYPTED_HEADER_SIZE must be set to the offset of the *next* field.
196 GNUNET_HashCode hmac;
199 * Sequence number, in network byte order. This field
200 * must be the first encrypted/decrypted field
202 uint32_t sequence_number GNUNET_PACKED;
205 * Reserved, always 'GNUNET_BANDWIDTH_VALUE_MAX'.
207 struct GNUNET_BANDWIDTH_Value32NBO reserved;
210 * Timestamp. Used to prevent reply of ancient messages
211 * (recent messages are caught with the sequence number).
213 struct GNUNET_TIME_AbsoluteNBO timestamp;
218 * Number of bytes (at the beginning) of "struct EncryptedMessage"
219 * that are NOT encrypted.
221 #define ENCRYPTED_HEADER_SIZE (offsetof(struct EncryptedMessage, sequence_number))
225 * State machine for our P2P encryption handshake. Everyone starts in
226 * "DOWN", if we receive the other peer's key (other peer initiated)
227 * we start in state RECEIVED (since we will immediately send our
228 * own); otherwise we start in SENT. If we get back a PONG from
229 * within either state, we move up to CONFIRMED (the PONG will always
230 * be sent back encrypted with the key we sent to the other peer).
240 * We've sent our session key.
245 * We've received the other peers session key.
247 KX_STATE_KEY_RECEIVED,
250 * The other peer has confirmed our session key with a message
251 * encrypted with his session key (which we got). Key exchange
259 * Information about the status of a key exchange with another peer.
261 struct GSC_KeyExchangeInfo
264 * Identity of the peer.
266 struct GNUNET_PeerIdentity peer;
269 * SetKeyMessage to transmit (initialized the first
270 * time our status goes past 'KX_STATE_KEY_SENT').
272 struct SetKeyMessage skm;
275 * PING message we transmit to the other peer.
277 struct PingMessage ping;
280 * SetKeyMessage we received and did not process yet.
282 struct SetKeyMessage *skm_received;
285 * PING message we received from the other peer and
286 * did not process yet (or NULL).
288 struct PingMessage *ping_received;
291 * PONG message we received from the other peer and
292 * did not process yet (or NULL).
294 struct PongMessage *pong_received;
297 * Encrypted message we received from the other peer and
298 * did not process yet (or NULL).
300 struct EncryptedMessage *emsg_received;
303 * Non-NULL if we are currently looking up HELLOs for this peer.
306 struct GNUNET_PEERINFO_IteratorContext *pitr;
309 * Public key of the neighbour, NULL if we don't have it yet.
311 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
314 * We received a PONG message before we got the "public_key"
315 * (or the SET_KEY). We keep it here until we have a key
316 * to decrypt it. NULL if no PONG is pending.
318 struct PongMessage *pending_pong;
321 * Key we use to encrypt our messages for the other peer
322 * (initialized by us when we do the handshake).
324 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
327 * Key we use to decrypt messages from the other peer
328 * (given to us by the other peer during the handshake).
330 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
333 * At what time did we generate our encryption key?
335 struct GNUNET_TIME_Absolute encrypt_key_created;
338 * At what time did the other peer generate the decryption key?
340 struct GNUNET_TIME_Absolute decrypt_key_created;
343 * When should the session time out (if there are no PONGs)?
345 struct GNUNET_TIME_Absolute timeout;
348 * At what frequency are we currently re-trying SET_KEY messages?
350 struct GNUNET_TIME_Relative set_key_retry_frequency;
353 * ID of task used for re-trying SET_KEY and PING message.
355 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
358 * ID of task used for sending keep-alive pings.
360 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
363 * Bit map indicating which of the 32 sequence numbers before the last
364 * were received (good for accepting out-of-order packets and
365 * estimating reliability of the connection)
367 unsigned int last_packets_bitmap;
370 * last sequence number received on this connection (highest)
372 uint32_t last_sequence_number_received;
375 * last sequence number transmitted
377 uint32_t last_sequence_number_sent;
380 * What was our PING challenge number (for this peer)?
382 uint32_t ping_challenge;
385 * What is our connection status?
387 enum KxStateMachine status;
394 * Handle to peerinfo service.
396 static struct GNUNET_PEERINFO_Handle *peerinfo;
401 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
406 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
409 * Our message stream tokenizer (for encrypted payload).
411 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
416 * Derive an authentication key from "set key" information
419 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
420 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
421 struct GNUNET_TIME_Absolute creation_time)
423 static const char ctx[] = "authentication key";
424 struct GNUNET_TIME_AbsoluteNBO ctbe;
427 ctbe = GNUNET_TIME_absolute_hton (creation_time);
428 GNUNET_CRYPTO_hmac_derive_key (akey, skey, &seed, sizeof (seed), &skey->key,
429 sizeof (skey->key), &ctbe, sizeof (ctbe), ctx,
435 * Derive an IV from packet information
438 derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
439 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
440 const struct GNUNET_PeerIdentity *identity)
442 static const char ctx[] = "initialization vector";
444 GNUNET_CRYPTO_aes_derive_iv (iv, skey, &seed, sizeof (seed),
445 &identity->hashPubKey.bits,
446 sizeof (identity->hashPubKey.bits), ctx,
451 * Derive an IV from pong packet information
454 derive_pong_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
455 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
456 uint32_t challenge, const struct GNUNET_PeerIdentity *identity)
458 static const char ctx[] = "pong initialization vector";
460 GNUNET_CRYPTO_aes_derive_iv (iv, skey, &seed, sizeof (seed),
461 &identity->hashPubKey.bits,
462 sizeof (identity->hashPubKey.bits), &challenge,
463 sizeof (challenge), ctx, sizeof (ctx), NULL);
468 * Encrypt size bytes from in and write the result to out. Use the
469 * key for outbound traffic of the given neighbour.
471 * @param kx key information context
472 * @param iv initialization vector to use
473 * @param in ciphertext
474 * @param out plaintext
475 * @param size size of in/out
476 * @return GNUNET_OK on success
479 do_encrypt (struct GSC_KeyExchangeInfo *kx,
480 const struct GNUNET_CRYPTO_AesInitializationVector *iv,
481 const void *in, void *out, size_t size)
483 if (size != (uint16_t) size)
488 GNUNET_assert (size ==
489 GNUNET_CRYPTO_aes_encrypt (in, (uint16_t) size,
490 &kx->encrypt_key, iv, out));
491 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes encrypted"), size,
494 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
495 "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
496 (unsigned int) size, GNUNET_i2s (&kx->peer),
497 (unsigned int) kx->encrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
508 * Decrypt size bytes from in and write the result to out. Use the
509 * key for inbound traffic of the given neighbour. This function does
510 * NOT do any integrity-checks on the result.
512 * @param kx key information context
513 * @param iv initialization vector to use
514 * @param in ciphertext
515 * @param out plaintext
516 * @param size size of in/out
517 * @return GNUNET_OK on success
520 do_decrypt (struct GSC_KeyExchangeInfo *kx,
521 const struct GNUNET_CRYPTO_AesInitializationVector *iv,
522 const void *in, void *out, size_t size)
524 if (size != (uint16_t) size)
529 if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP))
532 return GNUNET_SYSERR;
535 GNUNET_CRYPTO_aes_decrypt (in, (uint16_t) size, &kx->decrypt_key, iv,
539 return GNUNET_SYSERR;
541 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes decrypted"), size,
544 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
545 "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
546 (unsigned int) size, GNUNET_i2s (&kx->peer),
547 (unsigned int) kx->decrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
556 * Send our key (and encrypted PING) to the other peer.
558 * @param kx key exchange context
561 send_key (struct GSC_KeyExchangeInfo *kx);
565 * Task that will retry "send_key" if our previous attempt failed.
567 * @param cls our 'struct GSC_KeyExchangeInfo'
568 * @param tc scheduler context
571 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
573 struct GSC_KeyExchangeInfo *kx = cls;
575 kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
576 kx->set_key_retry_frequency =
577 GNUNET_TIME_relative_multiply (kx->set_key_retry_frequency, 2);
583 * PEERINFO is giving us a HELLO for a peer. Add the public key to
584 * the neighbour's struct and continue with the key exchange. Or, if
585 * we did not get a HELLO, just do nothing.
587 * @param cls the 'struct GSC_KeyExchangeInfo' to retry sending the key for
588 * @param peer the peer for which this is the HELLO
589 * @param hello HELLO message of that peer
590 * @param err_msg NULL if successful, otherwise contains error message
593 process_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
594 const struct GNUNET_HELLO_Message *hello, const char *err_msg)
596 struct GSC_KeyExchangeInfo *kx = cls;
597 struct SetKeyMessage *skm;
601 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
602 _("Error in communication with PEERINFO service\n"));
609 if (kx->public_key != NULL)
610 return; /* done here */
612 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
613 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
614 GNUNET_i2s (&kx->peer));
616 GNUNET_STATISTICS_update (GSC_stats,
618 ("# Delayed connecting due to lack of public key"),
620 kx->retry_set_key_task =
621 GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
622 &set_key_retry_task, kx);
625 if (kx->public_key != NULL)
627 /* already have public key, why are we here? */
631 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->retry_set_key_task);
633 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
634 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, kx->public_key))
637 GNUNET_free (kx->public_key);
638 kx->public_key = NULL;
642 if (NULL != kx->skm_received)
644 skm = kx->skm_received;
645 kx->skm_received = NULL;
646 GSC_KX_handle_set_key (kx, &skm->header);
653 * Start the key exchange with the given peer.
655 * @param pid identity of the peer to do a key exchange with
656 * @return key exchange information context
658 struct GSC_KeyExchangeInfo *
659 GSC_KX_start (const struct GNUNET_PeerIdentity *pid)
661 struct GSC_KeyExchangeInfo *kx;
664 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Initiating key exchange with `%s'\n",
667 GNUNET_STATISTICS_update (GSC_stats,
668 gettext_noop ("# key exchanges initiated"), 1,
670 kx = GNUNET_malloc (sizeof (struct GSC_KeyExchangeInfo));
672 kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
674 GNUNET_PEERINFO_iterate (peerinfo, pid,
675 GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */ ,
682 * Stop key exchange with the given peer. Clean up key material.
684 * @param kx key exchange to stop
687 GSC_KX_stop (struct GSC_KeyExchangeInfo *kx)
689 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# key exchanges stopped"),
691 if (kx->pitr != NULL)
693 GNUNET_PEERINFO_iterate_cancel (kx->pitr);
696 if (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
698 GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
699 kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
701 if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
703 GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
704 kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
706 GNUNET_free_non_null (kx->skm_received);
707 GNUNET_free_non_null (kx->ping_received);
708 GNUNET_free_non_null (kx->pong_received);
709 GNUNET_free_non_null (kx->emsg_received);
710 GNUNET_free_non_null (kx->public_key);
716 * We received a SET_KEY message. Validate and update
717 * our key material and status.
719 * @param kx key exchange status for the corresponding peer
720 * @param msg the set key message we received
723 GSC_KX_handle_set_key (struct GSC_KeyExchangeInfo *kx,
724 const struct GNUNET_MessageHeader *msg)
726 const struct SetKeyMessage *m;
727 struct GNUNET_TIME_Absolute t;
728 struct GNUNET_CRYPTO_AesSessionKey k;
729 struct PingMessage *ping;
730 struct PongMessage *pong;
731 enum KxStateMachine sender_status;
734 size = ntohs (msg->size);
735 if (size != sizeof (struct SetKeyMessage))
740 m = (const struct SetKeyMessage *) msg;
741 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# session keys received"),
745 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
746 "Core service receives `%s' request from `%4s'.\n", "SET_KEY",
747 GNUNET_i2s (&kx->peer));
749 if (kx->public_key == NULL)
751 GNUNET_free_non_null (kx->skm_received);
752 kx->skm_received = (struct SetKeyMessage *) GNUNET_copy_message (msg);
756 memcmp (&m->target, &GSC_my_identity,
757 sizeof (struct GNUNET_PeerIdentity)))
759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
760 _("`%s' is for `%s', not for me. Ignoring.\n"), "SET_KEY",
761 GNUNET_i2s (&m->target));
764 if ((ntohl (m->purpose.size) !=
765 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
766 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
767 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
768 sizeof (struct GNUNET_PeerIdentity)) ||
770 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY, &m->purpose,
771 &m->signature, kx->public_key)))
773 /* invalid signature */
777 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
778 if (((kx->status == KX_STATE_KEY_RECEIVED) || (kx->status == KX_STATE_UP)) &&
779 (t.abs_value < kx->decrypt_key_created.abs_value))
781 /* this could rarely happen due to massive re-ordering of
782 * messages on the network level, but is most likely either
783 * a bug or some adversary messing with us. Report. */
787 if ((GNUNET_CRYPTO_rsa_decrypt
788 (my_private_key, &m->encrypted_key, &k,
789 sizeof (struct GNUNET_CRYPTO_AesSessionKey)) !=
790 sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
791 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
793 /* failed to decrypt !? */
797 GNUNET_STATISTICS_update (GSC_stats,
798 gettext_noop ("# SET_KEY messages decrypted"), 1,
801 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received SET_KEY from `%s'\n",
802 GNUNET_i2s (&kx->peer));
805 if (kx->decrypt_key_created.abs_value != t.abs_value)
807 /* fresh key, reset sequence numbers */
808 kx->last_sequence_number_received = 0;
809 kx->last_packets_bitmap = 0;
810 kx->decrypt_key_created = t;
812 sender_status = (enum KxStateMachine) ntohl (m->sender_status);
817 kx->status = KX_STATE_KEY_RECEIVED;
818 /* we're not up, so we are already doing 'send_key' */
820 case KX_STATE_KEY_SENT:
821 kx->status = KX_STATE_KEY_RECEIVED;
822 /* we're not up, so we are already doing 'send_key' */
824 case KX_STATE_KEY_RECEIVED:
825 /* we're not up, so we are already doing 'send_key' */
828 if ((sender_status == KX_STATE_DOWN) ||
829 (sender_status == KX_STATE_KEY_SENT))
830 send_key (kx); /* we are up, but other peer is not! */
836 if (kx->ping_received != NULL)
838 ping = kx->ping_received;
839 kx->ping_received = NULL;
840 GSC_KX_handle_ping (kx, &ping->header);
843 if (kx->pong_received != NULL)
845 pong = kx->pong_received;
846 kx->pong_received = NULL;
847 GSC_KX_handle_pong (kx, &pong->header);
854 * We received a PING message. Validate and transmit
857 * @param kx key exchange status for the corresponding peer
858 * @param msg the encrypted PING message itself
861 GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *kx,
862 const struct GNUNET_MessageHeader *msg)
864 const struct PingMessage *m;
865 struct PingMessage t;
866 struct PongMessage tx;
867 struct PongMessage tp;
868 struct GNUNET_CRYPTO_AesInitializationVector iv;
871 msize = ntohs (msg->size);
872 if (msize != sizeof (struct PingMessage))
877 GNUNET_STATISTICS_update (GSC_stats,
878 gettext_noop ("# PING messages received"), 1,
880 if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP))
883 GNUNET_free_non_null (kx->ping_received);
884 kx->ping_received = (struct PingMessage *) GNUNET_copy_message (msg);
887 m = (const struct PingMessage *) msg;
889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
890 "Core service receives `%s' request from `%4s'.\n", "PING",
891 GNUNET_i2s (&kx->peer));
893 derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
895 do_decrypt (kx, &iv, &m->target, &t.target,
896 sizeof (struct PingMessage) - ((void *) &m->target -
903 memcmp (&t.target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
908 GNUNET_snprintf (sender, sizeof (sender), "%8s", GNUNET_i2s (&kx->peer));
909 GNUNET_snprintf (peer, sizeof (peer), "%8s", GNUNET_i2s (&t.target));
910 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
912 ("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
913 sender, GNUNET_i2s (&GSC_my_identity), peer);
918 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PING from `%s'\n",
919 GNUNET_i2s (&kx->peer));
922 tx.reserved = GNUNET_BANDWIDTH_VALUE_MAX;
923 tx.challenge = t.challenge;
924 tx.target = t.target;
925 tp.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
926 tp.header.size = htons (sizeof (struct PongMessage));
928 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
929 derive_pong_iv (&iv, &kx->encrypt_key, tp.iv_seed, t.challenge, &kx->peer);
930 do_encrypt (kx, &iv, &tx.challenge, &tp.challenge,
931 sizeof (struct PongMessage) - ((void *) &tp.challenge -
933 GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages created"),
935 GSC_NEIGHBOURS_transmit (&kx->peer, &tp.header,
936 GNUNET_TIME_UNIT_FOREVER_REL /* FIXME: timeout */ );
941 * Create a fresh SET KEY message for transmission to the other peer.
942 * Also creates a new key.
944 * @param kx key exchange context to create SET KEY message for
947 setup_fresh_setkey (struct GSC_KeyExchangeInfo *kx)
949 struct SetKeyMessage *skm;
951 GNUNET_CRYPTO_aes_create_session_key (&kx->encrypt_key);
952 kx->encrypt_key_created = GNUNET_TIME_absolute_get ();
954 skm->header.size = htons (sizeof (struct SetKeyMessage));
955 skm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
957 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
958 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
959 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
960 sizeof (struct GNUNET_PeerIdentity));
961 skm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
962 skm->creation_time = GNUNET_TIME_absolute_hton (kx->encrypt_key_created);
963 skm->target = kx->peer;
964 GNUNET_assert (GNUNET_OK ==
965 GNUNET_CRYPTO_rsa_encrypt (&kx->encrypt_key,
967 GNUNET_CRYPTO_AesSessionKey),
969 &skm->encrypted_key));
970 GNUNET_assert (GNUNET_OK ==
971 GNUNET_CRYPTO_rsa_sign (my_private_key, &skm->purpose,
977 * Create a fresh PING message for transmission to the other peer.
979 * @param kx key exchange context to create PING for
982 setup_fresh_ping (struct GSC_KeyExchangeInfo *kx)
984 struct PingMessage pp;
985 struct PingMessage *pm;
986 struct GNUNET_CRYPTO_AesInitializationVector iv;
989 pm->header.size = htons (sizeof (struct PingMessage));
990 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
992 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
993 derive_iv (&iv, &kx->encrypt_key, pm->iv_seed, &kx->peer);
994 pp.challenge = kx->ping_challenge;
995 pp.target = kx->peer;
996 do_encrypt (kx, &iv, &pp.target, &pm->target,
997 sizeof (struct PingMessage) - ((void *) &pm->target -
1003 * Task triggered when a neighbour entry is about to time out
1004 * (and we should prevent this by sending a PING).
1006 * @param cls the 'struct GSC_KeyExchangeInfo'
1007 * @param tc scheduler context (not used)
1010 send_keep_alive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1012 struct GSC_KeyExchangeInfo *kx = cls;
1013 struct GNUNET_TIME_Relative retry;
1014 struct GNUNET_TIME_Relative left;
1016 kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1017 left = GNUNET_TIME_absolute_get_remaining (kx->timeout);
1018 if (left.rel_value == 0)
1020 GNUNET_STATISTICS_update (GSC_stats,
1021 gettext_noop ("# sessions terminated by timeout"),
1023 GSC_SESSIONS_end (&kx->peer);
1024 kx->status = KX_STATE_DOWN;
1028 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending KEEPALIVE to `%s'\n",
1029 GNUNET_i2s (&kx->peer));
1031 GNUNET_STATISTICS_update (GSC_stats,
1032 gettext_noop ("# keepalive messages sent"), 1,
1034 setup_fresh_ping (kx);
1035 GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
1036 kx->set_key_retry_frequency);
1038 GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1039 MIN_PING_FREQUENCY);
1040 kx->keep_alive_task =
1041 GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx);
1046 * We've seen a valid message from the other peer.
1047 * Update the time when the session would time out
1048 * and delay sending our keep alive message further.
1050 * @param kx key exchange where we saw activity
1053 update_timeout (struct GSC_KeyExchangeInfo *kx)
1056 GNUNET_TIME_relative_to_absolute
1057 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1058 if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1059 GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1060 kx->keep_alive_task =
1061 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
1062 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1063 2), &send_keep_alive, kx);
1068 * We received a PONG message. Validate and update our status.
1070 * @param kx key exchange context for the the PONG
1071 * @param msg the encrypted PONG message itself
1074 GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx,
1075 const struct GNUNET_MessageHeader *msg)
1077 const struct PongMessage *m;
1078 struct PongMessage t;
1079 struct EncryptedMessage *emsg;
1080 struct GNUNET_CRYPTO_AesInitializationVector iv;
1083 msize = ntohs (msg->size);
1084 if (msize != sizeof (struct PongMessage))
1086 GNUNET_break_op (0);
1089 GNUNET_STATISTICS_update (GSC_stats,
1090 gettext_noop ("# PONG messages received"), 1,
1092 if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP))
1094 if (kx->status == KX_STATE_KEY_SENT)
1096 GNUNET_free_non_null (kx->pong_received);
1097 kx->pong_received = (struct PongMessage *) GNUNET_copy_message (msg);
1101 m = (const struct PongMessage *) msg;
1103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1104 "Core service receives `%s' response from `%4s'.\n", "PONG",
1105 GNUNET_i2s (&kx->peer));
1107 /* mark as garbage, just to be sure */
1108 memset (&t, 255, sizeof (t));
1109 derive_pong_iv (&iv, &kx->decrypt_key, m->iv_seed, kx->ping_challenge,
1112 do_decrypt (kx, &iv, &m->challenge, &t.challenge,
1113 sizeof (struct PongMessage) - ((void *) &m->challenge -
1116 GNUNET_break_op (0);
1119 GNUNET_STATISTICS_update (GSC_stats,
1120 gettext_noop ("# PONG messages decrypted"), 1,
1122 if ((0 != memcmp (&t.target, &kx->peer, sizeof (struct GNUNET_PeerIdentity)))
1123 || (kx->ping_challenge != t.challenge))
1125 /* PONG malformed */
1127 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1128 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
1129 "PONG", GNUNET_i2s (&kx->peer),
1130 (unsigned int) kx->ping_challenge);
1131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1132 "Received malformed `%s' received from `%4s' with challenge %u\n",
1133 "PONG", GNUNET_i2s (&t.target), (unsigned int) t.challenge);
1138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PONG from `%s'\n",
1139 GNUNET_i2s (&kx->peer));
1144 GNUNET_break (0); /* should be impossible */
1146 case KX_STATE_KEY_SENT:
1147 GNUNET_break (0); /* should be impossible */
1149 case KX_STATE_KEY_RECEIVED:
1150 GNUNET_STATISTICS_update (GSC_stats,
1152 ("# session keys confirmed via PONG"), 1,
1154 kx->status = KX_STATE_UP;
1155 GSC_SESSIONS_create (&kx->peer, kx);
1156 GNUNET_assert (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK);
1157 GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1158 kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1159 GNUNET_assert (kx->keep_alive_task == GNUNET_SCHEDULER_NO_TASK);
1160 if (kx->emsg_received != NULL)
1162 emsg = kx->emsg_received;
1163 kx->emsg_received = NULL;
1164 GSC_KX_handle_encrypted_message (kx, &emsg->header, NULL,
1165 0 /* FIXME: ATSI */ );
1168 update_timeout (kx);
1171 update_timeout (kx);
1181 * Send our key (and encrypted PING) to the other peer.
1183 * @param kx key exchange context
1186 send_key (struct GSC_KeyExchangeInfo *kx)
1188 GNUNET_assert (kx->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK);
1189 if (KX_STATE_UP == kx->status)
1190 return; /* nothing to do */
1191 if (kx->public_key == NULL)
1193 /* lookup public key, then try again */
1195 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1196 "Trying to obtain public key for `%s'\n",
1197 GNUNET_i2s (&kx->peer));
1200 GNUNET_PEERINFO_iterate (peerinfo, &kx->peer,
1201 GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */ ,
1202 &process_hello, kx);
1210 kx->status = KX_STATE_KEY_SENT;
1211 /* setup SET KEY message */
1212 setup_fresh_setkey (kx);
1213 setup_fresh_ping (kx);
1214 GNUNET_STATISTICS_update (GSC_stats,
1216 ("# SET_KEY and PING messages created"), 1,
1219 case KX_STATE_KEY_SENT:
1221 case KX_STATE_KEY_RECEIVED:
1231 /* always update sender status in SET KEY message */
1232 kx->skm.sender_status = htonl ((int32_t) kx->status);
1234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending SET_KEY and PING to `%s'\n",
1235 GNUNET_i2s (&kx->peer));
1237 GSC_NEIGHBOURS_transmit (&kx->peer, &kx->skm.header,
1238 kx->set_key_retry_frequency);
1239 GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
1240 kx->set_key_retry_frequency);
1241 kx->retry_set_key_task =
1242 GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
1243 &set_key_retry_task, kx);
1248 * Encrypt and transmit a message with the given payload.
1250 * @param kx key exchange context
1251 * @param payload payload of the message
1252 * @param payload_size number of bytes in 'payload'
1255 GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
1256 const void *payload, size_t payload_size)
1258 size_t used = payload_size + sizeof (struct EncryptedMessage);
1259 char pbuf[used]; /* plaintext */
1260 char cbuf[used]; /* ciphertext */
1261 struct EncryptedMessage *em; /* encrypted message */
1262 struct EncryptedMessage *ph; /* plaintext header */
1263 struct GNUNET_CRYPTO_AesInitializationVector iv;
1264 struct GNUNET_CRYPTO_AuthKey auth_key;
1266 ph = (struct EncryptedMessage *) pbuf;
1268 htonl (GNUNET_CRYPTO_random_u32
1269 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
1270 ph->sequence_number = htonl (++kx->last_sequence_number_sent);
1271 ph->reserved = GNUNET_BANDWIDTH_VALUE_MAX;
1272 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1273 memcpy (&ph[1], payload, payload_size);
1275 em = (struct EncryptedMessage *) cbuf;
1276 em->header.size = htons (used);
1277 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1278 em->iv_seed = ph->iv_seed;
1279 derive_iv (&iv, &kx->encrypt_key, ph->iv_seed, &kx->peer);
1280 GNUNET_assert (GNUNET_OK ==
1281 do_encrypt (kx, &iv, &ph->sequence_number,
1282 &em->sequence_number,
1283 used - ENCRYPTED_HEADER_SIZE));
1285 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Encrypted %u bytes for %s\n",
1286 used - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1288 derive_auth_key (&auth_key, &kx->encrypt_key, ph->iv_seed,
1289 kx->encrypt_key_created);
1290 GNUNET_CRYPTO_hmac (&auth_key, &em->sequence_number,
1291 used - ENCRYPTED_HEADER_SIZE, &em->hmac);
1292 GSC_NEIGHBOURS_transmit (&kx->peer, &em->header,
1293 GNUNET_TIME_UNIT_FOREVER_REL);
1298 * Closure for 'deliver_message'
1300 struct DeliverMessageContext
1304 * Performance information for the connection.
1306 const struct GNUNET_ATS_Information *atsi;
1309 * Sender of the message.
1311 const struct GNUNET_PeerIdentity *peer;
1314 * Number of entries in 'atsi' array.
1316 uint32_t atsi_count;
1321 * We received an encrypted message. Decrypt, validate and
1322 * pass on to the appropriate clients.
1324 * @param kx key exchange context for encrypting the message
1325 * @param msg encrypted message
1326 * @param atsi performance data
1327 * @param atsi_count number of entries in ats (excluding 0-termination)
1330 GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *kx,
1331 const struct GNUNET_MessageHeader *msg,
1332 const struct GNUNET_ATS_Information *atsi,
1333 uint32_t atsi_count)
1335 const struct EncryptedMessage *m;
1336 struct EncryptedMessage *pt; /* plaintext */
1339 struct GNUNET_TIME_Absolute t;
1340 struct GNUNET_CRYPTO_AesInitializationVector iv;
1341 struct GNUNET_CRYPTO_AuthKey auth_key;
1342 struct DeliverMessageContext dmc;
1343 uint16_t size = ntohs (msg->size);
1347 sizeof (struct EncryptedMessage) + sizeof (struct GNUNET_MessageHeader))
1349 GNUNET_break_op (0);
1352 m = (const struct EncryptedMessage *) msg;
1353 if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP))
1355 GNUNET_STATISTICS_update (GSC_stats,
1357 ("# failed to decrypt message (no session key)"),
1361 if (kx->status == KX_STATE_KEY_RECEIVED)
1364 GNUNET_free_non_null (kx->ping_received);
1365 kx->emsg_received = (struct EncryptedMessage *) GNUNET_copy_message (msg);
1369 derive_auth_key (&auth_key, &kx->decrypt_key, m->iv_seed,
1370 kx->decrypt_key_created);
1371 GNUNET_CRYPTO_hmac (&auth_key, &m->sequence_number,
1372 size - ENCRYPTED_HEADER_SIZE, &ph);
1373 if (0 != memcmp (&ph, &m->hmac, sizeof (GNUNET_HashCode)))
1375 /* checksum failed */
1376 GNUNET_break_op (0);
1379 derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
1382 do_decrypt (kx, &iv, &m->sequence_number, &buf[ENCRYPTED_HEADER_SIZE],
1383 size - ENCRYPTED_HEADER_SIZE))
1386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypted %u bytes from %s\n",
1387 size - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
1389 pt = (struct EncryptedMessage *) buf;
1391 /* validate sequence number */
1392 snum = ntohl (pt->sequence_number);
1393 if (kx->last_sequence_number_received == snum)
1395 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1396 "Received duplicate message, ignoring.\n");
1397 /* duplicate, ignore */
1398 GNUNET_STATISTICS_update (GSC_stats,
1399 gettext_noop ("# bytes dropped (duplicates)"),
1403 if ((kx->last_sequence_number_received > snum) &&
1404 (kx->last_sequence_number_received - snum > 32))
1406 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1407 "Received ancient out of sequence message, ignoring.\n");
1408 /* ancient out of sequence, ignore */
1409 GNUNET_STATISTICS_update (GSC_stats,
1411 ("# bytes dropped (out of sequence)"), size,
1415 if (kx->last_sequence_number_received > snum)
1417 unsigned int rotbit = 1 << (kx->last_sequence_number_received - snum - 1);
1419 if ((kx->last_packets_bitmap & rotbit) != 0)
1421 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1422 "Received duplicate message, ignoring.\n");
1423 GNUNET_STATISTICS_update (GSC_stats,
1424 gettext_noop ("# bytes dropped (duplicates)"),
1426 /* duplicate, ignore */
1429 kx->last_packets_bitmap |= rotbit;
1431 if (kx->last_sequence_number_received < snum)
1433 unsigned int shift = (snum - kx->last_sequence_number_received);
1435 if (shift >= 8 * sizeof (kx->last_packets_bitmap))
1436 kx->last_packets_bitmap = 0;
1438 kx->last_packets_bitmap <<= shift;
1439 kx->last_sequence_number_received = snum;
1442 /* check timestamp */
1443 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
1444 if (GNUNET_TIME_absolute_get_duration (t).rel_value >
1445 MAX_MESSAGE_AGE.rel_value)
1447 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1448 _("Message received far too old (%llu ms). Content ignored.\n"),
1449 GNUNET_TIME_absolute_get_duration (t).rel_value);
1450 GNUNET_STATISTICS_update (GSC_stats,
1452 ("# bytes dropped (ancient message)"), size,
1457 /* process decrypted message(s) */
1458 update_timeout (kx);
1459 GNUNET_STATISTICS_update (GSC_stats,
1460 gettext_noop ("# bytes of payload decrypted"),
1461 size - sizeof (struct EncryptedMessage), GNUNET_NO);
1463 dmc.atsi_count = atsi_count;
1464 dmc.peer = &kx->peer;
1466 GNUNET_SERVER_mst_receive (mst, &dmc,
1467 &buf[sizeof (struct EncryptedMessage)],
1468 size - sizeof (struct EncryptedMessage),
1469 GNUNET_YES, GNUNET_NO))
1470 GNUNET_break_op (0);
1475 * Deliver P2P message to interested clients.
1476 * Invokes send twice, once for clients that want the full message, and once
1477 * for clients that only want the header
1479 * @param cls always NULL
1480 * @param client who sent us the message (struct GSC_KeyExchangeInfo)
1481 * @param m the message
1484 deliver_message (void *cls, void *client, const struct GNUNET_MessageHeader *m)
1486 struct DeliverMessageContext *dmc = client;
1488 switch (ntohs (m->type))
1490 case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP:
1491 case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP:
1492 GSC_SESSIONS_set_typemap (dmc->peer, m);
1495 GSC_CLIENTS_deliver_message (dmc->peer, dmc->atsi, dmc->atsi_count, m,
1497 GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
1498 GSC_CLIENTS_deliver_message (dmc->peer, dmc->atsi, dmc->atsi_count, m,
1499 sizeof (struct GNUNET_MessageHeader),
1500 GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
1506 * Initialize KX subsystem.
1508 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1516 GNUNET_CONFIGURATION_get_value_filename (GSC_cfg, "GNUNETD", "HOSTKEY",
1519 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1521 ("Core service is lacking HOSTKEY configuration setting. Exiting.\n"));
1522 return GNUNET_SYSERR;
1524 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1525 GNUNET_free (keyfile);
1526 if (my_private_key == NULL)
1528 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1529 _("Core service could not access hostkey. Exiting.\n"));
1530 return GNUNET_SYSERR;
1532 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1533 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1534 &GSC_my_identity.hashPubKey);
1535 peerinfo = GNUNET_PEERINFO_connect (GSC_cfg);
1536 if (NULL == peerinfo)
1538 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1539 _("Could not access PEERINFO service. Exiting.\n"));
1540 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1541 my_private_key = NULL;
1542 return GNUNET_SYSERR;
1544 mst = GNUNET_SERVER_mst_create (&deliver_message, NULL);
1550 * Shutdown KX subsystem.
1555 if (my_private_key != NULL)
1557 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1558 my_private_key = NULL;
1560 if (peerinfo != NULL)
1562 GNUNET_PEERINFO_disconnect (peerinfo);
1567 GNUNET_SERVER_mst_destroy (mst);
1572 /* end of gnunet-service-core_kx.c */