2 This file is part of GNUnet.
3 Copyright (C) 2009-2013, 2016 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your 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 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * @file core/gnunet-service-core_kx.c
21 * @brief code for managing the key exchange (SET_KEY, PING, PONG) with other peers
22 * @author Christian Grothoff
25 #include "gnunet-service-core_kx.h"
26 #include "gnunet-service-core.h"
27 #include "gnunet-service-core_sessions.h"
28 #include "gnunet_statistics_service.h"
29 #include "gnunet_transport_core_service.h"
30 #include "gnunet_constants.h"
31 #include "gnunet_signatures.h"
32 #include "gnunet_protocols.h"
36 * Enable expensive (and possibly problematic for privacy!) logging of KX.
41 * How long do we wait for SET_KEY confirmation initially?
43 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
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 * How often do we rekey?
53 #define REKEY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
56 * What time difference do we tolerate?
58 #define REKEY_TOLERANCE GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
61 * What is the maximum age of a message for us to consider processing
62 * it? Note that this looks at the timestamp used by the other peer,
63 * so clock skew between machines does come into play here. So this
64 * should be picked high enough so that a little bit of clock skew
65 * does not prevent peers from connecting to us.
67 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
71 GNUNET_NETWORK_STRUCT_BEGIN
74 * Message transmitted with the signed ephemeral key of a peer. The
75 * session key is then derived from the two ephemeral keys (ECDHE).
77 struct EphemeralKeyMessage
81 * Message type is #GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY.
83 struct GNUNET_MessageHeader header;
86 * Status of the sender (should be in `enum PeerStateMachine`), nbo.
88 int32_t sender_status GNUNET_PACKED;
91 * An ECC signature of the @e origin_identity asserting the validity
92 * of the given ephemeral key.
94 struct GNUNET_CRYPTO_EddsaSignature signature;
97 * Information about what is being signed.
99 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
102 * At what time was this key created (beginning of validity).
104 struct GNUNET_TIME_AbsoluteNBO creation_time;
107 * When does the given ephemeral key expire (end of validity).
109 struct GNUNET_TIME_AbsoluteNBO expiration_time;
112 * Ephemeral public ECC key.
114 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral_key;
117 * Public key of the signing peer (persistent version, not the
118 * ephemeral public key).
120 struct GNUNET_PeerIdentity origin_identity;
126 * We're sending an (encrypted) PING to the other peer to check if he
127 * can decrypt. The other peer should respond with a PONG with the
128 * same content, except this time encrypted with the receiver's key.
133 * Message type is #GNUNET_MESSAGE_TYPE_CORE_PING.
135 struct GNUNET_MessageHeader header;
140 uint32_t iv_seed GNUNET_PACKED;
143 * Intended target of the PING, used primarily to check
144 * that decryption actually worked.
146 struct GNUNET_PeerIdentity target;
149 * Random number chosen to make replay harder.
151 uint32_t challenge GNUNET_PACKED;
156 * Response to a PING. Includes data from the original PING.
161 * Message type is #GNUNET_MESSAGE_TYPE_CORE_PONG.
163 struct GNUNET_MessageHeader header;
168 uint32_t iv_seed GNUNET_PACKED;
171 * Random number to make replay attacks harder.
173 uint32_t challenge GNUNET_PACKED;
176 * Reserved, always zero.
181 * Intended target of the PING, used primarily to check
182 * that decryption actually worked.
184 struct GNUNET_PeerIdentity target;
189 * Encapsulation for encrypted messages exchanged between
190 * peers. Followed by the actual encrypted data.
192 struct EncryptedMessage
195 * Message type is #GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE.
197 struct GNUNET_MessageHeader header;
200 * Random value used for IV generation.
202 uint32_t iv_seed GNUNET_PACKED;
205 * MAC of the encrypted message (starting at @e sequence_number),
206 * used to verify message integrity. Everything after this value
207 * (excluding this value itself) will be encrypted and
208 * authenticated. #ENCRYPTED_HEADER_SIZE must be set to the offset
209 * of the *next* field.
211 struct GNUNET_HashCode hmac;
214 * Sequence number, in network byte order. This field
215 * must be the first encrypted/decrypted field
217 uint32_t sequence_number GNUNET_PACKED;
220 * Reserved, always zero.
222 uint32_t reserved GNUNET_PACKED;
225 * Timestamp. Used to prevent replay of ancient messages
226 * (recent messages are caught with the sequence number).
228 struct GNUNET_TIME_AbsoluteNBO timestamp;
231 GNUNET_NETWORK_STRUCT_END
235 * Number of bytes (at the beginning) of `struct EncryptedMessage`
236 * that are NOT encrypted.
238 #define ENCRYPTED_HEADER_SIZE (offsetof(struct EncryptedMessage, sequence_number))
242 * Information about the status of a key exchange with another peer.
244 struct GSC_KeyExchangeInfo
250 struct GSC_KeyExchangeInfo *next;
255 struct GSC_KeyExchangeInfo *prev;
258 * Identity of the peer.
260 const struct GNUNET_PeerIdentity *peer;
263 * Message queue for sending messages to @a peer.
265 struct GNUNET_MQ_Handle *mq;
268 * Our message stream tokenizer (for encrypted payload).
270 struct GNUNET_MessageStreamTokenizer *mst;
273 * PING message we transmit to the other peer.
275 struct PingMessage ping;
278 * Ephemeral public ECC key of the other peer.
280 struct GNUNET_CRYPTO_EcdhePublicKey other_ephemeral_key;
283 * Key we use to encrypt our messages for the other peer
284 * (initialized by us when we do the handshake).
286 struct GNUNET_CRYPTO_SymmetricSessionKey encrypt_key;
289 * Key we use to decrypt messages from the other peer
290 * (given to us by the other peer during the handshake).
292 struct GNUNET_CRYPTO_SymmetricSessionKey decrypt_key;
295 * At what time did the other peer generate the decryption key?
297 struct GNUNET_TIME_Absolute foreign_key_expires;
300 * When should the session time out (if there are no PONGs)?
302 struct GNUNET_TIME_Absolute timeout;
305 * What was the last timeout we informed our monitors about?
307 struct GNUNET_TIME_Absolute last_notify_timeout;
310 * At what frequency are we currently re-trying SET_KEY messages?
312 struct GNUNET_TIME_Relative set_key_retry_frequency;
315 * ID of task used for re-trying SET_KEY and PING message.
317 struct GNUNET_SCHEDULER_Task *retry_set_key_task;
320 * ID of task used for sending keep-alive pings.
322 struct GNUNET_SCHEDULER_Task *keep_alive_task;
325 * Bit map indicating which of the 32 sequence numbers before the
326 * last were received (good for accepting out-of-order packets and
327 * estimating reliability of the connection)
329 uint32_t last_packets_bitmap;
332 * last sequence number received on this connection (highest)
334 uint32_t last_sequence_number_received;
337 * last sequence number transmitted
339 uint32_t last_sequence_number_sent;
342 * What was our PING challenge number (for this peer)?
344 uint32_t ping_challenge;
347 * #GNUNET_YES if this peer currently has excess bandwidth.
349 int has_excess_bandwidth;
352 * What is our connection status?
354 enum GNUNET_CORE_KxState status;
362 static struct GNUNET_TRANSPORT_CoreHandle *transport;
367 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
370 * Our ephemeral private key.
372 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
375 * Current message we send for a key exchange.
377 static struct EphemeralKeyMessage current_ekm;
382 static struct GSC_KeyExchangeInfo *kx_head;
387 static struct GSC_KeyExchangeInfo *kx_tail;
390 * Task scheduled for periodic re-generation (and thus rekeying) of our
393 static struct GNUNET_SCHEDULER_Task *rekey_task;
396 * Notification context for broadcasting to monitors.
398 static struct GNUNET_NotificationContext *nc;
402 * Calculate seed value we should use for a message.
404 * @param kx key exchange context
407 calculate_seed (struct GSC_KeyExchangeInfo *kx)
409 /* Note: may want to make this non-random and instead
410 derive from key material to avoid having an undetectable
412 return htonl (GNUNET_CRYPTO_random_u32
413 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
418 * Inform all monitors about the KX state of the given peer.
420 * @param kx key exchange state to inform about
423 monitor_notify_all (struct GSC_KeyExchangeInfo *kx)
425 struct MonitorNotifyMessage msg;
427 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY);
428 msg.header.size = htons (sizeof (msg));
429 msg.state = htonl ((uint32_t) kx->status);
430 msg.peer = *kx->peer;
431 msg.timeout = GNUNET_TIME_absolute_hton (kx->timeout);
432 GNUNET_notification_context_broadcast (nc,
435 kx->last_notify_timeout = kx->timeout;
440 * Derive an authentication key from "set key" information
442 * @param akey authentication key to derive
443 * @param skey session key to use
444 * @param seed seed to use
447 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
448 const struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
451 static const char ctx[] = "authentication key";
453 struct GNUNET_HashCode sh;
455 GNUNET_CRYPTO_hash (skey,
458 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
459 "Deriving Auth key from SKEY %s and seed %u\n",
461 (unsigned int) seed);
463 GNUNET_CRYPTO_hmac_derive_key (akey,
465 &seed, sizeof (seed),
466 skey, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
473 * Derive an IV from packet information
475 * @param iv initialization vector to initialize
476 * @param skey session key to use
477 * @param seed seed to use
478 * @param identity identity of the other peer to use
481 derive_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
482 const struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
484 const struct GNUNET_PeerIdentity *identity)
486 static const char ctx[] = "initialization vector";
488 struct GNUNET_HashCode sh;
490 GNUNET_CRYPTO_hash (skey,
493 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
494 "Deriving IV from SKEY %s and seed %u for peer %s\n",
497 GNUNET_i2s (identity));
499 GNUNET_CRYPTO_symmetric_derive_iv (iv,
501 &seed, sizeof (seed),
503 sizeof (struct GNUNET_PeerIdentity), ctx,
509 * Derive an IV from pong packet information
511 * @param iv initialization vector to initialize
512 * @param skey session key to use
513 * @param seed seed to use
514 * @param challenge nonce to use
515 * @param identity identity of the other peer to use
518 derive_pong_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
519 const struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
522 const struct GNUNET_PeerIdentity *identity)
524 static const char ctx[] = "pong initialization vector";
526 struct GNUNET_HashCode sh;
528 GNUNET_CRYPTO_hash (skey,
531 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
532 "Deriving PONG IV from SKEY %s and seed %u/%u for %s\n",
535 (unsigned int) challenge,
536 GNUNET_i2s (identity));
538 GNUNET_CRYPTO_symmetric_derive_iv (iv,
540 &seed, sizeof (seed),
542 sizeof (struct GNUNET_PeerIdentity),
543 &challenge, sizeof (challenge),
550 * Derive an AES key from key material
552 * @param sender peer identity of the sender
553 * @param receiver peer identity of the sender
554 * @param key_material high entropy key material to use
555 * @param skey set to derived session key
558 derive_aes_key (const struct GNUNET_PeerIdentity *sender,
559 const struct GNUNET_PeerIdentity *receiver,
560 const struct GNUNET_HashCode *key_material,
561 struct GNUNET_CRYPTO_SymmetricSessionKey *skey)
563 static const char ctx[] = "aes key generation vector";
565 struct GNUNET_HashCode sh;
567 GNUNET_CRYPTO_hash (skey,
570 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
571 "Deriving AES Keys for %s to %s from %s\n",
573 GNUNET_i2s2 (receiver),
574 GNUNET_h2s (key_material));
576 GNUNET_CRYPTO_kdf (skey, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
578 key_material, sizeof (struct GNUNET_HashCode),
579 sender, sizeof (struct GNUNET_PeerIdentity),
580 receiver, sizeof (struct GNUNET_PeerIdentity),
586 * Encrypt size bytes from @a in and write the result to @a out. Use the
587 * @a kx key for outbound traffic of the given neighbour.
589 * @param kx key information context
590 * @param iv initialization vector to use
591 * @param in ciphertext
592 * @param out plaintext
593 * @param size size of @a in/@a out
594 * @return #GNUNET_OK on success
597 do_encrypt (struct GSC_KeyExchangeInfo *kx,
598 const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
603 if (size != (uint16_t) size)
608 GNUNET_assert (size ==
609 GNUNET_CRYPTO_symmetric_encrypt (in,
614 GNUNET_STATISTICS_update (GSC_stats,
615 gettext_noop ("# bytes encrypted"),
618 /* the following is too sensitive to write to log files by accident,
619 so we require manual intervention to get this one... */
621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
622 "Encrypted %u bytes for `%s' using key %u, IV %u\n",
624 GNUNET_i2s (kx->peer),
625 (unsigned int) kx->encrypt_key.crc32,
626 GNUNET_CRYPTO_crc32_n (iv,
634 * Decrypt size bytes from @a in and write the result to @a out. Use
635 * the @a kx key for inbound traffic of the given neighbour. This
636 * function does NOT do any integrity-checks on the result.
638 * @param kx key information context
639 * @param iv initialization vector to use
640 * @param in ciphertext
641 * @param out plaintext
642 * @param size size of @a in / @a out
643 * @return #GNUNET_OK on success
646 do_decrypt (struct GSC_KeyExchangeInfo *kx,
647 const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
652 if (size != (uint16_t) size)
657 if ( (kx->status != GNUNET_CORE_KX_STATE_KEY_RECEIVED) &&
658 (kx->status != GNUNET_CORE_KX_STATE_UP) &&
659 (kx->status != GNUNET_CORE_KX_STATE_REKEY_SENT) )
662 return GNUNET_SYSERR;
665 GNUNET_CRYPTO_symmetric_decrypt (in,
672 return GNUNET_SYSERR;
674 GNUNET_STATISTICS_update (GSC_stats,
675 gettext_noop ("# bytes decrypted"),
678 /* the following is too sensitive to write to log files by accident,
679 so we require manual intervention to get this one... */
681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
682 "Decrypted %u bytes from `%s' using key %u, IV %u\n",
684 GNUNET_i2s (kx->peer),
685 (unsigned int) kx->decrypt_key.crc32,
686 GNUNET_CRYPTO_crc32_n (iv,
695 * Send our key (and encrypted PING) to the other peer.
697 * @param kx key exchange context
700 send_key (struct GSC_KeyExchangeInfo *kx);
704 * Task that will retry #send_key() if our previous attempt failed.
706 * @param cls our `struct GSC_KeyExchangeInfo`
709 set_key_retry_task (void *cls)
711 struct GSC_KeyExchangeInfo *kx = cls;
713 kx->retry_set_key_task = NULL;
714 kx->set_key_retry_frequency = GNUNET_TIME_STD_BACKOFF (kx->set_key_retry_frequency);
715 GNUNET_assert (GNUNET_CORE_KX_STATE_DOWN != kx->status);
721 * Create a fresh PING message for transmission to the other peer.
723 * @param kx key exchange context to create PING for
726 setup_fresh_ping (struct GSC_KeyExchangeInfo *kx)
728 struct PingMessage pp;
729 struct PingMessage *pm;
730 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
733 kx->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
735 pm->header.size = htons (sizeof (struct PingMessage));
736 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
737 pm->iv_seed = calculate_seed (kx);
742 pp.challenge = kx->ping_challenge;
743 pp.target = *kx->peer;
748 sizeof (struct PingMessage) - ((void *) &pm->target -
754 * Deliver P2P message to interested clients. Invokes send twice,
755 * once for clients that want the full message, and once for clients
756 * that only want the header
758 * @param cls the `struct GSC_KeyExchangeInfo`
759 * @param m the message
760 * @return #GNUNET_OK on success,
761 * #GNUNET_NO to stop further processing (no error)
762 * #GNUNET_SYSERR to stop further processing with error
765 deliver_message (void *cls,
766 const struct GNUNET_MessageHeader *m)
768 struct GSC_KeyExchangeInfo *kx = cls;
770 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
771 "Decrypted message of type %d from %s\n",
773 GNUNET_i2s (kx->peer));
774 if (GNUNET_CORE_KX_STATE_UP != kx->status)
776 GNUNET_STATISTICS_update (GSC_stats,
777 gettext_noop ("# PAYLOAD dropped (out of order)"),
782 switch (ntohs (m->type))
784 case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP:
785 case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP:
786 GSC_SESSIONS_set_typemap (kx->peer, m);
788 case GNUNET_MESSAGE_TYPE_CORE_CONFIRM_TYPE_MAP:
789 GSC_SESSIONS_confirm_typemap (kx->peer, m);
792 GSC_CLIENTS_deliver_message (kx->peer,
795 GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
796 GSC_CLIENTS_deliver_message (kx->peer,
798 sizeof (struct GNUNET_MessageHeader),
799 GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
806 * Function called by transport to notify us that
807 * a peer connected to us (on the network level).
808 * Starts the key exchange with the given peer.
810 * @param cls closure (NULL)
811 * @param pid identity of the peer to do a key exchange with
812 * @return key exchange information context
815 handle_transport_notify_connect (void *cls,
816 const struct GNUNET_PeerIdentity *pid,
817 struct GNUNET_MQ_Handle *mq)
819 struct GSC_KeyExchangeInfo *kx;
820 struct GNUNET_HashCode h1;
821 struct GNUNET_HashCode h2;
823 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
824 "Initiating key exchange with `%s'\n",
826 GNUNET_STATISTICS_update (GSC_stats,
827 gettext_noop ("# key exchanges initiated"),
830 kx = GNUNET_new (struct GSC_KeyExchangeInfo);
831 kx->mst = GNUNET_MST_create (&deliver_message,
835 kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
836 GNUNET_CONTAINER_DLL_insert (kx_head,
839 kx->status = GNUNET_CORE_KX_STATE_KEY_SENT;
840 monitor_notify_all (kx);
841 GNUNET_CRYPTO_hash (pid,
842 sizeof (struct GNUNET_PeerIdentity),
844 GNUNET_CRYPTO_hash (&GSC_my_identity,
845 sizeof (struct GNUNET_PeerIdentity),
847 if (0 < GNUNET_CRYPTO_hash_cmp (&h1,
850 /* peer with "lower" identity starts KX, otherwise we typically end up
851 with both peers starting the exchange and transmit the 'set key'
857 /* peer with "higher" identity starts a delayed KX, if the "lower" peer
858 * does not start a KX since he sees no reasons to do so */
859 kx->retry_set_key_task
860 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
869 * Function called by transport telling us that a peer
871 * Stop key exchange with the given peer. Clean up key material.
874 * @param peer the peer that disconnected
875 * @param handler_cls the `struct GSC_KeyExchangeInfo` of the peer
878 handle_transport_notify_disconnect (void *cls,
879 const struct GNUNET_PeerIdentity *peer,
882 struct GSC_KeyExchangeInfo *kx = handler_cls;
884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
885 "Peer `%s' disconnected from us.\n",
887 GSC_SESSIONS_end (kx->peer);
888 GNUNET_STATISTICS_update (GSC_stats,
889 gettext_noop ("# key exchanges stopped"),
892 if (NULL != kx->retry_set_key_task)
894 GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
895 kx->retry_set_key_task = NULL;
897 if (NULL != kx->keep_alive_task)
899 GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
900 kx->keep_alive_task = NULL;
902 kx->status = GNUNET_CORE_KX_PEER_DISCONNECT;
903 monitor_notify_all (kx);
904 GNUNET_CONTAINER_DLL_remove (kx_head,
907 GNUNET_MST_destroy (kx->mst);
913 * Send our PING to the other peer.
915 * @param kx key exchange context
918 send_ping (struct GSC_KeyExchangeInfo *kx)
920 struct GNUNET_MQ_Envelope *env;
922 GNUNET_STATISTICS_update (GSC_stats,
923 gettext_noop ("# PING messages transmitted"),
926 env = GNUNET_MQ_msg_copy (&kx->ping.header);
927 GNUNET_MQ_send (kx->mq,
933 * Derive fresh session keys from the current ephemeral keys.
935 * @param kx session to derive keys for
938 derive_session_keys (struct GSC_KeyExchangeInfo *kx)
940 struct GNUNET_HashCode key_material;
943 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
944 &kx->other_ephemeral_key,
950 derive_aes_key (&GSC_my_identity,
954 derive_aes_key (kx->peer,
958 memset (&key_material, 0, sizeof (key_material));
959 /* fresh key, reset sequence numbers */
960 kx->last_sequence_number_received = 0;
961 kx->last_packets_bitmap = 0;
962 setup_fresh_ping (kx);
967 * We received a #GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY message.
968 * Validate and update our key material and status.
970 * @param cls key exchange status for the corresponding peer
971 * @param m the set key message we received
974 handle_ephemeral_key (void *cls,
975 const struct EphemeralKeyMessage *m)
977 struct GSC_KeyExchangeInfo *kx = cls;
978 struct GNUNET_TIME_Absolute start_t;
979 struct GNUNET_TIME_Absolute end_t;
980 struct GNUNET_TIME_Absolute now;
981 enum GNUNET_CORE_KxState sender_status;
983 end_t = GNUNET_TIME_absolute_ntoh (m->expiration_time);
984 if ( ( (GNUNET_CORE_KX_STATE_KEY_RECEIVED == kx->status) ||
985 (GNUNET_CORE_KX_STATE_UP == kx->status) ||
986 (GNUNET_CORE_KX_STATE_REKEY_SENT == kx->status) ) &&
987 (end_t.abs_value_us < kx->foreign_key_expires.abs_value_us) )
989 GNUNET_STATISTICS_update (GSC_stats,
990 gettext_noop ("# old ephemeral keys ignored"),
993 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
994 "Received expired EPHEMERAL_KEY from %s\n",
995 GNUNET_i2s (&m->origin_identity));
998 if (0 == memcmp (&m->ephemeral_key,
999 &kx->other_ephemeral_key,
1000 sizeof (m->ephemeral_key)))
1002 GNUNET_STATISTICS_update (GSC_stats,
1003 gettext_noop ("# duplicate ephemeral keys ignored"),
1006 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1007 "Ignoring duplicate EPHEMERAL_KEY from %s\n",
1008 GNUNET_i2s (&m->origin_identity));
1012 memcmp (&m->origin_identity,
1014 sizeof (struct GNUNET_PeerIdentity)))
1016 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1017 "Received EPHEMERAL_KEY from %s, but expected %s\n",
1018 GNUNET_i2s (&m->origin_identity),
1019 GNUNET_i2s_full (kx->peer));
1020 GNUNET_break_op (0);
1023 if ((ntohl (m->purpose.size) !=
1024 sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
1025 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1026 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1027 sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) +
1028 sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)) ||
1030 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY,
1033 &m->origin_identity.public_key)))
1035 /* invalid signature */
1036 GNUNET_break_op (0);
1037 GNUNET_STATISTICS_update (GSC_stats,
1038 gettext_noop ("# EPHEMERAL_KEYs rejected (bad signature)"),
1041 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1042 "Received EPHEMERAL_KEY from %s with bad signature\n",
1043 GNUNET_i2s (&m->origin_identity));
1046 now = GNUNET_TIME_absolute_get ();
1047 start_t = GNUNET_TIME_absolute_ntoh (m->creation_time);
1048 if ( (end_t.abs_value_us < GNUNET_TIME_absolute_subtract (now, REKEY_TOLERANCE).abs_value_us) ||
1049 (start_t.abs_value_us > GNUNET_TIME_absolute_add (now, REKEY_TOLERANCE).abs_value_us) )
1051 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1052 _("EPHEMERAL_KEY from peer `%s' rejected as its validity range does not match our system time (%llu not in [%llu,%llu]).\n"),
1053 GNUNET_i2s (kx->peer),
1054 (unsigned long long) now.abs_value_us,
1055 (unsigned long long) start_t.abs_value_us,
1056 (unsigned long long) end_t.abs_value_us);
1057 GNUNET_STATISTICS_update (GSC_stats,
1058 gettext_noop ("# EPHEMERAL_KEY messages rejected due to time"),
1065 struct GNUNET_HashCode eh;
1067 GNUNET_CRYPTO_hash (&m->ephemeral_key,
1068 sizeof (m->ephemeral_key),
1070 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1071 "Received valid EPHEMERAL_KEY `%s' from `%s' in state %d.\n",
1073 GNUNET_i2s (kx->peer),
1077 GNUNET_STATISTICS_update (GSC_stats,
1078 gettext_noop ("# valid ephemeral keys received"),
1081 kx->other_ephemeral_key = m->ephemeral_key;
1082 kx->foreign_key_expires = end_t;
1083 derive_session_keys (kx);
1085 /* check if we still need to send the sender our key */
1086 sender_status = (enum GNUNET_CORE_KxState) ntohl (m->sender_status);
1087 switch (sender_status)
1089 case GNUNET_CORE_KX_STATE_DOWN:
1090 GNUNET_break_op (0);
1092 case GNUNET_CORE_KX_STATE_KEY_SENT:
1093 /* fine, need to send our key after updating our status, see below */
1094 GSC_SESSIONS_reinit (kx->peer);
1096 case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
1097 /* other peer already got our key, but typemap did go down */
1098 GSC_SESSIONS_reinit (kx->peer);
1100 case GNUNET_CORE_KX_STATE_UP:
1101 /* other peer already got our key, typemap NOT down */
1103 case GNUNET_CORE_KX_STATE_REKEY_SENT:
1104 /* other peer already got our key, typemap NOT down */
1110 /* check if we need to confirm everything is fine via PING + PONG */
1113 case GNUNET_CORE_KX_STATE_DOWN:
1114 GNUNET_assert (NULL == kx->keep_alive_task);
1115 kx->status = GNUNET_CORE_KX_STATE_KEY_RECEIVED;
1116 monitor_notify_all (kx);
1117 if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
1122 case GNUNET_CORE_KX_STATE_KEY_SENT:
1123 GNUNET_assert (NULL == kx->keep_alive_task);
1124 kx->status = GNUNET_CORE_KX_STATE_KEY_RECEIVED;
1125 monitor_notify_all (kx);
1126 if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
1131 case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
1132 GNUNET_assert (NULL == kx->keep_alive_task);
1133 if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
1138 case GNUNET_CORE_KX_STATE_UP:
1139 kx->status = GNUNET_CORE_KX_STATE_REKEY_SENT;
1140 monitor_notify_all (kx);
1141 if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
1146 case GNUNET_CORE_KX_STATE_REKEY_SENT:
1147 if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
1160 * We received a PING message. Validate and transmit
1163 * @param cls key exchange status for the corresponding peer
1164 * @param m the encrypted PING message itself
1167 handle_ping (void *cls,
1168 const struct PingMessage *m)
1170 struct GSC_KeyExchangeInfo *kx = cls;
1171 struct PingMessage t;
1172 struct PongMessage tx;
1173 struct PongMessage *tp;
1174 struct GNUNET_MQ_Envelope *env;
1175 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1177 GNUNET_STATISTICS_update (GSC_stats,
1178 gettext_noop ("# PING messages received"),
1181 if ( (kx->status != GNUNET_CORE_KX_STATE_KEY_RECEIVED) &&
1182 (kx->status != GNUNET_CORE_KX_STATE_UP) &&
1183 (kx->status != GNUNET_CORE_KX_STATE_REKEY_SENT))
1186 GNUNET_STATISTICS_update (GSC_stats,
1187 gettext_noop ("# PING messages dropped (out of order)"),
1192 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1193 "Core service receives PING request from `%s'.\n",
1194 GNUNET_i2s (kx->peer));
1204 sizeof (struct PingMessage) - ((void *) &m->target -
1207 GNUNET_break_op (0);
1213 sizeof (struct GNUNET_PeerIdentity)))
1215 if (GNUNET_CORE_KX_STATE_REKEY_SENT != kx->status)
1216 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1217 "Decryption of PING from peer `%s' failed, PING for `%s'?\n",
1218 GNUNET_i2s (kx->peer),
1219 GNUNET_i2s2 (&t.target));
1221 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1222 "Decryption of PING from peer `%s' failed after rekey (harmless)\n",
1223 GNUNET_i2s (kx->peer));
1224 GNUNET_break_op (0);
1227 /* construct PONG */
1229 tx.challenge = t.challenge;
1230 tx.target = t.target;
1231 env = GNUNET_MQ_msg (tp,
1232 GNUNET_MESSAGE_TYPE_CORE_PONG);
1233 tp->iv_seed = calculate_seed (kx);
1234 derive_pong_iv (&iv,
1243 sizeof (struct PongMessage) - ((void *) &tp->challenge -
1245 GNUNET_STATISTICS_update (GSC_stats,
1246 gettext_noop ("# PONG messages created"),
1249 GNUNET_MQ_send (kx->mq,
1255 * Task triggered when a neighbour entry is about to time out
1256 * (and we should prevent this by sending a PING).
1258 * @param cls the `struct GSC_KeyExchangeInfo`
1261 send_keep_alive (void *cls)
1263 struct GSC_KeyExchangeInfo *kx = cls;
1264 struct GNUNET_TIME_Relative retry;
1265 struct GNUNET_TIME_Relative left;
1267 kx->keep_alive_task = NULL;
1268 left = GNUNET_TIME_absolute_get_remaining (kx->timeout);
1269 if (0 == left.rel_value_us)
1271 GNUNET_STATISTICS_update (GSC_stats,
1272 gettext_noop ("# sessions terminated by timeout"),
1275 GSC_SESSIONS_end (kx->peer);
1276 kx->status = GNUNET_CORE_KX_STATE_KEY_SENT;
1277 monitor_notify_all (kx);
1281 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1282 "Sending KEEPALIVE to `%s'\n",
1283 GNUNET_i2s (kx->peer));
1284 GNUNET_STATISTICS_update (GSC_stats,
1285 gettext_noop ("# keepalive messages sent"),
1288 setup_fresh_ping (kx);
1291 GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1292 MIN_PING_FREQUENCY);
1293 kx->keep_alive_task =
1294 GNUNET_SCHEDULER_add_delayed (retry,
1301 * We've seen a valid message from the other peer.
1302 * Update the time when the session would time out
1303 * and delay sending our keep alive message further.
1305 * @param kx key exchange where we saw activity
1308 update_timeout (struct GSC_KeyExchangeInfo *kx)
1310 struct GNUNET_TIME_Relative delta;
1313 GNUNET_TIME_relative_to_absolute
1314 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1315 delta = GNUNET_TIME_absolute_get_difference (kx->last_notify_timeout,
1317 if (delta.rel_value_us > 5LL * 1000LL * 1000LL)
1319 /* we only notify monitors about timeout changes if those
1320 are bigger than the threshold (5s) */
1321 monitor_notify_all (kx);
1323 if (NULL != kx->keep_alive_task)
1324 GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1325 kx->keep_alive_task =
1326 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
1327 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1335 * We received a PONG message. Validate and update our status.
1337 * @param kx key exchange context for the the PONG
1338 * @param m the encrypted PONG message itself
1341 handle_pong (void *cls,
1342 const struct PongMessage *m)
1344 struct GSC_KeyExchangeInfo *kx = cls;
1345 struct PongMessage t;
1346 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1348 GNUNET_STATISTICS_update (GSC_stats,
1349 gettext_noop ("# PONG messages received"),
1354 case GNUNET_CORE_KX_STATE_DOWN:
1355 GNUNET_STATISTICS_update (GSC_stats,
1356 gettext_noop ("# PONG messages dropped (connection down)"), 1,
1359 case GNUNET_CORE_KX_STATE_KEY_SENT:
1360 GNUNET_STATISTICS_update (GSC_stats,
1361 gettext_noop ("# PONG messages dropped (out of order)"), 1,
1364 case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
1366 case GNUNET_CORE_KX_STATE_UP:
1368 case GNUNET_CORE_KX_STATE_REKEY_SENT:
1374 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1375 "Core service receives PONG response from `%s'.\n",
1376 GNUNET_i2s (kx->peer));
1377 /* mark as garbage, just to be sure */
1378 memset (&t, 255, sizeof (t));
1379 derive_pong_iv (&iv,
1389 sizeof (struct PongMessage) - ((void *) &m->challenge -
1392 GNUNET_break_op (0);
1395 GNUNET_STATISTICS_update (GSC_stats,
1396 gettext_noop ("# PONG messages decrypted"),
1399 if ((0 != memcmp (&t.target,
1401 sizeof (struct GNUNET_PeerIdentity))) ||
1402 (kx->ping_challenge != t.challenge))
1404 /* PONG malformed */
1405 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1406 "Received malformed PONG wanted sender `%s' with challenge %u\n",
1407 GNUNET_i2s (kx->peer),
1408 (unsigned int) kx->ping_challenge);
1409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1410 "Received malformed PONG received from `%s' with challenge %u\n",
1411 GNUNET_i2s (&t.target),
1412 (unsigned int) t.challenge);
1415 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1416 "Received valid PONG from `%s'\n",
1417 GNUNET_i2s (kx->peer));
1418 /* no need to resend key any longer */
1419 if (NULL != kx->retry_set_key_task)
1421 GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1422 kx->retry_set_key_task = NULL;
1426 case GNUNET_CORE_KX_STATE_DOWN:
1427 GNUNET_assert (0); /* should be impossible */
1429 case GNUNET_CORE_KX_STATE_KEY_SENT:
1430 GNUNET_assert (0); /* should be impossible */
1432 case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
1433 GNUNET_STATISTICS_update (GSC_stats,
1434 gettext_noop ("# session keys confirmed via PONG"),
1437 kx->status = GNUNET_CORE_KX_STATE_UP;
1438 monitor_notify_all (kx);
1439 GSC_SESSIONS_create (kx->peer, kx);
1440 GNUNET_assert (NULL == kx->keep_alive_task);
1441 update_timeout (kx);
1443 case GNUNET_CORE_KX_STATE_UP:
1444 GNUNET_STATISTICS_update (GSC_stats,
1445 gettext_noop ("# timeouts prevented via PONG"),
1448 update_timeout (kx);
1450 case GNUNET_CORE_KX_STATE_REKEY_SENT:
1451 GNUNET_STATISTICS_update (GSC_stats,
1452 gettext_noop ("# rekey operations confirmed via PONG"),
1455 kx->status = GNUNET_CORE_KX_STATE_UP;
1456 monitor_notify_all (kx);
1457 update_timeout (kx);
1467 * Send our key to the other peer.
1469 * @param kx key exchange context
1472 send_key (struct GSC_KeyExchangeInfo *kx)
1474 struct GNUNET_MQ_Envelope *env;
1476 GNUNET_assert (GNUNET_CORE_KX_STATE_DOWN != kx->status);
1477 if (NULL != kx->retry_set_key_task)
1479 GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1480 kx->retry_set_key_task = NULL;
1482 /* always update sender status in SET KEY message */
1485 struct GNUNET_HashCode hc;
1487 GNUNET_CRYPTO_hash (¤t_ekm.ephemeral_key,
1488 sizeof (current_ekm.ephemeral_key),
1490 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1491 "Sending EPHEMERAL_KEY %s to `%s' (my status: %d)\n",
1493 GNUNET_i2s (kx->peer),
1497 current_ekm.sender_status = htonl ((int32_t) (kx->status));
1498 env = GNUNET_MQ_msg_copy (¤t_ekm.header);
1499 GNUNET_MQ_send (kx->mq,
1501 if (GNUNET_CORE_KX_STATE_KEY_SENT != kx->status)
1503 kx->retry_set_key_task =
1504 GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
1505 &set_key_retry_task,
1511 * Encrypt and transmit a message with the given payload.
1513 * @param kx key exchange context
1514 * @param payload payload of the message
1515 * @param payload_size number of bytes in @a payload
1518 GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
1519 const void *payload,
1520 size_t payload_size)
1522 size_t used = payload_size + sizeof (struct EncryptedMessage);
1523 char pbuf[used]; /* plaintext */
1524 struct EncryptedMessage *em; /* encrypted message */
1525 struct EncryptedMessage *ph; /* plaintext header */
1526 struct GNUNET_MQ_Envelope *env;
1527 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1528 struct GNUNET_CRYPTO_AuthKey auth_key;
1530 ph = (struct EncryptedMessage *) pbuf;
1531 ph->sequence_number = htonl (++kx->last_sequence_number_sent);
1532 ph->iv_seed = calculate_seed (kx);
1534 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1535 GNUNET_memcpy (&ph[1],
1538 env = GNUNET_MQ_msg_extra (em,
1540 GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1541 em->iv_seed = ph->iv_seed;
1546 GNUNET_assert (GNUNET_OK ==
1549 &ph->sequence_number,
1550 &em->sequence_number,
1551 used - ENCRYPTED_HEADER_SIZE));
1554 struct GNUNET_HashCode hc;
1556 GNUNET_CRYPTO_hash (&ph->sequence_number,
1557 used - ENCRYPTED_HEADER_SIZE,
1559 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1560 "Encrypted payload `%s' of %u bytes for %s\n",
1562 (unsigned int) (used - ENCRYPTED_HEADER_SIZE),
1563 GNUNET_i2s (kx->peer));
1566 derive_auth_key (&auth_key,
1569 GNUNET_CRYPTO_hmac (&auth_key,
1570 &em->sequence_number,
1571 used - ENCRYPTED_HEADER_SIZE,
1575 struct GNUNET_HashCode hc;
1577 GNUNET_CRYPTO_hash (&auth_key,
1580 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1581 "For peer %s, used AC %s to create hmac %s\n",
1582 GNUNET_i2s (kx->peer),
1584 GNUNET_h2s2 (&em->hmac));
1587 kx->has_excess_bandwidth = GNUNET_NO;
1588 GNUNET_MQ_send (kx->mq,
1594 * We received an encrypted message. Check that it is
1595 * well-formed (size-wise).
1597 * @param cls key exchange context for encrypting the message
1598 * @param m encrypted message
1599 * @return #GNUNET_OK if @a msg is well-formed (size-wise)
1602 check_encrypted (void *cls,
1603 const struct EncryptedMessage *m)
1605 uint16_t size = ntohs (m->header.size) - sizeof (*m);
1607 if (size < sizeof (struct GNUNET_MessageHeader))
1609 GNUNET_break_op (0);
1610 return GNUNET_SYSERR;
1617 * We received an encrypted message. Decrypt, validate and
1618 * pass on to the appropriate clients.
1620 * @param cls key exchange context for encrypting the message
1621 * @param m encrypted message
1624 handle_encrypted (void *cls,
1625 const struct EncryptedMessage *m)
1627 struct GSC_KeyExchangeInfo *kx = cls;
1628 struct EncryptedMessage *pt; /* plaintext */
1629 struct GNUNET_HashCode ph;
1631 struct GNUNET_TIME_Absolute t;
1632 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1633 struct GNUNET_CRYPTO_AuthKey auth_key;
1634 uint16_t size = ntohs (m->header.size);
1635 char buf[size] GNUNET_ALIGN;
1637 if (GNUNET_CORE_KX_STATE_UP != kx->status)
1639 GNUNET_STATISTICS_update (GSC_stats,
1640 gettext_noop ("# DATA message dropped (out of order)"),
1645 if (0 == GNUNET_TIME_absolute_get_remaining (kx->foreign_key_expires).rel_value_us)
1647 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1648 _("Session to peer `%s' went down due to key expiration (should not happen)\n"),
1649 GNUNET_i2s (kx->peer));
1650 GNUNET_STATISTICS_update (GSC_stats,
1651 gettext_noop ("# sessions terminated by key expiration"),
1653 GSC_SESSIONS_end (kx->peer);
1654 if (NULL != kx->keep_alive_task)
1656 GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1657 kx->keep_alive_task = NULL;
1659 kx->status = GNUNET_CORE_KX_STATE_KEY_SENT;
1660 monitor_notify_all (kx);
1668 struct GNUNET_HashCode hc;
1670 GNUNET_CRYPTO_hash (&m->sequence_number,
1671 size - ENCRYPTED_HEADER_SIZE,
1673 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1674 "Received encrypted payload `%s' of %u bytes from %s\n",
1676 (unsigned int) (size - ENCRYPTED_HEADER_SIZE),
1677 GNUNET_i2s (kx->peer));
1680 derive_auth_key (&auth_key,
1683 GNUNET_CRYPTO_hmac (&auth_key,
1684 &m->sequence_number,
1685 size - ENCRYPTED_HEADER_SIZE,
1689 struct GNUNET_HashCode hc;
1691 GNUNET_CRYPTO_hash (&auth_key,
1694 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1695 "For peer %s, used AC %s to verify hmac %s\n",
1696 GNUNET_i2s (kx->peer),
1698 GNUNET_h2s2 (&m->hmac));
1701 if (0 != memcmp (&ph,
1703 sizeof (struct GNUNET_HashCode)))
1705 /* checksum failed */
1706 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1707 "Failed checksum validation for a message from `%s'\n",
1708 GNUNET_i2s (kx->peer));
1719 &m->sequence_number,
1720 &buf[ENCRYPTED_HEADER_SIZE],
1721 size - ENCRYPTED_HEADER_SIZE))
1723 GNUNET_break_op (0);
1726 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1727 "Decrypted %u bytes from %s\n",
1728 (unsigned int) (size - ENCRYPTED_HEADER_SIZE),
1729 GNUNET_i2s (kx->peer));
1730 pt = (struct EncryptedMessage *) buf;
1732 /* validate sequence number */
1733 snum = ntohl (pt->sequence_number);
1734 if (kx->last_sequence_number_received == snum)
1736 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1737 "Received duplicate message, ignoring.\n");
1738 /* duplicate, ignore */
1739 GNUNET_STATISTICS_update (GSC_stats,
1740 gettext_noop ("# bytes dropped (duplicates)"),
1745 if ((kx->last_sequence_number_received > snum) &&
1746 (kx->last_sequence_number_received - snum > 32))
1748 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1749 "Received ancient out of sequence message, ignoring.\n");
1750 /* ancient out of sequence, ignore */
1751 GNUNET_STATISTICS_update (GSC_stats,
1753 ("# bytes dropped (out of sequence)"), size,
1757 if (kx->last_sequence_number_received > snum)
1759 uint32_t rotbit = 1U << (kx->last_sequence_number_received - snum - 1);
1761 if ((kx->last_packets_bitmap & rotbit) != 0)
1763 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1764 "Received duplicate message, ignoring.\n");
1765 GNUNET_STATISTICS_update (GSC_stats,
1766 gettext_noop ("# bytes dropped (duplicates)"),
1768 /* duplicate, ignore */
1771 kx->last_packets_bitmap |= rotbit;
1773 if (kx->last_sequence_number_received < snum)
1775 unsigned int shift = (snum - kx->last_sequence_number_received);
1777 if (shift >= 8 * sizeof (kx->last_packets_bitmap))
1778 kx->last_packets_bitmap = 0;
1780 kx->last_packets_bitmap <<= shift;
1781 kx->last_sequence_number_received = snum;
1784 /* check timestamp */
1785 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
1786 if (GNUNET_TIME_absolute_get_duration (t).rel_value_us >
1787 MAX_MESSAGE_AGE.rel_value_us)
1789 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1790 "Message received far too old (%s). Content ignored.\n",
1791 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (t),
1793 GNUNET_STATISTICS_update (GSC_stats,
1795 ("# bytes dropped (ancient message)"), size,
1800 /* process decrypted message(s) */
1801 update_timeout (kx);
1802 GNUNET_STATISTICS_update (GSC_stats,
1803 gettext_noop ("# bytes of payload decrypted"),
1804 size - sizeof (struct EncryptedMessage),
1807 GNUNET_MST_from_buffer (kx->mst,
1808 &buf[sizeof (struct EncryptedMessage)],
1809 size - sizeof (struct EncryptedMessage),
1812 GNUNET_break_op (0);
1817 * One of our neighbours has excess bandwidth, remember this.
1820 * @param pid identity of the peer with excess bandwidth
1821 * @param connect_cls the `struct Neighbour`
1824 handle_transport_notify_excess_bw (void *cls,
1825 const struct GNUNET_PeerIdentity *pid,
1828 struct GSC_KeyExchangeInfo *kx = connect_cls;
1830 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1831 "Peer %s has excess bandwidth available\n",
1833 kx->has_excess_bandwidth = GNUNET_YES;
1834 GSC_SESSIONS_solicit (pid);
1839 * Setup the message that links the ephemeral key to our persistent
1840 * public key and generate the appropriate signature.
1843 sign_ephemeral_key ()
1845 current_ekm.header.size = htons (sizeof (struct EphemeralKeyMessage));
1846 current_ekm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY);
1847 current_ekm.sender_status = 0; /* to be set later */
1848 current_ekm.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY);
1849 current_ekm.purpose.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
1850 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1851 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1852 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
1853 sizeof (struct GNUNET_PeerIdentity));
1854 current_ekm.creation_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1856 GNUNET_CONFIGURATION_get_value_yesno (GSC_cfg,
1858 "USE_EPHEMERAL_KEYS"))
1860 current_ekm.expiration_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_add (REKEY_FREQUENCY,
1865 current_ekm.expiration_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_FOREVER_ABS);
1867 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key,
1868 ¤t_ekm.ephemeral_key);
1869 current_ekm.origin_identity = GSC_my_identity;
1870 GNUNET_assert (GNUNET_OK ==
1871 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1872 ¤t_ekm.purpose,
1873 ¤t_ekm.signature));
1878 * Task run to trigger rekeying.
1880 * @param cls closure, NULL
1883 do_rekey (void *cls)
1885 struct GSC_KeyExchangeInfo *pos;
1887 rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY,
1890 if (NULL != my_ephemeral_key)
1891 GNUNET_free (my_ephemeral_key);
1892 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1893 GNUNET_assert (NULL != my_ephemeral_key);
1894 sign_ephemeral_key ();
1896 struct GNUNET_HashCode eh;
1898 GNUNET_CRYPTO_hash (¤t_ekm.ephemeral_key,
1899 sizeof (current_ekm.ephemeral_key),
1901 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1905 for (pos = kx_head; NULL != pos; pos = pos->next)
1907 if (GNUNET_CORE_KX_STATE_UP == pos->status)
1909 pos->status = GNUNET_CORE_KX_STATE_REKEY_SENT;
1910 monitor_notify_all (pos);
1911 derive_session_keys (pos);
1913 if (GNUNET_CORE_KX_STATE_DOWN == pos->status)
1915 pos->status = GNUNET_CORE_KX_STATE_KEY_SENT;
1916 monitor_notify_all (pos);
1918 monitor_notify_all (pos);
1925 * Initialize KX subsystem.
1927 * @param pk private key to use for the peer
1928 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1931 GSC_KX_init (struct GNUNET_CRYPTO_EddsaPrivateKey *pk)
1933 struct GNUNET_MQ_MessageHandler handlers[] = {
1934 GNUNET_MQ_hd_fixed_size (ephemeral_key,
1935 GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY,
1936 struct EphemeralKeyMessage,
1938 GNUNET_MQ_hd_fixed_size (ping,
1939 GNUNET_MESSAGE_TYPE_CORE_PING,
1942 GNUNET_MQ_hd_fixed_size (pong,
1943 GNUNET_MESSAGE_TYPE_CORE_PONG,
1946 GNUNET_MQ_hd_var_size (encrypted,
1947 GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE,
1948 struct EncryptedMessage,
1950 GNUNET_MQ_handler_end()
1953 my_private_key = pk;
1954 GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
1955 &GSC_my_identity.public_key);
1956 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1957 if (NULL == my_ephemeral_key)
1960 GNUNET_free (my_private_key);
1961 my_private_key = NULL;
1962 return GNUNET_SYSERR;
1964 sign_ephemeral_key ();
1966 struct GNUNET_HashCode eh;
1968 GNUNET_CRYPTO_hash (¤t_ekm.ephemeral_key,
1969 sizeof (current_ekm.ephemeral_key),
1971 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1972 "Starting with ephemeral key %s\n",
1976 nc = GNUNET_notification_context_create (1);
1977 rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY,
1981 = GNUNET_TRANSPORT_core_connect (GSC_cfg,
1985 &handle_transport_notify_connect,
1986 &handle_transport_notify_disconnect,
1987 &handle_transport_notify_excess_bw);
1988 if (NULL == transport)
1991 return GNUNET_SYSERR;
1998 * Shutdown KX subsystem.
2003 if (NULL != transport)
2005 GNUNET_TRANSPORT_core_disconnect (transport);
2008 if (NULL != rekey_task)
2010 GNUNET_SCHEDULER_cancel (rekey_task);
2013 if (NULL != my_ephemeral_key)
2015 GNUNET_free (my_ephemeral_key);
2016 my_ephemeral_key = NULL;
2018 if (NULL != my_private_key)
2020 GNUNET_free (my_private_key);
2021 my_private_key = NULL;
2025 GNUNET_notification_context_destroy (nc);
2032 * Check how many messages are queued for the given neighbour.
2034 * @param kxinfo data about neighbour to check
2035 * @return number of items in the message queue
2038 GSC_NEIGHBOURS_get_queue_length (const struct GSC_KeyExchangeInfo *kxinfo)
2040 return GNUNET_MQ_get_length (kxinfo->mq);
2045 * Check if the given neighbour has excess bandwidth available.
2047 * @param target neighbour to check
2048 * @return #GNUNET_YES if excess bandwidth is available, #GNUNET_NO if not
2051 GSC_NEIGHBOURS_check_excess_bandwidth (const struct GSC_KeyExchangeInfo *kxinfo)
2053 return kxinfo->has_excess_bandwidth;
2058 * Handle #GNUNET_MESSAGE_TYPE_CORE_MONITOR_PEERS request. For this
2059 * request type, the client does not have to have transmitted an INIT
2060 * request. All current peers are returned, regardless of which
2061 * message types they accept.
2063 * @param mq message queue to add for monitoring
2066 GSC_KX_handle_client_monitor_peers (struct GNUNET_MQ_Handle *mq)
2068 struct GNUNET_MQ_Envelope *env;
2069 struct MonitorNotifyMessage *done_msg;
2070 struct GSC_KeyExchangeInfo *kx;
2072 GNUNET_notification_context_add (nc,
2074 for (kx = kx_head; NULL != kx; kx = kx->next)
2076 struct GNUNET_MQ_Envelope *env;
2077 struct MonitorNotifyMessage *msg;
2079 env = GNUNET_MQ_msg (msg,
2080 GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY);
2081 msg->state = htonl ((uint32_t) kx->status);
2082 msg->peer = *kx->peer;
2083 msg->timeout = GNUNET_TIME_absolute_hton (kx->timeout);
2087 env = GNUNET_MQ_msg (done_msg,
2088 GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY);
2089 done_msg->state = htonl ((uint32_t) GNUNET_CORE_KX_ITERATION_FINISHED);
2090 done_msg->timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_FOREVER_ABS);
2096 /* end of gnunet-service-core_kx.c */