2 This file is part of GNUnet
3 Copyright (C) 2010-2014, 2018, 2019 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/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file transport/gnunet-communicator-udp.c
23 * @brief Transport plugin using UDP.
24 * @author Christian Grothoff
27 * - consider imposing transmission limits in the absence
28 * of ACKs; or: maybe this should be done at TNG service level?
29 * (at least the receiver might want to enforce limits on
30 * KX/DH operations per sender in here) (#5552)
31 * - overall, we should look more into flow control support
32 * (either in backchannel, or general solution in TNG service)
33 * - handle addresses discovered from broadcasts (#5551)
34 * (think: what was the story again on address validation?
35 * where is the API for that!?!)
36 * - support DNS names in BINDTO option (#5528)
37 * - support NAT connection reversal method (#5529)
38 * - support other UDP-specific NAT traversal methods (#)
41 #include "gnunet_util_lib.h"
42 #include "gnunet_protocols.h"
43 #include "gnunet_signatures.h"
44 #include "gnunet_constants.h"
45 #include "gnunet_nt_lib.h"
46 #include "gnunet_nat_service.h"
47 #include "gnunet_statistics_service.h"
48 #include "gnunet_transport_application_service.h"
49 #include "gnunet_transport_communication_service.h"
52 * How often do we rekey based on time (at least)
54 #define REKEY_TIME_INTERVAL GNUNET_TIME_UNIT_DAYS
57 * How long do we wait until we must have received the initial KX?
59 #define PROTO_QUEUE_TIMEOUT GNUNET_TIME_UNIT_MINUTES
62 * How often do we broadcast our presence on the LAN?
64 #define BROADCAST_FREQUENCY GNUNET_TIME_UNIT_MINUTES
67 * How often do we scan for changes to our network interfaces?
69 #define INTERFACE_SCAN_FREQUENCY \
70 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5)
73 * How long do we believe our addresses to remain up (before
74 * the other peer should revalidate).
76 #define ADDRESS_VALIDITY_PERIOD GNUNET_TIME_UNIT_HOURS
81 #define AES_KEY_SIZE (256 / 8)
86 #define AES_IV_SIZE (96 / 8)
89 * Size of the GCM tag.
91 #define GCM_TAG_SIZE (128 / 8)
94 * If we fall below this number of available KCNs,
95 * we generate additional ACKs until we reach
97 * Should be large enough that we don't generate ACKs all
98 * the time and still have enough time for the ACK to
99 * arrive before the sender runs out. So really this
100 * should ideally be based on the RTT.
102 #define KCN_THRESHOLD 92
105 * How many KCNs do we keep around *after* we hit
106 * the #KCN_THRESHOLD? Should be larger than
107 * #KCN_THRESHOLD so we do not generate just one
110 #define KCN_TARGET 128
113 * What is the maximum delta between KCN sequence numbers
114 * that we allow. Used to expire 'ancient' KCNs that likely
115 * were dropped by the network. Must be larger than
116 * KCN_TARGET (otherwise we generate new KCNs all the time),
117 * but not too large (otherwise packet loss may cause
118 * sender to fall back to KX needlessly when sender runs
119 * out of ACK'ed KCNs due to losses).
121 #define MAX_SQN_DELTA 160
124 * How many shared master secrets do we keep around
125 * at most per sender? Should be large enough so
126 * that we generally have a chance of sending an ACK
127 * before the sender already rotated out the master
128 * secret. Generally values around #KCN_TARGET make
129 * sense. Might make sense to adapt to RTT if we had
130 * a good measurement...
132 #define MAX_SECRETS 128
135 * How often do we rekey based on number of bytes transmitted?
136 * (additionally randomized).
138 #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
141 * Address prefix used by the communicator.
144 #define COMMUNICATOR_ADDRESS_PREFIX "udp"
147 * Configuration section used by the communicator.
149 #define COMMUNICATOR_CONFIG_SECTION "communicator-udp"
151 GNUNET_NETWORK_STRUCT_BEGIN
155 * Signature we use to verify that the ephemeral key was really chosen by
156 * the specified sender. If possible, the receiver should respond with
157 * a `struct UDPAck` (possibly via backchannel).
159 struct UdpHandshakeSignature {
161 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
163 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
166 * Identity of the inititor of the UDP connection (UDP client).
168 struct GNUNET_PeerIdentity sender;
171 * Presumed identity of the target of the UDP connection (UDP server)
173 struct GNUNET_PeerIdentity receiver;
176 * Ephemeral key used by the @e sender.
178 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
181 * Monotonic time of @e sender, to possibly help detect replay attacks
182 * (if receiver persists times by sender).
184 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
189 * "Plaintext" header at beginning of KX message. Followed
190 * by encrypted `struct UDPConfirmation`.
194 * Ephemeral key for KX.
196 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
199 * HMAC for the following encrypted message, using GCM. HMAC uses
200 * key derived from the handshake with sequence number zero.
202 char gcm_tag[GCM_TAG_SIZE];
207 * Encrypted continuation of UDP initial handshake, followed
208 * by message header with payload.
210 struct UDPConfirmation {
214 struct GNUNET_PeerIdentity sender;
217 * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
219 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
222 * Monotonic time of @e sender, to possibly help detect replay attacks
223 * (if receiver persists times by sender).
225 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
227 /* followed by messages */
229 /* padding may follow actual messages */
234 * UDP key acknowledgement. May be sent via backchannel. Allows the
235 * sender to use `struct UDPBox` with the acknowledge key henceforth.
239 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK.
241 struct GNUNET_MessageHeader header;
244 * Sequence acknowledgement limit. Specifies current maximum sequence
245 * number supported by receiver.
247 uint32_t sequence_max GNUNET_PACKED;
250 * CMAC of the base key being acknowledged.
252 struct GNUNET_HashCode cmac;
257 * Signature we use to verify that the broadcast was really made by
258 * the peer that claims to have made it. Basically, affirms that the
259 * peer is really using this IP address (albeit possibly not in _our_
260 * LAN). Makes it difficult for peers in the LAN to claim to
261 * be just any global peer -- an attacker must have at least
262 * shared a LAN with the peer they're pretending to be here.
264 struct UdpBroadcastSignature {
266 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
268 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
271 * Identity of the inititor of the UDP broadcast.
273 struct GNUNET_PeerIdentity sender;
276 * Hash of the sender's UDP address.
278 struct GNUNET_HashCode h_address;
283 * Broadcast by peer in LAN announcing its presence. Unusual in that
284 * we don't pad these to full MTU, as we cannot prevent being
285 * recognized in LAN as GNUnet peers if this feature is enabled
286 * anyway. Also, the entire message is in cleartext.
288 struct UDPBroadcast {
290 * Sender's peer identity.
292 struct GNUNET_PeerIdentity sender;
295 * Sender's signature of type
296 * #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
298 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
303 * UDP message box. Always sent encrypted, only allowed after
304 * the receiver sent a `struct UDPAck` for the base key!
308 * Key and IV identification code. KDF applied to an acknowledged
309 * base key and a sequence number. Sequence numbers must be used
310 * monotonically increasing up to the maximum specified in
311 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
312 * must fall back to sending handshakes!
314 struct GNUNET_ShortHashCode kid;
317 * 128-bit authentication tag for the following encrypted message,
318 * from GCM. MAC starts at the @e body_start that follows and
319 * extends until the end of the UDP payload. If the @e hmac is
320 * wrong, the receiver should check if the message might be a
321 * `struct UdpHandshakeSignature`.
323 char gcm_tag[GCM_TAG_SIZE];
327 GNUNET_NETWORK_STRUCT_END
330 * Shared secret we generated for a particular sender or receiver.
336 * Pre-generated "kid" code (key and IV identification code) to
337 * quickly derive master key for a `struct UDPBox`.
339 struct KeyCacheEntry {
343 struct KeyCacheEntry *next;
348 struct KeyCacheEntry *prev;
351 * Key and IV identification code. KDF applied to an acknowledged
352 * base key and a sequence number. Sequence numbers must be used
353 * monotonically increasing up to the maximum specified in
354 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
355 * must fall back to sending handshakes!
357 struct GNUNET_ShortHashCode kid;
360 * Corresponding shared secret.
362 struct SharedSecret *ss;
365 * Sequence number used to derive this entry from master key.
367 uint32_t sequence_number;
372 * Information we track per sender address we have recently been
373 * in contact with (decryption from sender).
375 struct SenderAddress;
378 * Information we track per receiving address we have recently been
379 * in contact with (encryption to receiver).
381 struct ReceiverAddress;
384 * Shared secret we generated for a particular sender or receiver.
386 struct SharedSecret {
390 struct SharedSecret *next;
395 struct SharedSecret *prev;
398 * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
400 struct KeyCacheEntry *kce_head;
403 * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
405 struct KeyCacheEntry *kce_tail;
408 * Sender we use this shared secret with, or NULL.
410 struct SenderAddress *sender;
413 * Receiver we use this shared secret with, or NULL.
415 struct ReceiverAddress *receiver;
418 * Master shared secret.
420 struct GNUNET_HashCode master;
423 * CMAC is used to identify @e master in ACKs.
425 struct GNUNET_HashCode cmac;
428 * Up to which sequence number did we use this @e master already?
429 * (for encrypting only)
431 uint32_t sequence_used;
434 * Up to which sequence number did the other peer allow us to use
435 * this key, or up to which number did we allow the other peer to
438 uint32_t sequence_allowed;
441 * Number of active KCN entries.
443 unsigned int active_kce_count;
448 * Information we track per sender address we have recently been
449 * in contact with (we decrypt messages from the sender).
451 struct SenderAddress {
453 * To whom are we talking to.
455 struct GNUNET_PeerIdentity target;
458 * Entry in sender expiration heap.
460 struct GNUNET_CONTAINER_HeapNode *hn;
463 * Shared secrets we used with @e target, first used is head.
465 struct SharedSecret *ss_head;
468 * Shared secrets we used with @e target, last used is tail.
470 struct SharedSecret *ss_tail;
473 * Address of the other peer.
475 struct sockaddr *address;
478 * Length of the address.
480 socklen_t address_len;
483 * Timeout for this sender.
485 struct GNUNET_TIME_Absolute timeout;
488 * Length of the DLL at @a ss_head.
490 unsigned int num_secrets;
493 * Which network type does this queue use?
495 enum GNUNET_NetworkType nt;
500 * Information we track per receiving address we have recently been
501 * in contact with (encryption to receiver).
503 struct ReceiverAddress {
505 * To whom are we talking to.
507 struct GNUNET_PeerIdentity target;
510 * Shared secrets we received from @e target, first used is head.
512 struct SharedSecret *ss_head;
515 * Shared secrets we received with @e target, last used is tail.
517 struct SharedSecret *ss_tail;
520 * Address of the receiver in the human-readable format
521 * with the #COMMUNICATOR_ADDRESS_PREFIX.
526 * Address of the other peer.
528 struct sockaddr *address;
531 * Length of the address.
533 socklen_t address_len;
536 * Entry in sender expiration heap.
538 struct GNUNET_CONTAINER_HeapNode *hn;
541 * Message queue we are providing for the #ch.
543 struct GNUNET_MQ_Handle *mq;
546 * handle for this queue with the #ch.
548 struct GNUNET_TRANSPORT_QueueHandle *qh;
551 * Timeout for this receiver address.
553 struct GNUNET_TIME_Absolute timeout;
556 * MTU we allowed transport for this receiver right now.
561 * Length of the DLL at @a ss_head.
563 unsigned int num_secrets;
566 * Number of BOX keys from ACKs we have currently
567 * available for this receiver.
569 unsigned int acks_available;
572 * Which network type does this queue use?
574 enum GNUNET_NetworkType nt;
579 * Interface we broadcast our presence on.
581 struct BroadcastInterface {
585 struct BroadcastInterface *next;
590 struct BroadcastInterface *prev;
593 * Task for this broadcast interface.
595 struct GNUNET_SCHEDULER_Task *broadcast_task;
598 * Sender's address of the interface.
603 * Broadcast address to use on the interface.
608 * Message we broadcast on this interface.
610 struct UDPBroadcast bcm;
613 * If this is an IPv6 interface, this is the request
614 * we use to join/leave the group.
616 struct ipv6_mreq mcreq;
619 * Number of bytes in @e sa.
624 * Was this interface found in the last #iface_proc() scan?
631 * Cache of pre-generated key IDs.
633 static struct GNUNET_CONTAINER_MultiShortmap *key_cache;
638 static struct GNUNET_SCHEDULER_Task *read_task;
643 static struct GNUNET_SCHEDULER_Task *timeout_task;
646 * ID of master broadcast task
648 static struct GNUNET_SCHEDULER_Task *broadcast_task;
651 * For logging statistics.
653 static struct GNUNET_STATISTICS_Handle *stats;
658 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
661 * Receivers (map from peer identity to `struct ReceiverAddress`)
663 static struct GNUNET_CONTAINER_MultiPeerMap *receivers;
666 * Senders (map from peer identity to `struct SenderAddress`)
668 static struct GNUNET_CONTAINER_MultiPeerMap *senders;
671 * Expiration heap for senders (contains `struct SenderAddress`)
673 static struct GNUNET_CONTAINER_Heap *senders_heap;
676 * Expiration heap for receivers (contains `struct ReceiverAddress`)
678 static struct GNUNET_CONTAINER_Heap *receivers_heap;
681 * Broadcast interface tasks. Kept in a DLL.
683 static struct BroadcastInterface *bi_head;
686 * Broadcast interface tasks. Kept in a DLL.
688 static struct BroadcastInterface *bi_tail;
693 static struct GNUNET_NETWORK_Handle *udp_sock;
696 * #GNUNET_YES if #udp_sock supports IPv6.
698 static int have_v6_socket;
703 static struct GNUNET_PeerIdentity my_identity;
708 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
713 static const struct GNUNET_CONFIGURATION_Handle *cfg;
716 * Our handle to report addresses for validation to TRANSPORT.
718 static struct GNUNET_TRANSPORT_ApplicationHandle *ah;
721 * Network scanner to determine network types.
723 static struct GNUNET_NT_InterfaceScanner *is;
726 * Connection to NAT service.
728 static struct GNUNET_NAT_Handle *nat;
731 * Port number to which we are actually bound.
733 static uint16_t my_port;
737 * An interface went away, stop broadcasting on it.
739 * @param bi entity to close down
742 bi_destroy(struct BroadcastInterface *bi)
744 if (AF_INET6 == bi->sa->sa_family)
746 /* Leave the multicast group */
747 if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt(udp_sock,
753 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "setsockopt");
756 GNUNET_CONTAINER_DLL_remove(bi_head, bi_tail, bi);
757 GNUNET_SCHEDULER_cancel(bi->broadcast_task);
759 GNUNET_free_non_null(bi->ba);
765 * Destroys a receiving state due to timeout or shutdown.
767 * @param receiver entity to close down
770 receiver_destroy(struct ReceiverAddress *receiver)
772 struct GNUNET_MQ_Handle *mq;
774 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
775 "Disconnecting receiver for peer `%s'\n",
776 GNUNET_i2s(&receiver->target));
777 if (NULL != (mq = receiver->mq))
780 GNUNET_MQ_destroy(mq);
782 if (NULL != receiver->qh)
784 GNUNET_TRANSPORT_communicator_mq_del(receiver->qh);
787 GNUNET_assert(GNUNET_YES ==
788 GNUNET_CONTAINER_multipeermap_remove(receivers,
791 GNUNET_assert(receiver == GNUNET_CONTAINER_heap_remove_node(receiver->hn));
792 GNUNET_STATISTICS_set(stats,
793 "# receivers active",
794 GNUNET_CONTAINER_multipeermap_size(receivers),
796 GNUNET_free(receiver->address);
797 GNUNET_free(receiver->foreign_addr);
798 GNUNET_free(receiver);
803 * Free memory used by key cache entry.
805 * @param kce the key cache entry
808 kce_destroy(struct KeyCacheEntry *kce)
810 struct SharedSecret *ss = kce->ss;
812 ss->active_kce_count--;
813 GNUNET_CONTAINER_DLL_remove(ss->kce_head, ss->kce_tail, kce);
814 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multishortmap_remove(key_cache,
824 * @param msec master secret for HMAC calculation
825 * @param serial number for the @a smac calculation
826 * @param kid[out] where to write the key ID
829 get_kid(const struct GNUNET_HashCode *msec,
831 struct GNUNET_ShortHashCode *kid)
833 uint32_t sid = htonl(serial);
835 GNUNET_CRYPTO_hkdf(kid,
851 * Setup key cache entry for sequence number @a seq and shared secret @a ss.
853 * @param ss shared secret
854 * @param seq sequence number for the key cache entry
857 kce_generate(struct SharedSecret *ss, uint32_t seq)
859 struct KeyCacheEntry *kce;
861 GNUNET_assert(0 < seq);
862 kce = GNUNET_new(struct KeyCacheEntry);
864 kce->sequence_number = seq;
865 get_kid(&ss->master, seq, &kce->kid);
866 GNUNET_CONTAINER_DLL_insert(ss->kce_head, ss->kce_tail, kce);
867 ss->active_kce_count++;
868 (void)GNUNET_CONTAINER_multishortmap_put(
872 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
873 GNUNET_STATISTICS_set(stats,
875 GNUNET_CONTAINER_multishortmap_size(key_cache),
881 * Destroy @a ss and associated key cache entries.
883 * @param ss shared secret to destroy
886 secret_destroy(struct SharedSecret *ss)
888 struct SenderAddress *sender;
889 struct ReceiverAddress *receiver;
890 struct KeyCacheEntry *kce;
892 if (NULL != (sender = ss->sender))
894 GNUNET_CONTAINER_DLL_remove(sender->ss_head, sender->ss_tail, ss);
895 sender->num_secrets--;
897 if (NULL != (receiver = ss->receiver))
899 GNUNET_CONTAINER_DLL_remove(receiver->ss_head, receiver->ss_tail, ss);
900 receiver->num_secrets--;
901 receiver->acks_available -= (ss->sequence_allowed - ss->sequence_used);
903 while (NULL != (kce = ss->kce_head))
905 GNUNET_STATISTICS_update(stats, "# Secrets active", -1, GNUNET_NO);
906 GNUNET_STATISTICS_set(stats,
908 GNUNET_CONTAINER_multishortmap_size(key_cache),
915 * Functions with this signature are called whenever we need
916 * to close a sender's state due to timeout.
918 * @param sender entity to close down
921 sender_destroy(struct SenderAddress *sender)
925 GNUNET_CONTAINER_multipeermap_remove(senders, &sender->target, sender));
926 GNUNET_assert(sender == GNUNET_CONTAINER_heap_remove_node(sender->hn));
927 GNUNET_STATISTICS_set(stats,
929 GNUNET_CONTAINER_multipeermap_size(senders),
931 GNUNET_free(sender->address);
937 * Compute @a key and @a iv.
939 * @param msec master secret for calculation
940 * @param serial number for the @a smac calculation
941 * @param key[out] where to write the decrption key
942 * @param iv[out] where to write the IV
945 get_iv_key(const struct GNUNET_HashCode *msec,
947 char key[AES_KEY_SIZE],
948 char iv[AES_IV_SIZE])
950 uint32_t sid = htonl(serial);
951 char res[AES_KEY_SIZE + AES_IV_SIZE];
953 GNUNET_CRYPTO_hkdf(res,
962 strlen("UDP-IV-KEY"),
965 memcpy(key, res, AES_KEY_SIZE);
966 memcpy(iv, &res[AES_KEY_SIZE], AES_IV_SIZE);
971 * Increment sender timeout due to activity.
973 * @param sender address for which the timeout should be rescheduled
976 reschedule_sender_timeout(struct SenderAddress *sender)
979 GNUNET_TIME_relative_to_absolute(GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
980 GNUNET_CONTAINER_heap_update_cost(sender->hn, sender->timeout.abs_value_us);
985 * Increment receiver timeout due to activity.
987 * @param receiver address for which the timeout should be rescheduled
990 reschedule_receiver_timeout(struct ReceiverAddress *receiver)
993 GNUNET_TIME_relative_to_absolute(GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
994 GNUNET_CONTAINER_heap_update_cost(receiver->hn,
995 receiver->timeout.abs_value_us);
1000 * Task run to check #receiver_heap and #sender_heap for timeouts.
1002 * @param cls unused, NULL
1005 check_timeouts(void *cls)
1007 struct GNUNET_TIME_Relative st;
1008 struct GNUNET_TIME_Relative rt;
1009 struct GNUNET_TIME_Relative delay;
1010 struct ReceiverAddress *receiver;
1011 struct SenderAddress *sender;
1014 timeout_task = NULL;
1015 rt = GNUNET_TIME_UNIT_FOREVER_REL;
1016 while (NULL != (receiver = GNUNET_CONTAINER_heap_peek(receivers_heap)))
1018 rt = GNUNET_TIME_absolute_get_remaining(receiver->timeout);
1019 if (0 != rt.rel_value_us)
1021 receiver_destroy(receiver);
1023 st = GNUNET_TIME_UNIT_FOREVER_REL;
1024 while (NULL != (sender = GNUNET_CONTAINER_heap_peek(senders_heap)))
1026 st = GNUNET_TIME_absolute_get_remaining(sender->timeout);
1027 if (0 != st.rel_value_us)
1029 sender_destroy(sender);
1031 delay = GNUNET_TIME_relative_min(rt, st);
1032 if (delay.rel_value_us < GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
1033 timeout_task = GNUNET_SCHEDULER_add_delayed(delay, &check_timeouts, NULL);
1038 * Calcualte cmac from master in @a ss.
1040 * @param ss[in,out] data structure to complete
1043 calculate_cmac(struct SharedSecret *ss)
1045 GNUNET_CRYPTO_hkdf(&ss->cmac,
1061 * We received @a plaintext_len bytes of @a plaintext from a @a sender.
1062 * Pass it on to CORE.
1064 * @param queue the queue that received the plaintext
1065 * @param plaintext the plaintext that was received
1066 * @param plaintext_len number of bytes of plaintext received
1069 pass_plaintext_to_core(struct SenderAddress *sender,
1070 const void *plaintext,
1071 size_t plaintext_len)
1073 const struct GNUNET_MessageHeader *hdr = plaintext;
1075 while (ntohs(hdr->size) < plaintext_len)
1077 GNUNET_STATISTICS_update(stats,
1078 "# bytes given to core",
1082 GNUNET_TRANSPORT_communicator_receive(ch,
1085 ADDRESS_VALIDITY_PERIOD,
1086 NULL /* no flow control possible */
1089 /* move on to next message, if any */
1090 plaintext_len -= ntohs(hdr->size);
1091 if (plaintext_len < sizeof(*hdr))
1093 hdr = plaintext + ntohs(hdr->size);
1095 GNUNET_STATISTICS_update(stats,
1096 "# bytes padding discarded",
1103 * Setup @a cipher based on shared secret @a msec and
1104 * serial number @a serial.
1106 * @param msec master shared secret
1107 * @param serial serial number of cipher to set up
1108 * @param cipher[out] cipher to initialize
1111 setup_cipher(const struct GNUNET_HashCode *msec,
1113 gcry_cipher_hd_t *cipher)
1115 char key[AES_KEY_SIZE];
1116 char iv[AES_IV_SIZE];
1118 gcry_cipher_open(cipher,
1119 GCRY_CIPHER_AES256 /* low level: go for speed */,
1120 GCRY_CIPHER_MODE_GCM,
1122 get_iv_key(msec, serial, key, iv);
1123 gcry_cipher_setkey(*cipher, key, sizeof(key));
1124 gcry_cipher_setiv(*cipher, iv, sizeof(iv));
1129 * Try to decrypt @a buf using shared secret @a ss and key/iv
1130 * derived using @a serial.
1132 * @param ss shared secret
1133 * @param tag GCM authentication tag
1134 * @param serial serial number to use
1135 * @param in_buf input buffer to decrypt
1136 * @param in_buf_size number of bytes in @a in_buf and available in @a out_buf
1137 * @param out_buf where to write the result
1138 * @return #GNUNET_OK on success
1141 try_decrypt(const struct SharedSecret *ss,
1142 const char tag[GCM_TAG_SIZE],
1148 gcry_cipher_hd_t cipher;
1150 setup_cipher(&ss->master, serial, &cipher);
1153 gcry_cipher_decrypt(cipher, out_buf, in_buf_size, in_buf, in_buf_size));
1154 if (0 != gcry_cipher_checktag(cipher, tag, GCM_TAG_SIZE))
1156 gcry_cipher_close(cipher);
1157 GNUNET_STATISTICS_update(stats,
1158 "# AEAD authentication failures",
1161 return GNUNET_SYSERR;
1163 gcry_cipher_close(cipher);
1169 * Setup shared secret for decryption.
1171 * @param ephemeral ephemeral key we received from the other peer
1172 * @return new shared secret
1174 static struct SharedSecret *
1175 setup_shared_secret_dec(const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1177 struct SharedSecret *ss;
1179 ss = GNUNET_new(struct SharedSecret);
1180 GNUNET_CRYPTO_eddsa_ecdh(my_private_key, ephemeral, &ss->master);
1186 * Setup shared secret for encryption.
1188 * @param ephemeral ephemeral key we are sending to the other peer
1189 * @param receiver[in,out] queue to initialize encryption key for
1190 * @return new shared secret
1192 static struct SharedSecret *
1193 setup_shared_secret_enc(const struct GNUNET_CRYPTO_EcdhePrivateKey *ephemeral,
1194 struct ReceiverAddress *receiver)
1196 struct SharedSecret *ss;
1198 ss = GNUNET_new(struct SharedSecret);
1199 GNUNET_CRYPTO_ecdh_eddsa(ephemeral,
1200 &receiver->target.public_key,
1203 ss->receiver = receiver;
1204 GNUNET_CONTAINER_DLL_insert(receiver->ss_head, receiver->ss_tail, ss);
1205 receiver->num_secrets++;
1206 GNUNET_STATISTICS_update(stats, "# Secrets active", 1, GNUNET_NO);
1212 * Setup the MQ for the @a receiver. If a queue exists,
1213 * the existing one is destroyed. Then the MTU is
1214 * recalculated and a fresh queue is initialized.
1216 * @param receiver receiver to setup MQ for
1219 setup_receiver_mq(struct ReceiverAddress *receiver);
1223 * We received an ACK for @a pid. Check if it is for
1224 * the receiver in @a value and if so, handle it and
1225 * return #GNUNET_NO. Otherwise, return #GNUNET_YES.
1227 * @param cls a `const struct UDPAck`
1228 * @param pid peer the ACK is from
1229 * @param value a `struct ReceiverAddress`
1230 * @return #GNUNET_YES to continue to iterate
1233 handle_ack(void *cls, const struct GNUNET_PeerIdentity *pid, void *value)
1235 const struct UDPAck *ack = cls;
1236 struct ReceiverAddress *receiver = value;
1239 for (struct SharedSecret *ss = receiver->ss_head; NULL != ss; ss = ss->next)
1241 if (0 == memcmp(&ack->cmac, &ss->cmac, sizeof(struct GNUNET_HashCode)))
1245 allowed = ntohl(ack->sequence_max);
1247 if (allowed > ss->sequence_allowed)
1249 receiver->acks_available += (allowed - ss->sequence_allowed);
1250 if ((allowed - ss->sequence_allowed) == receiver->acks_available)
1252 /* we just incremented from zero => MTU change! */
1253 setup_receiver_mq(receiver);
1255 ss->sequence_allowed = allowed;
1256 /* move ss to head to avoid discarding it anytime soon! */
1257 GNUNET_CONTAINER_DLL_remove(receiver->ss_head, receiver->ss_tail, ss);
1258 GNUNET_CONTAINER_DLL_insert(receiver->ss_head, receiver->ss_tail, ss);
1268 * Test if we have received a valid message in plaintext.
1271 * @param sender peer to process inbound plaintext for
1272 * @param buf buffer we received
1273 * @param buf_size number of bytes in @a buf
1276 try_handle_plaintext(struct SenderAddress *sender,
1280 const struct GNUNET_MessageHeader *hdr =
1281 (const struct GNUNET_MessageHeader *)buf;
1282 const struct UDPAck *ack = (const struct UDPAck *)buf;
1285 if (sizeof(*hdr) > buf_size)
1286 return; /* not even a header */
1287 if (ntohs(hdr->size) > buf_size)
1288 return; /* not even a header */
1289 type = ntohs(hdr->type);
1292 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK:
1293 /* lookup master secret by 'cmac', then update sequence_max */
1294 GNUNET_CONTAINER_multipeermap_get_multiple(receivers,
1298 /* There could be more messages after the ACK, handle those as well */
1299 buf += ntohs(hdr->size);
1300 buf_size -= ntohs(hdr->size);
1301 pass_plaintext_to_core(sender, buf, buf_size);
1304 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD:
1309 pass_plaintext_to_core(sender, buf, buf_size);
1315 * We established a shared secret with a sender. We should try to send
1316 * the sender an `struct UDPAck` at the next opportunity to allow the
1317 * sender to use @a ss longer (assuming we did not yet already
1320 * @param ss shared secret to generate ACKs for
1323 consider_ss_ack(struct SharedSecret *ss)
1325 GNUNET_assert(NULL != ss->sender);
1326 /* drop ancient KeyCacheEntries */
1327 while ((NULL != ss->kce_head) &&
1329 ss->kce_head->sequence_number - ss->kce_tail->sequence_number))
1330 kce_destroy(ss->kce_tail);
1331 if (ss->active_kce_count < KCN_THRESHOLD)
1335 while (ss->active_kce_count < KCN_TARGET)
1336 kce_generate(ss, ++ss->sequence_allowed);
1337 ack.header.type = htons(GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK);
1338 ack.header.size = htons(sizeof(ack));
1339 ack.sequence_max = htonl(ss->sequence_allowed);
1340 ack.cmac = ss->cmac;
1341 GNUNET_TRANSPORT_communicator_notify(ch,
1342 &ss->sender->target,
1343 COMMUNICATOR_ADDRESS_PREFIX,
1350 * We received a @a box with matching @a kce. Decrypt and process it.
1352 * @param box the data we received
1353 * @param box_len number of bytes in @a box
1354 * @param kce key index to decrypt @a box
1357 decrypt_box(const struct UDPBox *box,
1359 struct KeyCacheEntry *kce)
1361 struct SharedSecret *ss = kce->ss;
1362 char out_buf[box_len - sizeof(*box)];
1364 GNUNET_assert(NULL != ss->sender);
1365 if (GNUNET_OK != try_decrypt(ss,
1367 kce->sequence_number,
1368 (const char *)&box[1],
1372 GNUNET_STATISTICS_update(stats,
1373 "# Decryption failures with valid KCE",
1380 GNUNET_STATISTICS_update(stats,
1381 "# bytes decrypted with BOX",
1384 try_handle_plaintext(ss->sender, out_buf, sizeof(out_buf));
1385 consider_ss_ack(ss);
1390 * Closure for #find_sender_by_address()
1392 struct SearchContext {
1394 * Address we are looking for.
1396 const struct sockaddr *address;
1399 * Number of bytes in @e address.
1401 socklen_t address_len;
1404 * Return value to set if we found a match.
1406 struct SenderAddress *sender;
1411 * Find existing `struct SenderAddress` by matching addresses.
1413 * @param cls a `struct SearchContext`
1414 * @param key ignored, must match already
1415 * @param value a `struct SenderAddress`
1416 * @return #GNUNET_YES if not found (continue to search), #GNUNET_NO if found
1419 find_sender_by_address(void *cls,
1420 const struct GNUNET_PeerIdentity *key,
1423 struct SearchContext *sc = cls;
1424 struct SenderAddress *sender = value;
1426 if ((sender->address_len == sc->address_len) &&
1427 (0 == memcmp(sender->address, sc->address, sender->address_len)))
1429 sc->sender = sender;
1430 return GNUNET_NO; /* stop iterating! */
1437 * Create sender address for @a target. Note that we
1438 * might already have one, so a fresh one is only allocated
1439 * if one does not yet exist for @a address.
1441 * @param target peer to generate address for
1442 * @param address target address
1443 * @param address_len number of bytes in @a address
1444 * @return data structure to keep track of key material for
1445 * decrypting data from @a target
1447 static struct SenderAddress *
1448 setup_sender(const struct GNUNET_PeerIdentity *target,
1449 const struct sockaddr *address,
1450 socklen_t address_len)
1452 struct SenderAddress *sender;
1453 struct SearchContext sc = { .address = address,
1454 .address_len = address_len,
1457 GNUNET_CONTAINER_multipeermap_get_multiple(senders,
1459 &find_sender_by_address,
1461 if (NULL != sc.sender)
1463 reschedule_sender_timeout(sc.sender);
1466 sender = GNUNET_new(struct SenderAddress);
1467 sender->target = *target;
1468 sender->address = GNUNET_memdup(address, address_len);
1469 sender->address_len = address_len;
1470 (void)GNUNET_CONTAINER_multipeermap_put(
1474 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1475 GNUNET_STATISTICS_set(stats,
1477 GNUNET_CONTAINER_multipeermap_size(receivers),
1480 GNUNET_TIME_relative_to_absolute(GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1481 sender->hn = GNUNET_CONTAINER_heap_insert(senders_heap,
1483 sender->timeout.abs_value_us);
1484 sender->nt = GNUNET_NT_scanner_get_type(is, address, address_len);
1485 if (NULL == timeout_task)
1486 timeout_task = GNUNET_SCHEDULER_add_now(&check_timeouts, NULL);
1492 * Check signature from @a uc against @a ephemeral.
1494 * @param ephermal key that is signed
1495 * @param uc signature of claimant
1496 * @return #GNUNET_OK if signature is valid
1499 verify_confirmation(const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
1500 const struct UDPConfirmation *uc)
1502 struct UdpHandshakeSignature uhs;
1504 uhs.purpose.purpose = htonl(GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1505 uhs.purpose.size = htonl(sizeof(uhs));
1506 uhs.sender = uc->sender;
1507 uhs.receiver = my_identity;
1508 uhs.ephemeral = *ephemeral;
1509 uhs.monotonic_time = uc->monotonic_time;
1510 return GNUNET_CRYPTO_eddsa_verify(GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE,
1513 &uc->sender.public_key);
1518 * Converts @a address to the address string format used by this
1519 * communicator in HELLOs.
1521 * @param address the address to convert, must be AF_INET or AF_INET6.
1522 * @param address_len number of bytes in @a address
1523 * @return string representation of @a address
1526 sockaddr_to_udpaddr_string(const struct sockaddr *address,
1527 socklen_t address_len)
1531 switch (address->sa_family)
1534 GNUNET_asprintf(&ret,
1536 COMMUNICATOR_ADDRESS_PREFIX,
1537 GNUNET_a2s(address, address_len));
1541 GNUNET_asprintf(&ret,
1543 COMMUNICATOR_ADDRESS_PREFIX,
1544 GNUNET_a2s(address, address_len));
1560 sock_read(void *cls)
1562 struct sockaddr_storage sa;
1563 socklen_t salen = sizeof(sa);
1564 char buf[UINT16_MAX];
1568 read_task = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
1572 rcvd = GNUNET_NETWORK_socket_recvfrom(udp_sock,
1575 (struct sockaddr *)&sa,
1579 GNUNET_log_strerror(GNUNET_ERROR_TYPE_DEBUG, "recv");
1583 /* first, see if it is a UDPBox */
1584 if (rcvd > sizeof(struct UDPBox))
1586 const struct UDPBox *box;
1587 struct KeyCacheEntry *kce;
1589 box = (const struct UDPBox *)buf;
1590 kce = GNUNET_CONTAINER_multishortmap_get(key_cache, &box->kid);
1593 decrypt_box(box, (size_t)rcvd, kce);
1598 /* next, check if it is a broadcast */
1599 if (sizeof(struct UDPBroadcast) == rcvd)
1601 const struct UDPBroadcast *ub;
1602 struct UdpBroadcastSignature uhs;
1604 ub = (const struct UDPBroadcast *)buf;
1605 uhs.purpose.purpose = htonl(GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
1606 uhs.purpose.size = htonl(sizeof(uhs));
1607 uhs.sender = ub->sender;
1608 GNUNET_CRYPTO_hash(&sa, salen, &uhs.h_address);
1610 GNUNET_CRYPTO_eddsa_verify(GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST,
1613 &ub->sender.public_key))
1616 enum GNUNET_NetworkType nt;
1619 sockaddr_to_udpaddr_string((const struct sockaddr *)&sa, salen);
1620 GNUNET_STATISTICS_update(stats, "# broadcasts received", 1, GNUNET_NO);
1621 /* use our own mechanism to determine network type */
1623 GNUNET_NT_scanner_get_type(is, (const struct sockaddr *)&sa, salen);
1624 GNUNET_TRANSPORT_application_validate(ah, &ub->sender, nt, addr_s);
1625 GNUNET_free(addr_s);
1628 /* continue with KX, mostly for statistics... */
1632 /* finally, test if it is a KX */
1633 if (rcvd < sizeof(struct UDPConfirmation) + sizeof(struct InitialKX))
1635 GNUNET_STATISTICS_update(stats,
1636 "# messages dropped (no kid, too small for KX)",
1643 const struct InitialKX *kx;
1644 struct SharedSecret *ss;
1645 char pbuf[rcvd - sizeof(struct InitialKX)];
1646 const struct UDPConfirmation *uc;
1647 struct SenderAddress *sender;
1649 kx = (const struct InitialKX *)buf;
1650 ss = setup_shared_secret_dec(&kx->ephemeral);
1651 if (GNUNET_OK != try_decrypt(ss,
1659 GNUNET_STATISTICS_update(
1661 "# messages dropped (no kid, AEAD decryption failed)",
1666 uc = (const struct UDPConfirmation *)pbuf;
1667 if (GNUNET_OK != verify_confirmation(&kx->ephemeral, uc))
1671 GNUNET_STATISTICS_update(stats,
1672 "# messages dropped (sender signature invalid)",
1678 sender = setup_sender(&uc->sender, (const struct sockaddr *)&sa, salen);
1679 ss->sender = sender;
1680 GNUNET_CONTAINER_DLL_insert(sender->ss_head, sender->ss_tail, ss);
1681 sender->num_secrets++;
1682 GNUNET_STATISTICS_update(stats, "# Secrets active", 1, GNUNET_NO);
1683 GNUNET_STATISTICS_update(stats,
1684 "# messages decrypted without BOX",
1687 try_handle_plaintext(sender, &uc[1], sizeof(pbuf) - sizeof(*uc));
1688 consider_ss_ack(ss);
1689 if (sender->num_secrets > MAX_SECRETS)
1690 secret_destroy(sender->ss_tail);
1696 * Convert UDP bind specification to a `struct sockaddr *`
1698 * @param bindto bind specification to convert
1699 * @param[out] sock_len set to the length of the address
1700 * @return converted bindto specification
1702 static struct sockaddr *
1703 udp_address_to_sockaddr(const char *bindto, socklen_t *sock_len)
1705 struct sockaddr *in;
1711 if (1 == sscanf(bindto, "%u%1s", &port, dummy))
1713 /* interpreting value as just a PORT number */
1714 if (port > UINT16_MAX)
1716 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1717 "BINDTO specification `%s' invalid: value too large for port\n",
1721 if ((GNUNET_NO == GNUNET_NETWORK_test_pf(PF_INET6)) ||
1723 GNUNET_CONFIGURATION_get_value_yesno(cfg,
1724 COMMUNICATOR_CONFIG_SECTION,
1727 struct sockaddr_in *i4;
1729 i4 = GNUNET_malloc(sizeof(struct sockaddr_in));
1730 i4->sin_family = AF_INET;
1731 i4->sin_port = htons((uint16_t)port);
1732 *sock_len = sizeof(struct sockaddr_in);
1733 in = (struct sockaddr *)i4;
1737 struct sockaddr_in6 *i6;
1739 i6 = GNUNET_malloc(sizeof(struct sockaddr_in6));
1740 i6->sin6_family = AF_INET6;
1741 i6->sin6_port = htons((uint16_t)port);
1742 *sock_len = sizeof(struct sockaddr_in6);
1743 in = (struct sockaddr *)i6;
1747 cp = GNUNET_strdup(bindto);
1748 colon = strrchr(cp, ':');
1751 /* interpet value after colon as port */
1754 if (1 == sscanf(colon, "%u%1s", &port, dummy))
1756 /* interpreting value as just a PORT number */
1757 if (port > UINT16_MAX)
1759 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1760 "BINDTO specification `%s' invalid: value too large for port\n",
1769 GNUNET_ERROR_TYPE_ERROR,
1770 "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1778 /* interpret missing port as 0, aka pick any free one */
1783 struct sockaddr_in v4;
1785 if (1 == inet_pton(AF_INET, cp, &v4))
1787 v4.sin_port = htons((uint16_t)port);
1788 in = GNUNET_memdup(&v4, sizeof(v4));
1789 *sock_len = sizeof(v4);
1796 struct sockaddr_in6 v6;
1800 if (('[' == *cp) && (']' == cp[strlen(cp) - 1]))
1802 start++; /* skip over '[' */
1803 cp[strlen(cp) - 1] = '\0'; /* eat ']' */
1805 if (1 == inet_pton(AF_INET6, start, &v6))
1807 v6.sin6_port = htons((uint16_t)port);
1808 in = GNUNET_memdup(&v6, sizeof(v6));
1809 *sock_len = sizeof(v6);
1814 /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1821 * Pad @a dgram by @a pad_size using @a out_cipher.
1823 * @param out_cipher cipher to use
1824 * @param dgram datagram to pad
1825 * @param pad_size number of bytes of padding to append
1828 do_pad(gcry_cipher_hd_t out_cipher, char *dgram, size_t pad_size)
1832 GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_WEAK, pad, sizeof(pad));
1833 if (sizeof(pad) > sizeof(struct GNUNET_MessageHeader))
1835 struct GNUNET_MessageHeader hdr =
1836 { .size = htons(sizeof(pad)),
1837 .type = htons(GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD) };
1839 memcpy(pad, &hdr, sizeof(hdr));
1843 gcry_cipher_encrypt(out_cipher, dgram, sizeof(pad), pad, sizeof(pad)));
1848 * Signature of functions implementing the sending functionality of a
1851 * @param mq the message queue
1852 * @param msg the message to send
1853 * @param impl_state our `struct ReceiverAddress`
1856 mq_send(struct GNUNET_MQ_Handle *mq,
1857 const struct GNUNET_MessageHeader *msg,
1860 struct ReceiverAddress *receiver = impl_state;
1861 uint16_t msize = ntohs(msg->size);
1863 GNUNET_assert(mq == receiver->mq);
1864 if (msize > receiver->mtu)
1867 receiver_destroy(receiver);
1870 reschedule_receiver_timeout(receiver);
1872 if (0 == receiver->acks_available)
1874 /* use KX encryption method */
1875 struct UdpHandshakeSignature uhs;
1876 struct UDPConfirmation uc;
1877 struct InitialKX kx;
1878 struct GNUNET_CRYPTO_EcdhePrivateKey epriv;
1879 char dgram[receiver->mtu + sizeof(uc) + sizeof(kx)];
1881 gcry_cipher_hd_t out_cipher;
1882 struct SharedSecret *ss;
1884 /* setup key material */
1885 GNUNET_assert(GNUNET_OK == GNUNET_CRYPTO_ecdhe_key_create2(&epriv));
1887 ss = setup_shared_secret_enc(&epriv, receiver);
1888 setup_cipher(&ss->master, 0, &out_cipher);
1890 uc.sender = my_identity;
1892 GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_monotonic(cfg));
1893 uhs.purpose.purpose = htonl(GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1894 uhs.purpose.size = htonl(sizeof(uhs));
1895 uhs.sender = my_identity;
1896 uhs.receiver = receiver->target;
1897 GNUNET_CRYPTO_ecdhe_key_get_public(&epriv, &uhs.ephemeral);
1898 uhs.monotonic_time = uc.monotonic_time;
1899 GNUNET_assert(GNUNET_OK == GNUNET_CRYPTO_eddsa_sign(my_private_key,
1902 /* Leave space for kx */
1903 dpos = sizeof(struct GNUNET_CRYPTO_EcdhePublicKey);
1904 /* Append encrypted uc to dgram */
1905 GNUNET_assert(0 == gcry_cipher_encrypt(out_cipher,
1911 /* Append encrypted payload to dgram */
1913 0 == gcry_cipher_encrypt(out_cipher, &dgram[dpos], msize, msg, msize));
1915 do_pad(out_cipher, &dgram[dpos], sizeof(dgram) - dpos);
1916 /* Datagram starts with kx */
1917 kx.ephemeral = uhs.ephemeral;
1919 0 == gcry_cipher_gettag(out_cipher, kx.gcm_tag, sizeof(kx.gcm_tag)));
1920 gcry_cipher_close(out_cipher);
1921 memcpy(dgram, &kx, sizeof(kx));
1922 if (-1 == GNUNET_NETWORK_socket_sendto(udp_sock,
1926 receiver->address_len))
1927 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "send");
1928 GNUNET_MQ_impl_send_continue(mq);
1930 } /* End of KX encryption method */
1932 /* begin "BOX" encryption method, scan for ACKs from tail! */
1933 for (struct SharedSecret *ss = receiver->ss_tail; NULL != ss; ss = ss->prev)
1935 if (ss->sequence_used < ss->sequence_allowed)
1937 char dgram[sizeof(struct UDPBox) + receiver->mtu];
1939 gcry_cipher_hd_t out_cipher;
1942 box = (struct UDPBox *)dgram;
1943 ss->sequence_used++;
1944 get_kid(&ss->master, ss->sequence_used, &box->kid);
1945 setup_cipher(&ss->master, ss->sequence_used, &out_cipher);
1946 /* Append encrypted payload to dgram */
1947 dpos = sizeof(struct UDPBox);
1949 0 == gcry_cipher_encrypt(out_cipher, &dgram[dpos], msize, msg, msize));
1951 do_pad(out_cipher, &dgram[dpos], sizeof(dgram) - dpos);
1952 GNUNET_assert(0 == gcry_cipher_gettag(out_cipher,
1954 sizeof(box->gcm_tag)));
1955 gcry_cipher_close(out_cipher);
1956 if (-1 == GNUNET_NETWORK_socket_sendto(udp_sock,
1960 receiver->address_len))
1961 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "send");
1962 GNUNET_MQ_impl_send_continue(mq);
1963 receiver->acks_available--;
1964 if (0 == receiver->acks_available)
1966 /* We have no more ACKs => MTU change! */
1967 setup_receiver_mq(receiver);
1977 * Signature of functions implementing the destruction of a message
1978 * queue. Implementations must not free @a mq, but should take care
1981 * @param mq the message queue to destroy
1982 * @param impl_state our `struct ReceiverAddress`
1985 mq_destroy(struct GNUNET_MQ_Handle *mq, void *impl_state)
1987 struct ReceiverAddress *receiver = impl_state;
1989 if (mq == receiver->mq)
1991 receiver->mq = NULL;
1992 receiver_destroy(receiver);
1998 * Implementation function that cancels the currently sent message.
2000 * @param mq message queue
2001 * @param impl_state our `struct RecvierAddress`
2004 mq_cancel(struct GNUNET_MQ_Handle *mq, void *impl_state)
2006 /* Cancellation is impossible with UDP; bail */
2012 * Generic error handler, called with the appropriate
2013 * error code and the same closure specified at the creation of
2014 * the message queue.
2015 * Not every message queue implementation supports an error handler.
2017 * @param cls our `struct ReceiverAddress`
2018 * @param error error code
2021 mq_error(void *cls, enum GNUNET_MQ_Error error)
2023 struct ReceiverAddress *receiver = cls;
2025 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2026 "MQ error in queue to %s: %d\n",
2027 GNUNET_i2s(&receiver->target),
2029 receiver_destroy(receiver);
2034 * Setup the MQ for the @a receiver. If a queue exists,
2035 * the existing one is destroyed. Then the MTU is
2036 * recalculated and a fresh queue is initialized.
2038 * @param receiver receiver to setup MQ for
2041 setup_receiver_mq(struct ReceiverAddress *receiver)
2045 if (NULL != receiver->qh)
2047 GNUNET_TRANSPORT_communicator_mq_del(receiver->qh);
2048 receiver->qh = NULL;
2050 GNUNET_assert(NULL == receiver->mq);
2051 switch (receiver->address->sa_family)
2054 base_mtu = 1480 /* Ethernet MTU, 1500 - Ethernet header - VLAN tag */
2055 - sizeof(struct GNUNET_TUN_IPv4Header) /* 20 */
2056 - sizeof(struct GNUNET_TUN_UdpHeader) /* 8 */;
2060 base_mtu = 1280 /* Minimum MTU required by IPv6 */
2061 - sizeof(struct GNUNET_TUN_IPv6Header) /* 40 */
2062 - sizeof(struct GNUNET_TUN_UdpHeader) /* 8 */;
2069 if (0 == receiver->acks_available)
2071 /* MTU based on full KX messages */
2072 receiver->mtu = base_mtu - sizeof(struct InitialKX) /* 48 */
2073 - sizeof(struct UDPConfirmation); /* 104 */
2077 /* MTU based on BOXed messages */
2078 receiver->mtu = base_mtu - sizeof(struct UDPBox);
2080 /* => Effective MTU for CORE will range from 1080 (IPv6 + KX) to
2081 1404 (IPv4 + Box) bytes, depending on circumstances... */
2082 if (NULL == receiver->mq)
2083 receiver->mq = GNUNET_MQ_queue_for_callbacks(&mq_send,
2091 GNUNET_TRANSPORT_communicator_mq_add(ch,
2093 receiver->foreign_addr,
2096 GNUNET_TRANSPORT_CS_OUTBOUND,
2102 * Function called by the transport service to initialize a
2103 * message queue given address information about another peer.
2104 * If and when the communication channel is established, the
2105 * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
2106 * to notify the service that the channel is now up. It is
2107 * the responsibility of the communicator to manage sane
2108 * retries and timeouts for any @a peer/@a address combination
2109 * provided by the transport service. Timeouts and retries
2110 * do not need to be signalled to the transport service.
2112 * @param cls closure
2113 * @param peer identity of the other peer
2114 * @param address where to send the message, human-readable
2115 * communicator-specific format, 0-terminated, UTF-8
2116 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is
2120 mq_init(void *cls, const struct GNUNET_PeerIdentity *peer, const char *address)
2122 struct ReceiverAddress *receiver;
2124 struct sockaddr *in;
2127 if (0 != strncmp(address,
2128 COMMUNICATOR_ADDRESS_PREFIX "-",
2129 strlen(COMMUNICATOR_ADDRESS_PREFIX "-")))
2132 return GNUNET_SYSERR;
2134 path = &address[strlen(COMMUNICATOR_ADDRESS_PREFIX "-")];
2135 in = udp_address_to_sockaddr(path, &in_len);
2137 receiver = GNUNET_new(struct ReceiverAddress);
2138 receiver->address = in;
2139 receiver->address_len = in_len;
2140 receiver->target = *peer;
2141 receiver->nt = GNUNET_NT_scanner_get_type(is, in, in_len);
2142 (void)GNUNET_CONTAINER_multipeermap_put(
2146 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2148 GNUNET_TIME_relative_to_absolute(GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2149 receiver->hn = GNUNET_CONTAINER_heap_insert(receivers_heap,
2151 receiver->timeout.abs_value_us);
2152 GNUNET_STATISTICS_set(stats,
2153 "# receivers active",
2154 GNUNET_CONTAINER_multipeermap_size(receivers),
2156 receiver->foreign_addr =
2157 sockaddr_to_udpaddr_string(receiver->address, receiver->address_len);
2158 setup_receiver_mq(receiver);
2159 if (NULL == timeout_task)
2160 timeout_task = GNUNET_SCHEDULER_add_now(&check_timeouts, NULL);
2166 * Iterator over all receivers to clean up.
2169 * @param target unused
2170 * @param value the queue to destroy
2171 * @return #GNUNET_OK to continue to iterate
2174 get_receiver_delete_it(void *cls,
2175 const struct GNUNET_PeerIdentity *target,
2178 struct ReceiverAddress *receiver = value;
2182 receiver_destroy(receiver);
2188 * Iterator over all senders to clean up.
2191 * @param target unused
2192 * @param value the queue to destroy
2193 * @return #GNUNET_OK to continue to iterate
2196 get_sender_delete_it(void *cls,
2197 const struct GNUNET_PeerIdentity *target,
2200 struct SenderAddress *sender = value;
2204 sender_destroy(sender);
2210 * Shutdown the UNIX communicator.
2212 * @param cls NULL (always)
2215 do_shutdown(void *cls)
2219 GNUNET_NAT_unregister(nat);
2222 while (NULL != bi_head)
2223 bi_destroy(bi_head);
2224 if (NULL != broadcast_task)
2226 GNUNET_SCHEDULER_cancel(broadcast_task);
2227 broadcast_task = NULL;
2229 if (NULL != read_task)
2231 GNUNET_SCHEDULER_cancel(read_task);
2234 if (NULL != udp_sock)
2236 GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close(udp_sock));
2239 GNUNET_CONTAINER_multipeermap_iterate(receivers,
2240 &get_receiver_delete_it,
2242 GNUNET_CONTAINER_multipeermap_destroy(receivers);
2243 GNUNET_CONTAINER_multipeermap_iterate(senders, &get_sender_delete_it, NULL);
2244 GNUNET_CONTAINER_multipeermap_destroy(senders);
2245 GNUNET_CONTAINER_multishortmap_destroy(key_cache);
2246 GNUNET_CONTAINER_heap_destroy(senders_heap);
2247 GNUNET_CONTAINER_heap_destroy(receivers_heap);
2250 GNUNET_TRANSPORT_communicator_disconnect(ch);
2255 GNUNET_TRANSPORT_application_done(ah);
2260 GNUNET_STATISTICS_destroy(stats, GNUNET_NO);
2263 if (NULL != my_private_key)
2265 GNUNET_free(my_private_key);
2266 my_private_key = NULL;
2270 GNUNET_NT_scanner_done(is);
2277 * Function called when the transport service has received a
2278 * backchannel message for this communicator (!) via a different return
2279 * path. Should be an acknowledgement.
2281 * @param cls closure, NULL
2282 * @param sender which peer sent the notification
2283 * @param msg payload
2286 enc_notify_cb(void *cls,
2287 const struct GNUNET_PeerIdentity *sender,
2288 const struct GNUNET_MessageHeader *msg)
2290 const struct UDPAck *ack;
2293 if ((ntohs(msg->type) != GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK) ||
2294 (ntohs(msg->size) != sizeof(struct UDPAck)))
2299 ack = (const struct UDPAck *)msg;
2300 GNUNET_CONTAINER_multipeermap_get_multiple(receivers,
2308 * Signature of the callback passed to #GNUNET_NAT_register() for
2309 * a function to call whenever our set of 'valid' addresses changes.
2311 * @param cls closure
2312 * @param app_ctx[in,out] location where the app can store stuff
2313 * on add and retrieve it on remove
2314 * @param add_remove #GNUNET_YES to add a new public IP address,
2315 * #GNUNET_NO to remove a previous (now invalid) one
2316 * @param ac address class the address belongs to
2317 * @param addr either the previous or the new public IP address
2318 * @param addrlen actual length of the @a addr
2321 nat_address_cb(void *cls,
2324 enum GNUNET_NAT_AddressClass ac,
2325 const struct sockaddr *addr,
2329 struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2331 if (GNUNET_YES == add_remove)
2333 enum GNUNET_NetworkType nt;
2335 GNUNET_asprintf(&my_addr,
2337 COMMUNICATOR_ADDRESS_PREFIX,
2338 GNUNET_a2s(addr, addrlen));
2339 nt = GNUNET_NT_scanner_get_type(is, addr, addrlen);
2341 GNUNET_TRANSPORT_communicator_address_add(ch,
2344 GNUNET_TIME_UNIT_FOREVER_REL);
2345 GNUNET_free(my_addr);
2351 GNUNET_TRANSPORT_communicator_address_remove(ai);
2358 * Broadcast our presence on one of our interfaces.
2360 * @param cls a `struct BroadcastInterface`
2363 ifc_broadcast(void *cls)
2365 struct BroadcastInterface *bi = cls;
2366 struct GNUNET_TIME_Relative delay;
2368 delay = BROADCAST_FREQUENCY;
2369 delay.rel_value_us =
2370 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, delay.rel_value_us);
2371 bi->broadcast_task =
2372 GNUNET_SCHEDULER_add_delayed(INTERFACE_SCAN_FREQUENCY, &ifc_broadcast, bi);
2374 switch (bi->sa->sa_family)
2381 if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt(udp_sock,
2386 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "setsockopt");
2387 sent = GNUNET_NETWORK_socket_sendto(udp_sock,
2393 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "sendto");
2394 if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt(udp_sock,
2399 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "setsockopt");
2405 struct sockaddr_in6 dst;
2407 dst.sin6_family = AF_INET6;
2408 dst.sin6_port = htons(my_port);
2409 dst.sin6_addr = bi->mcreq.ipv6mr_multiaddr;
2410 dst.sin6_scope_id = ((struct sockaddr_in6 *)bi->ba)->sin6_scope_id;
2412 sent = GNUNET_NETWORK_socket_sendto(udp_sock,
2415 (const struct sockaddr *)&dst,
2418 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "sendto");
2430 * Callback function invoked for each interface found.
2431 * Activates/deactivates broadcast interfaces.
2434 * @param name name of the interface (can be NULL for unknown)
2435 * @param isDefault is this presumably the default interface
2436 * @param addr address of this interface (can be NULL for unknown or unassigned)
2437 * @param broadcast_addr the broadcast address (can be NULL for unknown or
2439 * @param netmask the network mask (can be NULL for unknown or unassigned)
2440 * @param addrlen length of the address
2441 * @return #GNUNET_OK to continue iteration, #GNUNET_SYSERR to abort
2444 iface_proc(void *cls,
2447 const struct sockaddr *addr,
2448 const struct sockaddr *broadcast_addr,
2449 const struct sockaddr *netmask,
2452 struct BroadcastInterface *bi;
2453 enum GNUNET_NetworkType network;
2454 struct UdpBroadcastSignature ubs;
2459 return GNUNET_YES; /* need to know our address! */
2460 network = GNUNET_NT_scanner_get_type(is, addr, addrlen);
2461 if (GNUNET_NT_LOOPBACK == network)
2463 /* Broadcasting on loopback does not make sense */
2466 for (bi = bi_head; NULL != bi; bi = bi->next)
2468 if ((bi->salen == addrlen) && (0 == memcmp(addr, bi->sa, addrlen)))
2470 bi->found = GNUNET_YES;
2475 if ((AF_INET6 == addr->sa_family) && (NULL == broadcast_addr))
2476 return GNUNET_OK; /* broadcast_addr is required for IPv6! */
2477 if ((AF_INET6 == addr->sa_family) && (GNUNET_YES != have_v6_socket))
2478 return GNUNET_OK; /* not using IPv6 */
2480 bi = GNUNET_new(struct BroadcastInterface);
2481 bi->sa = GNUNET_memdup(addr, addrlen);
2482 if (NULL != broadcast_addr)
2483 bi->ba = GNUNET_memdup(broadcast_addr, addrlen);
2484 bi->salen = addrlen;
2485 bi->found = GNUNET_YES;
2486 bi->bcm.sender = my_identity;
2487 ubs.purpose.purpose = htonl(GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
2488 ubs.purpose.size = htonl(sizeof(ubs));
2489 ubs.sender = my_identity;
2490 GNUNET_CRYPTO_hash(addr, addrlen, &ubs.h_address);
2491 GNUNET_assert(GNUNET_OK == GNUNET_CRYPTO_eddsa_sign(my_private_key,
2493 &bi->bcm.sender_sig));
2494 bi->broadcast_task = GNUNET_SCHEDULER_add_now(&ifc_broadcast, bi);
2495 GNUNET_CONTAINER_DLL_insert(bi_head, bi_tail, bi);
2496 if ((AF_INET6 == addr->sa_family) && (NULL != broadcast_addr))
2498 /* Create IPv6 multicast request */
2499 const struct sockaddr_in6 *s6 =
2500 (const struct sockaddr_in6 *)broadcast_addr;
2503 1 == inet_pton(AF_INET6, "FF05::13B", &bi->mcreq.ipv6mr_multiaddr));
2505 /* http://tools.ietf.org/html/rfc2553#section-5.2:
2509 * Join a multicast group on a specified local interface. If the
2510 * interface index is specified as 0, the kernel chooses the local
2511 * interface. For example, some kernels look up the multicast
2512 * group in the normal IPv6 routing table and using the resulting
2513 * interface; we do this for each interface, so no need to use
2514 * zero (anymore...).
2516 bi->mcreq.ipv6mr_interface = s6->sin6_scope_id;
2518 /* Join the multicast group */
2519 if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt(udp_sock,
2525 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "setsockopt");
2533 * Scan interfaces to broadcast our presence on the LAN.
2535 * @param cls NULL, unused
2538 do_broadcast(void *cls)
2540 struct BroadcastInterface *bin;
2543 for (struct BroadcastInterface *bi = bi_head; NULL != bi; bi = bi->next)
2544 bi->found = GNUNET_NO;
2545 GNUNET_OS_network_interfaces_list(&iface_proc, NULL);
2546 for (struct BroadcastInterface *bi = bi_head; NULL != bi; bi = bin)
2549 if (GNUNET_NO == bi->found)
2552 broadcast_task = GNUNET_SCHEDULER_add_delayed(INTERFACE_SCAN_FREQUENCY,
2559 * Setup communicator and launch network interactions.
2561 * @param cls NULL (always)
2562 * @param args remaining command-line arguments
2563 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2564 * @param c configuration
2569 const char *cfgfile,
2570 const struct GNUNET_CONFIGURATION_Handle *c)
2573 struct sockaddr *in;
2575 struct sockaddr_storage in_sto;
2581 GNUNET_CONFIGURATION_get_value_filename(cfg,
2582 COMMUNICATOR_CONFIG_SECTION,
2586 GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR,
2587 COMMUNICATOR_CONFIG_SECTION,
2592 in = udp_address_to_sockaddr(bindto, &in_len);
2595 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2596 "Failed to setup UDP socket address with path `%s'\n",
2598 GNUNET_free(bindto);
2602 GNUNET_NETWORK_socket_create(in->sa_family, SOCK_DGRAM, IPPROTO_UDP);
2603 if (NULL == udp_sock)
2605 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "socket");
2607 GNUNET_free(bindto);
2610 if (AF_INET6 == in->sa_family)
2611 have_v6_socket = GNUNET_YES;
2612 if (GNUNET_OK != GNUNET_NETWORK_socket_bind(udp_sock, in, in_len))
2614 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "bind", bindto);
2615 GNUNET_NETWORK_socket_close(udp_sock);
2618 GNUNET_free(bindto);
2621 /* We might have bound to port 0, allowing the OS to figure it out;
2622 thus, get the real IN-address from the socket */
2623 sto_len = sizeof(in_sto);
2624 if (0 != getsockname(GNUNET_NETWORK_get_fd(udp_sock),
2625 (struct sockaddr *)&in_sto,
2628 memcpy(&in_sto, in, in_len);
2632 GNUNET_free(bindto);
2633 in = (struct sockaddr *)&in_sto;
2635 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2637 GNUNET_a2s((const struct sockaddr *)&in_sto, sto_len));
2638 switch (in->sa_family)
2641 my_port = ntohs(((struct sockaddr_in *)in)->sin_port);
2645 my_port = ntohs(((struct sockaddr_in6 *)in)->sin6_port);
2652 stats = GNUNET_STATISTICS_create("C-UDP", cfg);
2653 senders = GNUNET_CONTAINER_multipeermap_create(32, GNUNET_YES);
2654 receivers = GNUNET_CONTAINER_multipeermap_create(32, GNUNET_YES);
2655 senders_heap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
2657 GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
2658 key_cache = GNUNET_CONTAINER_multishortmap_create(1024, GNUNET_YES);
2659 GNUNET_SCHEDULER_add_shutdown(&do_shutdown, NULL);
2660 is = GNUNET_NT_scanner_init();
2661 my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration(cfg);
2662 if (NULL == my_private_key)
2665 GNUNET_ERROR_TYPE_ERROR,
2667 "Transport service is lacking key configuration settings. Exiting.\n"));
2668 GNUNET_SCHEDULER_shutdown();
2671 GNUNET_CRYPTO_eddsa_key_get_public(my_private_key, &my_identity.public_key);
2673 read_task = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
2677 ch = GNUNET_TRANSPORT_communicator_connect(cfg,
2678 COMMUNICATOR_CONFIG_SECTION,
2679 COMMUNICATOR_ADDRESS_PREFIX,
2680 GNUNET_TRANSPORT_CC_UNRELIABLE,
2688 GNUNET_SCHEDULER_shutdown();
2691 ah = GNUNET_TRANSPORT_application_init(cfg);
2695 GNUNET_SCHEDULER_shutdown();
2698 /* start broadcasting */
2700 GNUNET_CONFIGURATION_get_value_yesno(cfg,
2701 COMMUNICATOR_CONFIG_SECTION,
2702 "DISABLE_BROADCAST"))
2704 broadcast_task = GNUNET_SCHEDULER_add_now(&do_broadcast, NULL);
2706 nat = GNUNET_NAT_register(cfg,
2707 COMMUNICATOR_CONFIG_SECTION,
2709 1 /* one address */,
2710 (const struct sockaddr **)&in,
2713 NULL /* FIXME: support reversal: #5529 */,
2714 NULL /* closure */);
2719 * The main function for the UNIX communicator.
2721 * @param argc number of arguments from the command line
2722 * @param argv command line arguments
2723 * @return 0 ok, 1 on error
2726 main(int argc, char *const *argv)
2728 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2729 GNUNET_GETOPT_OPTION_END
2733 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv))
2736 ret = (GNUNET_OK == GNUNET_PROGRAM_run(argc,
2738 "gnunet-communicator-udp",
2739 _("GNUnet UDP communicator"),
2745 GNUNET_free((void *)argv);
2750 /* end of gnunet-communicator-udp.c */