2 This file is part of GNUnet.
3 Copyright (C) 2013 GNUnet e.V.
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
22 #include "gnunet_util_lib.h"
24 #include "gnunet_signatures.h"
25 #include "gnunet_statistics_service.h"
27 #include "cadet_protocol.h"
28 #include "cadet_path.h"
30 #include "gnunet-service-cadet_tunnel.h"
31 #include "gnunet-service-cadet_connection.h"
32 #include "gnunet-service-cadet_channel.h"
33 #include "gnunet-service-cadet_peer.h"
35 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
36 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
38 #define REKEY_WAIT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
40 #if !defined(GNUNET_CULL_LOGGING)
41 #define DUMP_KEYS_TO_STDERR GNUNET_YES
43 #define DUMP_KEYS_TO_STDERR GNUNET_NO
46 #define MIN_TUNNEL_BUFFER 8
47 #define MAX_TUNNEL_BUFFER 64
48 #define MAX_SKIPPED_KEYS 64
49 #define MAX_KEY_GAP 256
50 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
51 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
53 /******************************************************************************/
54 /******************************** STRUCTS **********************************/
55 /******************************************************************************/
59 struct CadetTChannel *next;
60 struct CadetTChannel *prev;
61 struct CadetChannel *ch;
66 * Connection list and metadata.
68 struct CadetTConnection
73 struct CadetTConnection *next;
78 struct CadetTConnection *prev;
83 struct CadetConnection *c;
86 * Creation time, to keep oldest connection alive.
88 struct GNUNET_TIME_Absolute created;
91 * Connection throughput, to keep fastest connection alive.
98 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
100 struct CadetTunnelSkippedKey
105 struct CadetTunnelSkippedKey *next;
110 struct CadetTunnelSkippedKey *prev;
113 * When was this key stored (for timeout).
115 struct GNUNET_TIME_Absolute timestamp;
120 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
125 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
128 * Key number for a given HK.
135 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
137 struct CadetTunnelAxolotl
140 * A (double linked) list of stored message keys and associated header keys
141 * for "skipped" messages, i.e. messages that have not been
142 * received despite the reception of more recent messages, (head).
144 struct CadetTunnelSkippedKey *skipped_head;
147 * Skipped messages' keys DLL, tail.
149 struct CadetTunnelSkippedKey *skipped_tail;
152 * Elements in @a skipped_head <-> @a skipped_tail.
154 unsigned int skipped;
157 * 32-byte root key which gets updated by DH ratchet.
159 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
162 * 32-byte header key (send).
164 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
167 * 32-byte header key (recv)
169 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
172 * 32-byte next header key (send).
174 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
177 * 32-byte next header key (recv).
179 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
182 * 32-byte chain keys (used for forward-secrecy updating, send).
184 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
187 * 32-byte chain keys (used for forward-secrecy updating, recv).
189 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
192 * ECDH for key exchange (A0 / B0).
194 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
197 * ECDH Ratchet key (send).
199 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
202 * ECDH Ratchet key (recv).
204 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
207 * Message number (reset to 0 with each new ratchet, next message to send).
212 * Message number (reset to 0 with each new ratchet, next message to recv).
217 * Previous message numbers (# of msgs sent under prev ratchet)
222 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
227 * Number of messages recieved since our last ratchet advance.
228 * - If this counter = 0, we cannot send a new ratchet key in next msg.
229 * - If this counter > 0, we can (but don't yet have to) send a new key.
231 unsigned int ratchet_allowed;
234 * Number of messages recieved since our last ratchet advance.
235 * - If this counter = 0, we cannot send a new ratchet key in next msg.
236 * - If this counter > 0, we can (but don't yet have to) send a new key.
238 unsigned int ratchet_counter;
241 * When does this ratchet expire and a new one is triggered.
243 struct GNUNET_TIME_Absolute ratchet_expiration;
247 * Struct containing all information regarding a tunnel to a peer.
252 * Endpoint of the tunnel.
254 struct CadetPeer *peer;
259 struct CadetTunnelAxolotl *ax;
262 * State of the tunnel connectivity.
264 enum CadetTunnelCState cstate;
267 * State of the tunnel encryption.
269 enum CadetTunnelEState estate;
272 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
275 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
278 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
280 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
283 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
285 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
288 * Task to start the rekey process.
290 struct GNUNET_SCHEDULER_Task *rekey_task;
293 * Paths that are actively used to reach the destination peer.
295 struct CadetTConnection *connection_head;
296 struct CadetTConnection *connection_tail;
299 * Next connection number.
304 * Channels inside this tunnel.
306 struct CadetTChannel *channel_head;
307 struct CadetTChannel *channel_tail;
310 * Channel ID for the next created channel.
312 CADET_ChannelNumber next_chid;
315 * Destroy flag: if true, destroy on last message.
317 struct GNUNET_SCHEDULER_Task * destroy_task;
320 * Queued messages, to transmit once tunnel gets connected.
322 struct CadetTunnelDelayed *tq_head;
323 struct CadetTunnelDelayed *tq_tail;
326 * Task to trim connections if too many are present.
328 struct GNUNET_SCHEDULER_Task * trim_connections_task;
331 * Ephemeral message in the queue (to avoid queueing more than one).
333 struct CadetConnectionQueue *ephm_h;
336 * Pong message in the queue.
338 struct CadetConnectionQueue *pong_h;
343 * Struct used to save messages in a non-ready tunnel to send once connected.
345 struct CadetTunnelDelayed
350 struct CadetTunnelDelayed *next;
351 struct CadetTunnelDelayed *prev;
356 struct CadetTunnel *t;
359 * Tunnel queue given to the channel to cancel request. Update on send_queued.
361 struct CadetTunnelQueue *tq;
366 /* struct GNUNET_MessageHeader *msg; */
371 * Handle for messages queued but not yet sent.
373 struct CadetTunnelQueue
376 * Connection queue handle, to cancel if necessary.
378 struct CadetConnectionQueue *cq;
381 * Handle in case message hasn't been given to a connection yet.
383 struct CadetTunnelDelayed *tqd;
386 * Continuation to call once sent.
391 * Closure for @c cont.
397 /******************************************************************************/
398 /******************************* GLOBALS ***********************************/
399 /******************************************************************************/
402 * Global handle to the statistics service.
404 extern struct GNUNET_STATISTICS_Handle *stats;
407 * Local peer own ID (memory efficient handle).
409 extern GNUNET_PEER_Id myid;
412 * Local peer own ID (full value).
414 extern struct GNUNET_PeerIdentity my_full_id;
418 * Don't try to recover tunnels if shutting down.
420 extern int shutting_down;
424 * Set of all tunnels, in order to trigger a new exchange on rekey.
425 * Indexed by peer's ID.
427 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
430 * Own Peer ID private key.
432 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
435 /******************************** AXOLOTL ************************************/
438 * How many messages are needed to trigger a ratchet advance.
440 static unsigned long long ratchet_messages;
443 * How long until we trigger a ratched advance.
445 static struct GNUNET_TIME_Relative ratchet_time;
448 /******************************************************************************/
449 /******************************** STATIC ***********************************/
450 /******************************************************************************/
453 * Get string description for tunnel connectivity state.
455 * @param cs Tunnel state.
457 * @return String representation.
460 cstate2s (enum CadetTunnelCState cs)
466 case CADET_TUNNEL_NEW:
467 return "CADET_TUNNEL_NEW";
468 case CADET_TUNNEL_SEARCHING:
469 return "CADET_TUNNEL_SEARCHING";
470 case CADET_TUNNEL_WAITING:
471 return "CADET_TUNNEL_WAITING";
472 case CADET_TUNNEL_READY:
473 return "CADET_TUNNEL_READY";
474 case CADET_TUNNEL_SHUTDOWN:
475 return "CADET_TUNNEL_SHUTDOWN";
477 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
485 * Get string description for tunnel encryption state.
487 * @param es Tunnel state.
489 * @return String representation.
492 estate2s (enum CadetTunnelEState es)
498 case CADET_TUNNEL_KEY_UNINITIALIZED:
499 return "CADET_TUNNEL_KEY_UNINITIALIZED";
500 case CADET_TUNNEL_KEY_SENT:
501 return "CADET_TUNNEL_KEY_SENT";
502 case CADET_TUNNEL_KEY_PING:
503 return "CADET_TUNNEL_KEY_PING";
504 case CADET_TUNNEL_KEY_OK:
505 return "CADET_TUNNEL_KEY_OK";
506 case CADET_TUNNEL_KEY_REKEY:
507 return "CADET_TUNNEL_KEY_REKEY";
509 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
517 * @brief Check if tunnel is ready to send traffic.
519 * Tunnel must be connected and with encryption correctly set up.
521 * @param t Tunnel to check.
523 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
526 is_ready (struct CadetTunnel *t)
532 conn_ok = CADET_TUNNEL_READY == t->cstate;
533 enc_ok = CADET_TUNNEL_KEY_OK == t->estate
534 || CADET_TUNNEL_KEY_REKEY == t->estate
535 || CADET_TUNNEL_KEY_PING == t->estate;
536 ready = conn_ok && enc_ok;
537 ready = ready || GCT_is_loopback (t);
543 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
545 * @param tch Tunnel's channel handle.
547 * @return Amount of messages the channel can still buffer towards the client.
550 get_channel_buffer (const struct CadetTChannel *tch)
554 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
555 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
557 return GCCH_get_buffer (tch->ch, fwd);
562 * Get the channel's allowance status.
564 * @param tch Tunnel's channel handle.
566 * @return #GNUNET_YES if we allowed the client to send data to us.
569 get_channel_allowed (const struct CadetTChannel *tch)
573 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
574 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
576 return GCCH_get_allowed (tch->ch, fwd);
581 * Get the connection's buffer.
583 * @param tc Tunnel's connection handle.
585 * @return Amount of messages the connection can still buffer.
588 get_connection_buffer (const struct CadetTConnection *tc)
592 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
593 fwd = GCC_is_origin (tc->c, GNUNET_YES);
595 return GCC_get_buffer (tc->c, fwd);
600 * Get the connection's allowance.
602 * @param tc Tunnel's connection handle.
604 * @return Amount of messages we have allowed the next peer to send us.
607 get_connection_allowed (const struct CadetTConnection *tc)
611 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
612 fwd = GCC_is_origin (tc->c, GNUNET_YES);
614 return GCC_get_allowed (tc->c, fwd);
619 * Create a new Axolotl ephemeral (ratchet) key.
624 new_ephemeral (struct CadetTunnel *t)
626 GNUNET_free_non_null (t->ax->DHRs);
627 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
628 #if DUMP_KEYS_TO_STDERR
630 struct GNUNET_CRYPTO_EcdhePublicKey pub;
631 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &pub);
632 LOG (GNUNET_ERROR_TYPE_DEBUG, " new DHRs generated: pub %s\n",
633 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &pub));
642 * @param plaintext Content to HMAC.
643 * @param size Size of @c plaintext.
644 * @param iv Initialization vector for the message.
645 * @param key Key to use.
646 * @param hmac[out] Destination to store the HMAC.
649 t_hmac (const void *plaintext, size_t size,
650 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
651 struct GNUNET_CADET_Hash *hmac)
653 static const char ctx[] = "cadet authentication key";
654 struct GNUNET_CRYPTO_AuthKey auth_key;
655 struct GNUNET_HashCode hash;
657 #if DUMP_KEYS_TO_STDERR
658 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC %u bytes with key %s\n", size,
659 GNUNET_i2s ((struct GNUNET_PeerIdentity *) key));
661 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
666 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
667 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
668 GNUNET_memcpy (hmac, &hash, sizeof (*hmac));
675 * @param key Key to use.
676 * @param hash[out] Resulting HMAC.
677 * @param source Source key material (data to HMAC).
678 * @param len Length of @a source.
681 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
682 struct GNUNET_HashCode *hash,
683 void *source, unsigned int len)
685 static const char ctx[] = "axolotl HMAC-HASH";
686 struct GNUNET_CRYPTO_AuthKey auth_key;
688 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
691 GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
696 * Derive a key from a HMAC-HASH.
698 * @param key Key to use for the HMAC.
699 * @param out Key to generate.
700 * @param source Source key material (data to HMAC).
701 * @param len Length of @a source.
704 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
705 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
706 void *source, unsigned int len)
708 static const char ctx[] = "axolotl derive key";
709 struct GNUNET_HashCode h;
711 t_ax_hmac_hash (key, &h, source, len);
712 GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
713 &h, sizeof (h), NULL);
718 * Encrypt data with the axolotl tunnel key.
720 * @param t Tunnel whose key to use.
721 * @param dst Destination for the encrypted data.
722 * @param src Source of the plaintext. Can overlap with @c dst.
723 * @param size Size of the plaintext.
725 * @return Size of the encrypted data.
728 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
730 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
731 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
732 struct CadetTunnelAxolotl *ax;
737 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
739 ax->ratchet_counter++;
740 if (GNUNET_YES == ax->ratchet_allowed
741 && (ratchet_messages <= ax->ratchet_counter
742 || 0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us))
744 ax->ratchet_flag = GNUNET_YES;
747 if (GNUNET_YES == ax->ratchet_flag)
749 /* Advance ratchet */
750 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
751 struct GNUNET_HashCode dh;
752 struct GNUNET_HashCode hmac;
753 static const char ctx[] = "axolotl ratchet";
758 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
759 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
760 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
761 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
762 &hmac, sizeof (hmac), NULL);
769 ax->ratchet_flag = GNUNET_NO;
770 ax->ratchet_allowed = GNUNET_NO;
771 ax->ratchet_counter = 0;
772 ax->ratchet_expiration =
773 GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
776 t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
777 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
779 #if DUMP_KEYS_TO_STDERR
780 LOG (GNUNET_ERROR_TYPE_DEBUG, " CKs: %s\n",
781 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKs));
782 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC with key %u: %s\n", ax->Ns,
783 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &MK));
786 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
787 t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
796 * Decrypt data with the axolotl tunnel key.
798 * @param t Tunnel whose key to use.
799 * @param dst Destination for the decrypted data.
800 * @param src Source of the ciphertext. Can overlap with @c dst.
801 * @param size Size of the ciphertext.
803 * @return Size of the decrypted data.
806 t_ax_decrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
808 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
809 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
810 struct CadetTunnelAxolotl *ax;
813 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt start\n");
817 t_hmac_derive_key (&ax->CKr, &MK, "0", 1);
818 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
820 #if DUMP_KEYS_TO_STDERR
821 LOG (GNUNET_ERROR_TYPE_DEBUG, " CKr: %s\n",
822 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKr));
823 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with key %u: %s\n", ax->Nr,
824 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &MK));
827 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
828 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, &MK, &iv, dst);
829 GNUNET_assert (out_size == size);
831 t_hmac_derive_key (&ax->CKr, &ax->CKr, "1", 1);
833 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
840 * Encrypt header with the axolotl header key.
842 * @param t Tunnel whose key to use.
843 * @param msg Message whose header to encrypt.
846 t_h_encrypt (struct CadetTunnel *t, struct GNUNET_CADET_Encrypted *msg)
848 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
849 struct CadetTunnelAxolotl *ax;
852 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_encrypt start\n");
855 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKs, NULL, 0, NULL);
857 #if DUMP_KEYS_TO_STDERR
858 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC_H with key %s\n",
859 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKs));
862 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns, AX_HEADER_SIZE,
863 &ax->HKs, &iv, &msg->Ns);
865 GNUNET_assert (AX_HEADER_SIZE == out_size);
867 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
872 * Decrypt header with the current axolotl header key.
874 * @param t Tunnel whose current ax HK to use.
875 * @param src Message whose header to decrypt.
876 * @param dst Where to decrypt header to.
879 t_h_decrypt (struct CadetTunnel *t, const struct GNUNET_CADET_Encrypted *src,
880 struct GNUNET_CADET_Encrypted *dst)
882 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
883 struct CadetTunnelAxolotl *ax;
886 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_decrypt start\n");
889 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKr, NULL, 0, NULL);
891 #if DUMP_KEYS_TO_STDERR
892 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC_H with key %s\n",
893 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKr));
896 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
897 &ax->HKr, &iv, &dst->Ns);
899 GNUNET_assert (AX_HEADER_SIZE == out_size);
901 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_decrypt end\n");
906 * Decrypt and verify data with the appropriate tunnel key and verify that the
907 * data has not been altered since it was sent by the remote peer.
909 * @param t Tunnel whose key to use.
910 * @param dst Destination for the plaintext.
911 * @param src Source of the message. Can overlap with @c dst.
912 * @param size Size of the message.
914 * @return Size of the decrypted data, -1 if an error was encountered.
917 try_old_ax_keys (struct CadetTunnel *t, void *dst,
918 const struct GNUNET_CADET_Encrypted *src, size_t size)
920 struct CadetTunnelSkippedKey *key;
921 struct GNUNET_CADET_Hash *hmac;
922 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
923 struct GNUNET_CADET_Encrypted plaintext_header;
924 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
930 LOG (GNUNET_ERROR_TYPE_DEBUG, "Trying old keys\n");
931 hmac = &plaintext_header.hmac;
932 esize = size - sizeof (struct GNUNET_CADET_Encrypted);
934 /* Find a correct Header Key */
935 for (key = t->ax->skipped_head; NULL != key; key = key->next)
937 #if DUMP_KEYS_TO_STDERR
938 LOG (GNUNET_ERROR_TYPE_DEBUG, " Trying hmac with key %s\n",
939 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->HK));
941 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &key->HK, hmac);
942 if (0 == memcmp (hmac, &src->hmac, sizeof (*hmac)))
944 LOG (GNUNET_ERROR_TYPE_DEBUG, " hmac correct\n");
952 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
953 GNUNET_assert (size > sizeof (struct GNUNET_CADET_Encrypted));
954 len = size - sizeof (struct GNUNET_CADET_Encrypted);
955 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
958 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->HK, NULL, 0, NULL);
959 res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
960 &key->HK, &iv, &plaintext_header.Ns);
961 GNUNET_assert (AX_HEADER_SIZE == res);
962 LOG (GNUNET_ERROR_TYPE_DEBUG, " Message %u, previous: %u\n",
963 ntohl (plaintext_header.Ns), ntohl (plaintext_header.PNs));
965 /* Find the correct Message Key */
966 N = ntohl (plaintext_header.Ns);
967 while (NULL != key && N != key->Kn)
969 if (NULL == key || 0 != memcmp (&key->HK, valid_HK, sizeof (*valid_HK)))
972 #if DUMP_KEYS_TO_STDERR
973 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC_H with skipped key %s\n",
974 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->HK));
975 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with skipped key %u: %s\n",
976 key->Kn, GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->MK));
979 /* Decrypt payload */
980 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->MK, NULL, 0, NULL);
981 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1], len, &key->MK, &iv, dst);
984 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
986 GNUNET_free (key); /* GNUNET_free overwrites memory with 0xbaadf00d */
993 * Delete a key from the list of skipped keys.
995 * @param t Tunnel to delete from.
996 * @param HKr Header Key to use.
999 store_skipped_key (struct CadetTunnel *t,
1000 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1002 struct CadetTunnelSkippedKey *key;
1004 key = GNUNET_new (struct CadetTunnelSkippedKey);
1005 key->timestamp = GNUNET_TIME_absolute_get ();
1006 key->Kn = t->ax->Nr;
1007 key->HK = t->ax->HKr;
1008 t_hmac_derive_key (&t->ax->CKr, &key->MK, "0", 1);
1009 #if DUMP_KEYS_TO_STDERR
1010 LOG (GNUNET_ERROR_TYPE_DEBUG, " storing MK for Nr %u: %s\n",
1011 key->Kn, GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->MK));
1012 LOG (GNUNET_ERROR_TYPE_DEBUG, " for CKr: %s\n",
1013 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->ax->CKr));
1015 t_hmac_derive_key (&t->ax->CKr, &t->ax->CKr, "1", 1);
1016 GNUNET_CONTAINER_DLL_insert (t->ax->skipped_head, t->ax->skipped_tail, key);
1023 * Delete a key from the list of skipped keys.
1025 * @param t Tunnel to delete from.
1026 * @param key Key to delete.
1029 delete_skipped_key (struct CadetTunnel *t, struct CadetTunnelSkippedKey *key)
1031 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1038 * Stage skipped AX keys and calculate the message key.
1040 * Stores each HK and MK for skipped messages.
1042 * @param t Tunnel where to stage the keys.
1043 * @param HKr Header key.
1044 * @param Np Received meesage number.
1046 * @return GNUNET_OK if keys were stored.
1047 * GNUNET_SYSERR if an error ocurred (Np not expected).
1050 store_ax_keys (struct CadetTunnel *t,
1051 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1057 gap = Np - t->ax->Nr;
1058 LOG (GNUNET_ERROR_TYPE_INFO, "Storing keys [%u, %u)\n", t->ax->Nr, Np);
1059 if (MAX_KEY_GAP < gap)
1061 /* Avoid DoS (forcing peer to do 2*33 chain HMAC operations) */
1062 /* TODO: start new key exchange on return */
1063 GNUNET_break_op (0);
1064 LOG (GNUNET_ERROR_TYPE_WARNING, "Got message %u, expected %u+\n",
1066 return GNUNET_SYSERR;
1070 /* Delayed message: don't store keys, flag to try old keys. */
1071 return GNUNET_SYSERR;
1074 while (t->ax->Nr < Np)
1075 store_skipped_key (t, HKr);
1077 while (t->ax->skipped > MAX_SKIPPED_KEYS)
1078 delete_skipped_key (t, t->ax->skipped_tail);
1085 * Decrypt and verify data with the appropriate tunnel key and verify that the
1086 * data has not been altered since it was sent by the remote peer.
1088 * @param t Tunnel whose key to use.
1089 * @param dst Destination for the plaintext.
1090 * @param src Source of the message. Can overlap with @c dst.
1091 * @param size Size of the message.
1093 * @return Size of the decrypted data, -1 if an error was encountered.
1096 t_ax_decrypt_and_validate (struct CadetTunnel *t, void *dst,
1097 const struct GNUNET_CADET_Encrypted *src,
1100 struct CadetTunnelAxolotl *ax;
1101 struct GNUNET_CADET_Hash msg_hmac;
1102 struct GNUNET_HashCode hmac;
1103 struct GNUNET_CADET_Encrypted plaintext_header;
1106 size_t esize; /* Size of encryped payload */
1107 size_t osize; /* Size of output (decrypted payload) */
1109 esize = size - sizeof (struct GNUNET_CADET_Encrypted);
1114 /* Try current HK */
1115 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->HKr, &msg_hmac);
1116 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1118 static const char ctx[] = "axolotl ratchet";
1119 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1120 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1121 struct GNUNET_HashCode dh;
1122 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1125 LOG (GNUNET_ERROR_TYPE_DEBUG, " trying next HK\n");
1126 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->NHKr, &msg_hmac);
1127 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1129 /* Try the skipped keys, if that fails, we're out of luck. */
1130 return try_old_ax_keys (t, dst, src, size);
1132 LOG (GNUNET_ERROR_TYPE_INFO, "next HK worked\n");
1136 t_h_decrypt (t, src, &plaintext_header);
1137 Np = ntohl (plaintext_header.Ns);
1138 PNp = ntohl (plaintext_header.PNs);
1139 DHRp = &plaintext_header.DHRs;
1140 store_ax_keys (t, &HK, PNp);
1142 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1143 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, DHRp, &dh);
1144 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1145 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1146 &hmac, sizeof (hmac), NULL);
1148 /* Commit "purported" keys */
1154 ax->ratchet_allowed = GNUNET_YES;
1158 LOG (GNUNET_ERROR_TYPE_DEBUG, "current HK\n");
1159 t_h_decrypt (t, src, &plaintext_header);
1160 Np = ntohl (plaintext_header.Ns);
1161 PNp = ntohl (plaintext_header.PNs);
1163 LOG (GNUNET_ERROR_TYPE_INFO, " got AX Nr %u\n", Np);
1165 if (GNUNET_OK != store_ax_keys (t, &ax->HKr, Np))
1166 /* Try the skipped keys, if that fails, we're out of luck. */
1167 return try_old_ax_keys (t, dst, src, size);
1169 osize = t_ax_decrypt (t, dst, &src[1], esize);
1174 GNUNET_break_op (0);
1183 * Pick a connection on which send the next data message.
1185 * @param t Tunnel on which to send the message.
1187 * @return The connection on which to send the next message.
1189 static struct CadetConnection *
1190 tunnel_get_connection (struct CadetTunnel *t)
1192 struct CadetTConnection *iter;
1193 struct CadetConnection *best;
1195 unsigned int lowest_q;
1197 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1199 lowest_q = UINT_MAX;
1200 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1202 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1203 GCC_2s (iter->c), GCC_get_state (iter->c));
1204 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1206 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1207 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1215 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1221 * Callback called when a queued message is sent.
1223 * Calculates the average time and connection packet tracking.
1225 * @param cls Closure (TunnelQueue handle).
1226 * @param c Connection this message was on.
1227 * @param q Connection queue handle (unused).
1228 * @param type Type of message sent.
1229 * @param fwd Was this a FWD going message?
1230 * @param size Size of the message.
1233 tun_message_sent (void *cls,
1234 struct CadetConnection *c,
1235 struct CadetConnectionQueue *q,
1236 uint16_t type, int fwd, size_t size)
1238 struct CadetTunnelQueue *qt = cls;
1239 struct CadetTunnel *t;
1241 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1243 GNUNET_assert (NULL != qt->cont);
1244 t = NULL == c ? NULL : GCC_get_tunnel (c);
1245 qt->cont (qt->cont_cls, t, qt, type, size);
1251 count_queued_data (const struct CadetTunnel *t)
1253 struct CadetTunnelDelayed *iter;
1256 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1263 * Delete a queued message: either was sent or the channel was destroyed
1264 * before the tunnel's key exchange had a chance to finish.
1266 * @param tqd Delayed queue handle.
1269 unqueue_data (struct CadetTunnelDelayed *tqd)
1271 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1277 * Cache a message to be sent once tunnel is online.
1279 * @param t Tunnel to hold the message.
1280 * @param msg Message itself (copy will be made).
1282 static struct CadetTunnelDelayed *
1283 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1285 struct CadetTunnelDelayed *tqd;
1286 uint16_t size = ntohs (msg->size);
1288 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1290 GNUNET_assert (GNUNET_NO == is_ready (t));
1292 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1295 GNUNET_memcpy (&tqd[1], msg, size);
1296 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1302 * Sends an already built message on a tunnel, encrypting it and
1303 * choosing the best connection.
1305 * @param message Message to send. Function modifies it.
1306 * @param t Tunnel on which this message is transmitted.
1307 * @param c Connection to use (autoselect if NULL).
1308 * @param force Force the tunnel to take the message (buffer overfill).
1309 * @param cont Continuation to call once message is really sent.
1310 * @param cont_cls Closure for @c cont.
1311 * @param existing_q In case this a transmission of previously queued data,
1312 * this should be TunnelQueue given to the client.
1314 * @return Handle to cancel message.
1315 * NULL if @c cont is NULL or an error happens and message is dropped.
1317 static struct CadetTunnelQueue *
1318 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1319 struct CadetTunnel *t,
1320 struct CadetConnection *c,
1324 struct CadetTunnelQueue *existing_q)
1326 struct GNUNET_MessageHeader *msg;
1327 struct GNUNET_CADET_Encrypted *ax_msg;
1328 struct CadetTunnelQueue *tq;
1329 size_t size = ntohs (message->size);
1330 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size] GNUNET_ALIGN;
1336 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1338 if (GNUNET_NO == is_ready (t))
1340 struct CadetTunnelDelayed *tqd;
1341 /* A non null existing_q indicates sending of queued data.
1342 * Should only happen after tunnel becomes ready.
1344 GNUNET_assert (NULL == existing_q);
1345 tqd = queue_data (t, message);
1348 tq = GNUNET_new (struct CadetTunnelQueue);
1352 tq->cont_cls = cont_cls;
1356 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1358 ax_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1359 msg = &ax_msg->header;
1360 msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1361 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1362 esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1363 ax_msg->Ns = htonl (t->ax->Ns++);
1364 ax_msg->PNs = htonl (t->ax->PNs);
1365 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1366 t_h_encrypt (t, ax_msg);
1367 t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1368 GNUNET_assert (esize == size);
1371 c = tunnel_get_connection (t);
1374 /* Why is tunnel 'ready'? Should have been queued! */
1375 if (NULL != t->destroy_task)
1378 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1380 return NULL; /* Drop... */
1382 fwd = GCC_is_origin (c, GNUNET_YES);
1383 ax_msg->cid = *GCC_get_id (c);
1384 ax_msg->pid = htonl (GCC_get_pid (c, fwd));
1387 type = ntohs (message->type);
1390 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1391 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1392 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1393 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1395 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1397 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1398 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1399 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1400 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1401 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1405 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1407 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1411 (void) GCC_send_prebuilt_message (msg, type, mid, c, fwd,
1415 if (NULL == existing_q)
1417 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1424 tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1425 &tun_message_sent, tq);
1426 GNUNET_assert (NULL != tq->cq);
1428 tq->cont_cls = cont_cls;
1435 * Send all cached messages that we can, tunnel is online.
1437 * @param t Tunnel that holds the messages. Cannot be loopback.
1440 send_queued_data (struct CadetTunnel *t)
1442 struct CadetTunnelDelayed *tqd;
1443 struct CadetTunnelDelayed *next;
1446 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1448 if (GCT_is_loopback (t))
1454 if (GNUNET_NO == is_ready (t))
1456 LOG (GNUNET_ERROR_TYPE_WARNING, " not ready yet: %s/%s\n",
1457 estate2s (t->estate), cstate2s (t->cstate));
1461 room = GCT_get_connections_buffer (t);
1462 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1463 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1464 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1466 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1469 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1470 tqd->t, NULL, GNUNET_YES,
1471 NULL != tqd->tq ? tqd->tq->cont : NULL,
1472 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1476 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1481 * @brief Resend the KX until we complete the handshake.
1483 * @param cls Closure (tunnel).
1486 kx_resend (void *cls)
1488 struct CadetTunnel *t = cls;
1490 t->rekey_task = NULL;
1491 if (CADET_TUNNEL_KEY_OK == t->estate)
1493 /* Should have been canceled on estate change */
1498 GCT_send_kx (t, CADET_TUNNEL_KEY_SENT >= t->estate);
1503 * Callback called when a queued message is sent.
1505 * @param cls Closure.
1506 * @param c Connection this message was on.
1507 * @param type Type of message sent.
1508 * @param fwd Was this a FWD going message?
1509 * @param size Size of the message.
1512 ephm_sent (void *cls,
1513 struct CadetConnection *c,
1514 struct CadetConnectionQueue *q,
1515 uint16_t type, int fwd, size_t size)
1517 struct CadetTunnel *t = cls;
1518 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
1522 if (CADET_TUNNEL_KEY_OK == t->estate)
1525 if (NULL != t->rekey_task)
1528 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1529 GNUNET_SCHEDULER_cancel (t->rekey_task);
1531 t->rekey_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1538 * Called only on shutdown, destroy every tunnel.
1540 * @param cls Closure (unused).
1541 * @param key Current public key.
1542 * @param value Value in the hash map (tunnel).
1544 * @return #GNUNET_YES, so we should continue to iterate,
1547 destroy_iterator (void *cls,
1548 const struct GNUNET_PeerIdentity *key,
1551 struct CadetTunnel *t = value;
1553 LOG (GNUNET_ERROR_TYPE_DEBUG,
1554 "GCT_shutdown destroying tunnel at %p\n", t);
1561 * Notify remote peer that we don't know a channel he is talking about,
1562 * probably CHANNEL_DESTROY was missed.
1564 * @param t Tunnel on which to notify.
1565 * @param gid ID of the channel.
1568 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1570 struct GNUNET_CADET_ChannelManage msg;
1572 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1573 msg.header.size = htons (sizeof (msg));
1574 msg.chid = htonl (gid);
1576 LOG (GNUNET_ERROR_TYPE_DEBUG,
1577 "WARNING destroying unknown channel %u on tunnel %s\n",
1579 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1584 * Demultiplex data per channel and call appropriate channel handler.
1586 * @param t Tunnel on which the data came.
1587 * @param msg Data message.
1588 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1589 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1590 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1591 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1594 handle_data (struct CadetTunnel *t,
1595 const struct GNUNET_CADET_Data *msg,
1598 struct CadetChannel *ch;
1604 size = ntohs (msg->header.size);
1606 sizeof (struct GNUNET_CADET_Data) +
1607 sizeof (struct GNUNET_MessageHeader))
1612 type = ntohs (msg[1].header.type);
1613 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n", GC_m2s (type));
1614 SPRINTF (buf, "# received payload of type %hu", type);
1615 GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
1619 ch = GCT_get_channel (t, ntohl (msg->chid));
1622 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1624 LOG (GNUNET_ERROR_TYPE_DEBUG, "channel 0x%X unknown\n", ntohl (msg->chid));
1625 send_channel_destroy (t, ntohl (msg->chid));
1629 GCCH_handle_data (ch, msg, fwd);
1634 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1636 * @param t Tunnel on which the DATA ACK came.
1637 * @param msg DATA ACK message.
1638 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1639 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1640 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1641 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1644 handle_data_ack (struct CadetTunnel *t,
1645 const struct GNUNET_CADET_DataACK *msg,
1648 struct CadetChannel *ch;
1652 size = ntohs (msg->header.size);
1653 if (size != sizeof (struct GNUNET_CADET_DataACK))
1660 ch = GCT_get_channel (t, ntohl (msg->chid));
1663 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1665 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1670 GCCH_handle_data_ack (ch, msg, fwd);
1675 * Handle channel create.
1677 * @param t Tunnel on which the message came.
1678 * @param msg ChannelCreate message.
1681 handle_ch_create (struct CadetTunnel *t,
1682 const struct GNUNET_CADET_ChannelCreate *msg)
1684 struct CadetChannel *ch;
1688 size = ntohs (msg->header.size);
1689 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1691 GNUNET_break_op (0);
1696 ch = GCT_get_channel (t, ntohl (msg->chid));
1697 if (NULL != ch && ! GCT_is_loopback (t))
1699 /* Probably a retransmission, safe to ignore */
1700 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1702 ch = GCCH_handle_create (t, msg);
1704 GCT_add_channel (t, ch);
1710 * Handle channel NACK: check correctness and call channel handler for NACKs.
1712 * @param t Tunnel on which the NACK came.
1713 * @param msg NACK message.
1716 handle_ch_nack (struct CadetTunnel *t,
1717 const struct GNUNET_CADET_ChannelManage *msg)
1719 struct CadetChannel *ch;
1723 size = ntohs (msg->header.size);
1724 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1731 ch = GCT_get_channel (t, ntohl (msg->chid));
1734 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1736 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1741 GCCH_handle_nack (ch);
1746 * Handle a CHANNEL ACK (SYNACK/ACK).
1748 * @param t Tunnel on which the CHANNEL ACK came.
1749 * @param msg CHANNEL ACK message.
1750 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1751 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1752 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1753 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1756 handle_ch_ack (struct CadetTunnel *t,
1757 const struct GNUNET_CADET_ChannelManage *msg,
1760 struct CadetChannel *ch;
1764 size = ntohs (msg->header.size);
1765 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1772 ch = GCT_get_channel (t, ntohl (msg->chid));
1775 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1777 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1782 GCCH_handle_ack (ch, msg, fwd);
1787 * Handle a channel destruction message.
1789 * @param t Tunnel on which the message came.
1790 * @param msg Channel destroy message.
1791 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1792 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1793 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1794 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1797 handle_ch_destroy (struct CadetTunnel *t,
1798 const struct GNUNET_CADET_ChannelManage *msg,
1801 struct CadetChannel *ch;
1805 size = ntohs (msg->header.size);
1806 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1813 ch = GCT_get_channel (t, ntohl (msg->chid));
1816 /* Probably a retransmission, safe to ignore */
1820 GCCH_handle_destroy (ch, msg, fwd);
1825 * Free Axolotl data.
1830 destroy_ax (struct CadetTunnel *t)
1835 GNUNET_free_non_null (t->ax->DHRs);
1836 GNUNET_free_non_null (t->ax->kx_0);
1837 while (NULL != t->ax->skipped_head)
1838 delete_skipped_key (t, t->ax->skipped_head);
1839 GNUNET_assert (0 == t->ax->skipped);
1841 GNUNET_free (t->ax);
1844 if (NULL != t->rekey_task)
1846 GNUNET_SCHEDULER_cancel (t->rekey_task);
1847 t->rekey_task = NULL;
1849 if (NULL != t->ephm_h)
1851 GCC_cancel (t->ephm_h);
1858 * Demultiplex by message type and call appropriate handler for a message
1859 * towards a channel of a local tunnel.
1861 * @param t Tunnel this message came on.
1862 * @param msgh Message header.
1863 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1864 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1865 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1866 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1869 handle_decrypted (struct CadetTunnel *t,
1870 const struct GNUNET_MessageHeader *msgh,
1876 type = ntohs (msgh->type);
1877 LOG (GNUNET_ERROR_TYPE_DEBUG, "<-- %s on %s\n", GC_m2s (type), GCT_2s (t));
1878 SPRINTF (buf, "# received encrypted of type %hu (%s)", type, GC_m2s (type));
1879 GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
1883 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1884 /* Do nothing, connection aleady got updated. */
1885 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1888 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1889 /* Don't send hop ACK, wait for client to ACK */
1890 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1893 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1894 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1897 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1898 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
1901 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1902 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
1905 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1906 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
1909 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1910 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
1914 GNUNET_break_op (0);
1915 LOG (GNUNET_ERROR_TYPE_WARNING,
1916 "end-to-end message not known (%u)\n",
1917 ntohs (msgh->type));
1918 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1923 /******************************************************************************/
1924 /******************************** API ***********************************/
1925 /******************************************************************************/
1928 * Decrypt and process an encrypted message.
1930 * Calls the appropriate handler for a message in a channel of a local tunnel.
1932 * @param t Tunnel this message came on.
1933 * @param msg Message header.
1936 GCT_handle_encrypted (struct CadetTunnel *t,
1937 const struct GNUNET_CADET_Encrypted *msg)
1939 uint16_t size = ntohs (msg->header.size);
1942 const struct GNUNET_MessageHeader *msgh;
1945 GNUNET_STATISTICS_update (stats, "# received encrypted", 1, GNUNET_NO);
1947 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, msg, size);
1949 if (-1 == decrypted_size)
1951 GNUNET_STATISTICS_update (stats, "# unable to decrypt", 1, GNUNET_NO);
1952 if (CADET_TUNNEL_KEY_PING <= t->estate)
1954 GNUNET_break_op (0);
1955 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong crypto, tunnel %s\n", GCT_2s (t));
1956 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1960 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
1962 /* FIXME: this is bad, as the structs returned from
1963 this loop may be unaligned, see util's MST for
1964 how to do this right. */
1966 while (off + sizeof (struct GNUNET_MessageHeader) <= decrypted_size)
1970 msgh = (const struct GNUNET_MessageHeader *) &cbuf[off];
1971 msize = ntohs (msgh->size);
1972 if (msize < sizeof (struct GNUNET_MessageHeader))
1974 GNUNET_break_op (0);
1977 if (off + msize < decrypted_size)
1979 GNUNET_break_op (0);
1982 handle_decrypted (t, msgh, GNUNET_SYSERR);
1989 * Handle a Key eXchange message.
1991 * @param t Tunnel on which the message came.
1992 * @param msg KX message itself.
1995 GCT_handle_kx (struct CadetTunnel *t,
1996 const struct GNUNET_CADET_KX *msg)
1998 struct CadetTunnelAxolotl *ax;
1999 struct GNUNET_HashCode key_material[3];
2000 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2001 const char salt[] = "CADET Axolotl salt";
2002 const struct GNUNET_PeerIdentity *pid;
2007 LOG (GNUNET_ERROR_TYPE_INFO, "<== { KX} on %s\n", GCT_2s (t));
2011 /* Something is wrong if ax is NULL. Whose fault it is? */
2016 pid = GCT_get_destination (t);
2017 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2018 am_I_alice = GNUNET_YES;
2019 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2020 am_I_alice = GNUNET_NO;
2023 GNUNET_break_op (0);
2027 if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
2029 if (NULL != t->rekey_task)
2031 GNUNET_SCHEDULER_cancel (t->rekey_task);
2032 t->rekey_task = NULL;
2034 GCT_send_kx (t, GNUNET_NO);
2037 if (0 == memcmp (&ax->DHRr, &msg->ratchet_key, sizeof(msg->ratchet_key)))
2039 LOG (GNUNET_ERROR_TYPE_INFO, " known ratchet key, exit\n");
2043 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2045 ax->DHRr = msg->ratchet_key;
2048 if (GNUNET_YES == am_I_alice)
2050 GNUNET_CRYPTO_eddsa_ecdh (id_key, /* A */
2051 &msg->ephemeral_key, /* B0 */
2056 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
2057 &pid->public_key, /* A */
2062 if (GNUNET_YES == am_I_alice)
2064 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
2065 &pid->public_key, /* B */
2070 GNUNET_CRYPTO_eddsa_ecdh (id_key, /* A */
2071 &msg->ephemeral_key, /* B0 */
2078 /* (This is the triple-DH, we could probably safely skip this,
2079 as A0/B0 are already in the key material.) */
2080 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
2081 &msg->ephemeral_key, /* B0 or A0 */
2084 #if DUMP_KEYS_TO_STDERR
2087 for (i = 0; i < 3; i++)
2088 LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2089 i, GNUNET_h2s (&key_material[i]));
2094 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2095 salt, sizeof (salt),
2096 &key_material, sizeof (key_material), NULL);
2098 if (0 == memcmp (&ax->RK, &keys[0], sizeof(ax->RK)))
2100 LOG (GNUNET_ERROR_TYPE_INFO, " known handshake key, exit\n");
2104 if (GNUNET_YES == am_I_alice)
2110 ax->ratchet_flag = GNUNET_YES;
2118 ax->ratchet_flag = GNUNET_NO;
2119 ax->ratchet_allowed = GNUNET_NO;
2120 ax->ratchet_counter = 0;
2121 ax->ratchet_expiration =
2122 GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
2128 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2129 send_queued_data (t);
2135 * Initialize the tunnel subsystem.
2137 * @param c Configuration handle.
2138 * @param key ECC private key, to derive all other keys and do crypto.
2141 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2142 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2144 unsigned int expected_overhead;
2146 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2148 expected_overhead = 0;
2149 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
2150 expected_overhead += sizeof (struct GNUNET_CADET_Data);
2151 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
2152 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2155 GNUNET_CONFIGURATION_get_value_number (c,
2160 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2164 ratchet_messages = 64;
2167 GNUNET_CONFIGURATION_get_value_time (c,
2172 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2173 "CADET", "RATCHET_TIME", "USING DEFAULT");
2174 ratchet_time = GNUNET_TIME_UNIT_HOURS;
2179 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2184 * Shut down the tunnel subsystem.
2189 LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down tunnels\n");
2190 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2191 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2198 * @param destination Peer this tunnel is towards.
2200 struct CadetTunnel *
2201 GCT_new (struct CadetPeer *destination)
2203 struct CadetTunnel *t;
2205 t = GNUNET_new (struct CadetTunnel);
2207 t->peer = destination;
2210 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2211 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2217 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
2219 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2225 * Change the tunnel's connection state.
2227 * @param t Tunnel whose connection state to change.
2228 * @param cstate New connection state.
2231 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2235 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2236 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2237 if (myid != GCP_get_short_id (t->peer) &&
2238 CADET_TUNNEL_READY != t->cstate &&
2239 CADET_TUNNEL_READY == cstate)
2242 if (CADET_TUNNEL_KEY_OK == t->estate)
2244 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2245 send_queued_data (t);
2247 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2249 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered KX\n");
2250 GCT_send_kx (t, GNUNET_NO);
2254 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
2259 if (CADET_TUNNEL_READY == cstate
2260 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2262 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2263 GCP_stop_search (t->peer);
2269 * Change the tunnel encryption state.
2271 * If the encryption state changes to OK, stop the rekey task.
2273 * @param t Tunnel whose encryption state to change, or NULL.
2274 * @param state New encryption state.
2277 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2279 enum CadetTunnelEState old;
2286 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2287 GCP_2s (t->peer), estate2s (old));
2288 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2289 GCP_2s (t->peer), estate2s (t->estate));
2291 if (CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
2293 if (NULL != t->rekey_task)
2295 GNUNET_SCHEDULER_cancel (t->rekey_task);
2296 t->rekey_task = NULL;
2298 /* Send queued data if tunnel is not loopback */
2299 if (myid != GCP_get_short_id (t->peer))
2300 send_queued_data (t);
2306 * @brief Check if tunnel has too many connections, and remove one if necessary.
2308 * Currently this means the newest connection, unless it is a direct one.
2309 * Implemented as a task to avoid freeing a connection that is in the middle
2310 * of being created/processed.
2312 * @param cls Closure (Tunnel to check).
2315 trim_connections (void *cls)
2317 struct CadetTunnel *t = cls;
2319 t->trim_connections_task = NULL;
2320 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2322 struct CadetTConnection *iter;
2323 struct CadetTConnection *c;
2325 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2327 if ((iter->created.abs_value_us > c->created.abs_value_us)
2328 && GNUNET_NO == GCC_is_direct (iter->c))
2335 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2337 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2350 * Add a connection to a tunnel.
2353 * @param c Connection.
2356 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2358 struct CadetTConnection *aux;
2360 GNUNET_assert (NULL != c);
2362 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2363 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2364 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2368 aux = GNUNET_new (struct CadetTConnection);
2370 aux->created = GNUNET_TIME_absolute_get ();
2372 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2374 if (CADET_TUNNEL_SEARCHING == t->cstate)
2375 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2377 if (NULL != t->trim_connections_task)
2378 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
2383 * Remove a connection from a tunnel.
2386 * @param c Connection.
2389 GCT_remove_connection (struct CadetTunnel *t,
2390 struct CadetConnection *c)
2392 struct CadetTConnection *aux;
2393 struct CadetTConnection *next;
2396 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2397 GCC_2s (c), GCT_2s (t));
2398 for (aux = t->connection_head; aux != NULL; aux = next)
2403 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2408 conns = GCT_count_connections (t);
2410 && NULL == t->destroy_task
2411 && CADET_TUNNEL_SHUTDOWN != t->cstate
2412 && GNUNET_NO == shutting_down)
2414 if (0 == GCT_count_any_connections (t))
2415 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2417 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2420 /* Start new connections if needed */
2421 if (CONNECTIONS_PER_TUNNEL > conns
2422 && CADET_TUNNEL_SHUTDOWN != t->cstate
2423 && GNUNET_NO == shutting_down)
2425 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
2426 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
2430 /* If not marked as ready, no change is needed */
2431 if (CADET_TUNNEL_READY != t->cstate)
2434 /* Check if any connection is ready to maintain cstate */
2435 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2436 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2442 * Add a channel to a tunnel.
2445 * @param ch Channel.
2448 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2450 struct CadetTChannel *aux;
2452 GNUNET_assert (NULL != ch);
2454 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2456 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2458 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2463 aux = GNUNET_new (struct CadetTChannel);
2465 LOG (GNUNET_ERROR_TYPE_DEBUG,
2466 " adding %p to %p\n", aux, t->channel_head);
2467 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head,
2471 if (NULL != t->destroy_task)
2473 GNUNET_SCHEDULER_cancel (t->destroy_task);
2474 t->destroy_task = NULL;
2475 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2481 * Remove a channel from a tunnel.
2484 * @param ch Channel.
2487 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2489 struct CadetTChannel *aux;
2491 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2492 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2496 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2497 GNUNET_CONTAINER_DLL_remove (t->channel_head,
2508 * Search for a channel by global ID.
2510 * @param t Tunnel containing the channel.
2511 * @param chid Public channel number.
2513 * @return channel handler, NULL if doesn't exist
2515 struct CadetChannel *
2516 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2518 struct CadetTChannel *iter;
2523 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2525 if (GCCH_get_id (iter->ch) == chid)
2529 return NULL == iter ? NULL : iter->ch;
2534 * @brief Destroy a tunnel and free all resources.
2536 * Should only be called a while after the tunnel has been marked as destroyed,
2537 * in case there is a new channel added to the same peer shortly after marking
2538 * the tunnel. This way we avoid a new public key handshake.
2540 * @param cls Closure (tunnel to destroy).
2543 delayed_destroy (void *cls)
2545 struct CadetTunnel *t = cls;
2546 struct CadetTConnection *iter;
2548 t->destroy_task = NULL;
2549 LOG (GNUNET_ERROR_TYPE_DEBUG,
2550 "delayed destroying tunnel %p\n",
2552 t->cstate = CADET_TUNNEL_SHUTDOWN;
2553 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2555 GCC_send_destroy (iter->c);
2562 * Tunnel is empty: destroy it.
2564 * Notifies all connections about the destruction.
2566 * @param t Tunnel to destroy.
2569 GCT_destroy_empty (struct CadetTunnel *t)
2571 if (GNUNET_YES == shutting_down)
2572 return; /* Will be destroyed immediately anyway */
2574 if (NULL != t->destroy_task)
2576 LOG (GNUNET_ERROR_TYPE_WARNING,
2577 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
2579 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2581 /* should never happen, tunnel can only become empty once, and the
2582 * task identifier should be NO_TASK (cleaned when the tunnel was created
2583 * or became un-empty)
2588 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
2591 // FIXME make delay a config option
2592 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2593 &delayed_destroy, t);
2594 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %p\n",
2595 t, t->destroy_task);
2600 * Destroy tunnel if empty (no more channels).
2602 * @param t Tunnel to destroy if empty.
2605 GCT_destroy_if_empty (struct CadetTunnel *t)
2607 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2608 if (0 < GCT_count_channels (t))
2611 GCT_destroy_empty (t);
2616 * Destroy the tunnel.
2618 * This function does not generate any warning traffic to clients or peers.
2621 * Cancel messages belonging to this tunnel queued to neighbors.
2622 * Free any allocated resources linked to the tunnel.
2624 * @param t The tunnel to destroy.
2627 GCT_destroy (struct CadetTunnel *t)
2629 struct CadetTConnection *iter_c;
2630 struct CadetTConnection *next_c;
2631 struct CadetTChannel *iter_ch;
2632 struct CadetTChannel *next_ch;
2633 unsigned int keepalives_queued;
2638 LOG (GNUNET_ERROR_TYPE_DEBUG,
2639 "destroying tunnel %s\n",
2641 GNUNET_break (GNUNET_YES ==
2642 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2643 GCP_get_id (t->peer), t));
2645 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2647 next_c = iter_c->next;
2648 GCC_destroy (iter_c->c);
2650 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2652 next_ch = iter_ch->next;
2653 GCCH_destroy (iter_ch->ch);
2654 /* Should only happen on shutdown, but it's ok. */
2656 keepalives_queued = 0;
2657 while (NULL != t->tq_head)
2659 /* Should have been cleaned by destuction of channel. */
2660 struct GNUNET_MessageHeader *mh;
2663 mh = (struct GNUNET_MessageHeader *) &t->tq_head[1];
2664 type = ntohs (mh->type);
2665 if (0 == keepalives_queued && GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE == type)
2667 keepalives_queued = 1;
2668 LOG (GNUNET_ERROR_TYPE_DEBUG,
2669 "one keepalive left behind on tunnel shutdown\n");
2671 else if (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY == type)
2673 LOG (GNUNET_ERROR_TYPE_WARNING,
2674 "tunnel destroyed before a CHANNEL_DESTROY was sent to peer\n");
2679 LOG (GNUNET_ERROR_TYPE_ERROR,
2680 "message left behind on tunnel shutdown: %s\n",
2683 unqueue_data (t->tq_head);
2687 if (NULL != t->destroy_task)
2689 LOG (GNUNET_ERROR_TYPE_DEBUG,
2690 "cancelling dest: %p\n",
2692 GNUNET_SCHEDULER_cancel (t->destroy_task);
2693 t->destroy_task = NULL;
2696 if (NULL != t->trim_connections_task)
2698 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %p\n",
2699 t->trim_connections_task);
2700 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
2701 t->trim_connections_task = NULL;
2704 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2705 GCP_set_tunnel (t->peer, NULL);
2707 if (NULL != t->rekey_task)
2709 GNUNET_SCHEDULER_cancel (t->rekey_task);
2710 t->rekey_task = NULL;
2720 * @brief Use the given path for the tunnel.
2721 * Update the next and prev hops (and RCs).
2722 * (Re)start the path refresh in case the tunnel is locally owned.
2724 * @param t Tunnel to update.
2725 * @param p Path to use.
2727 * @return Connection created.
2729 struct CadetConnection *
2730 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *path)
2732 struct CadetConnection *c;
2733 struct GNUNET_CADET_Hash cid;
2734 unsigned int own_pos;
2736 if (NULL == t || NULL == path)
2742 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
2748 for (own_pos = 0; own_pos < path->length; own_pos++)
2750 if (path->peers[own_pos] == myid)
2753 if (own_pos >= path->length)
2755 GNUNET_break_op (0);
2759 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2760 c = GCC_new (&cid, t, path, own_pos);
2763 /* Path was flawed */
2766 GCT_add_connection (t, c);
2772 * Count all created connections of a tunnel. Not necessarily ready connections!
2774 * @param t Tunnel on which to count.
2776 * @return Number of connections created, either being established or ready.
2779 GCT_count_any_connections (struct CadetTunnel *t)
2781 struct CadetTConnection *iter;
2787 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2795 * Count established (ready) connections of a tunnel.
2797 * @param t Tunnel on which to count.
2799 * @return Number of connections.
2802 GCT_count_connections (struct CadetTunnel *t)
2804 struct CadetTConnection *iter;
2810 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2811 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
2819 * Count channels of a tunnel.
2821 * @param t Tunnel on which to count.
2823 * @return Number of channels.
2826 GCT_count_channels (struct CadetTunnel *t)
2828 struct CadetTChannel *iter;
2831 for (count = 0, iter = t->channel_head;
2833 iter = iter->next, count++) /* skip */;
2840 * Get the connectivity state of a tunnel.
2844 * @return Tunnel's connectivity state.
2846 enum CadetTunnelCState
2847 GCT_get_cstate (struct CadetTunnel *t)
2852 return (enum CadetTunnelCState) -1;
2859 * Get the encryption state of a tunnel.
2863 * @return Tunnel's encryption state.
2865 enum CadetTunnelEState
2866 GCT_get_estate (struct CadetTunnel *t)
2871 return (enum CadetTunnelEState) -1;
2877 * Get the maximum buffer space for a tunnel towards a local client.
2881 * @return Biggest buffer space offered by any channel in the tunnel.
2884 GCT_get_channels_buffer (struct CadetTunnel *t)
2886 struct CadetTChannel *iter;
2887 unsigned int buffer;
2888 unsigned int ch_buf;
2890 if (NULL == t->channel_head)
2892 /* Probably getting buffer for a channel create/handshake. */
2893 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
2894 return MIN_TUNNEL_BUFFER;
2898 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2900 ch_buf = get_channel_buffer (iter);
2901 if (ch_buf > buffer)
2904 if (MIN_TUNNEL_BUFFER > buffer)
2905 return MIN_TUNNEL_BUFFER;
2907 if (MAX_TUNNEL_BUFFER < buffer)
2910 return MAX_TUNNEL_BUFFER;
2917 * Get the total buffer space for a tunnel for P2P traffic.
2921 * @return Buffer space offered by all connections in the tunnel.
2924 GCT_get_connections_buffer (struct CadetTunnel *t)
2926 struct CadetTConnection *iter;
2927 unsigned int buffer;
2929 if (GNUNET_NO == is_ready (t))
2931 if (count_queued_data (t) >= 3)
2938 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2940 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2944 buffer += get_connection_buffer (iter);
2952 * Get the tunnel's destination.
2956 * @return ID of the destination peer.
2958 const struct GNUNET_PeerIdentity *
2959 GCT_get_destination (struct CadetTunnel *t)
2961 return GCP_get_id (t->peer);
2966 * Get the tunnel's next free global channel ID.
2970 * @return GID of a channel free to use.
2973 GCT_get_next_chid (struct CadetTunnel *t)
2975 CADET_ChannelNumber chid;
2976 CADET_ChannelNumber mask;
2979 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2980 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2981 * If peer's ID is bigger, start at 0x4... bit 30 = 1
2983 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2988 t->next_chid |= mask;
2990 while (NULL != GCT_get_channel (t, t->next_chid))
2992 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2993 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2994 t->next_chid |= mask;
2996 chid = t->next_chid;
2997 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2998 t->next_chid |= mask;
3005 * Send ACK on one or more channels due to buffer in connections.
3007 * @param t Channel which has some free buffer space.
3010 GCT_unchoke_channels (struct CadetTunnel *t)
3012 struct CadetTChannel *iter;
3013 unsigned int buffer;
3014 unsigned int channels = GCT_count_channels (t);
3015 unsigned int choked_n;
3016 struct CadetChannel *choked[channels];
3018 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3019 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3020 if (NULL != t->channel_head)
3021 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3023 if (NULL != t->tq_head)
3024 send_queued_data (t);
3026 /* Get buffer space */
3027 buffer = GCT_get_connections_buffer (t);
3033 /* Count and remember choked channels */
3035 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3037 if (GNUNET_NO == get_channel_allowed (iter))
3039 choked[choked_n++] = iter->ch;
3043 /* Unchoke random channels */
3044 while (0 < buffer && 0 < choked_n)
3046 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3048 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3051 choked[r] = choked[choked_n];
3057 * Send ACK on one or more connections due to buffer space to the client.
3059 * Iterates all connections of the tunnel and sends ACKs appropriately.
3064 GCT_send_connection_acks (struct CadetTunnel *t)
3066 struct CadetTConnection *iter;
3069 uint32_t allow_per_connection;
3071 unsigned int buffer;
3073 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3082 if (CADET_TUNNEL_READY != t->cstate)
3085 buffer = GCT_get_channels_buffer (t);
3086 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
3088 /* Count connections, how many messages are already allowed */
3089 cs = GCT_count_connections (t);
3090 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3092 allowed += get_connection_allowed (iter);
3094 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
3096 /* Make sure there is no overflow */
3097 if (allowed > buffer)
3100 /* Authorize connections to send more data */
3101 to_allow = buffer - allowed;
3103 for (iter = t->connection_head;
3104 NULL != iter && to_allow > 0;
3107 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3108 || get_connection_allowed (iter) > 64 / 3)
3112 GNUNET_assert(cs != 0);
3113 allow_per_connection = to_allow/cs;
3114 to_allow -= allow_per_connection;
3116 GCC_allow (iter->c, allow_per_connection,
3117 GCC_is_origin (iter->c, GNUNET_NO));
3122 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
3123 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
3129 * Cancel a previously sent message while it's in the queue.
3131 * ONLY can be called before the continuation given to the send function
3132 * is called. Once the continuation is called, the message is no longer in the
3135 * @param q Handle to the queue.
3138 GCT_cancel (struct CadetTunnelQueue *q)
3142 GNUNET_assert (NULL == q->tqd);
3144 /* tun_message_sent() will be called and free q */
3146 else if (NULL != q->tqd)
3148 unqueue_data (q->tqd);
3150 if (NULL != q->cont)
3151 q->cont (q->cont_cls, NULL, q, 0, 0);
3162 * Check if the tunnel has queued traffic.
3164 * @param t Tunnel to check.
3166 * @return #GNUNET_YES if there is queued traffic
3167 * #GNUNET_NO otherwise
3170 GCT_has_queued_traffic (struct CadetTunnel *t)
3172 return (NULL != t->tq_head) ? GNUNET_YES : GNUNET_NO;
3177 * Sends an already built message on a tunnel, encrypting it and
3178 * choosing the best connection if not provided.
3180 * @param message Message to send. Function modifies it.
3181 * @param t Tunnel on which this message is transmitted.
3182 * @param c Connection to use (autoselect if NULL).
3183 * @param force Force the tunnel to take the message (buffer overfill).
3184 * @param cont Continuation to call once message is really sent.
3185 * @param cont_cls Closure for @c cont.
3187 * @return Handle to cancel message. NULL if @c cont is NULL.
3189 struct CadetTunnelQueue *
3190 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3191 struct CadetTunnel *t, struct CadetConnection *c,
3192 int force, GCT_sent cont, void *cont_cls)
3194 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3199 * Send a KX message.
3201 * @param t Tunnel on which to send it.
3202 * @param force_reply Force the other peer to reply with a KX message.
3205 GCT_send_kx (struct CadetTunnel *t, int force_reply)
3207 struct CadetConnection *c;
3208 struct GNUNET_CADET_KX msg;
3209 enum GNUNET_CADET_KX_Flags flags;
3211 LOG (GNUNET_ERROR_TYPE_INFO, "==> { KX} on %s\n", GCT_2s (t));
3212 if (NULL != t->ephm_h)
3214 LOG (GNUNET_ERROR_TYPE_INFO, " already queued, nop\n");
3217 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
3219 c = tunnel_get_connection (t);
3222 if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
3225 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
3230 msg.header.size = htons (sizeof (msg));
3231 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
3232 flags = GNUNET_CADET_KX_FLAG_NONE;
3233 if (GNUNET_YES == force_reply)
3234 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
3235 msg.flags = htonl (flags);
3236 msg.cid = *GCC_get_id (c);
3237 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
3238 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
3240 t->ephm_h = GCC_send_prebuilt_message (&msg.header, UINT16_MAX, 0,
3241 c, GCC_is_origin (c, GNUNET_YES),
3242 GNUNET_YES, &ephm_sent, t);
3243 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3244 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
3249 * Is the tunnel directed towards the local peer?
3253 * @return #GNUNET_YES if it is loopback.
3256 GCT_is_loopback (const struct CadetTunnel *t)
3258 return (myid == GCP_get_short_id (t->peer));
3263 * Is the tunnel this path already?
3268 * @return #GNUNET_YES a connection uses this path.
3271 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3273 struct CadetTConnection *iter;
3275 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3276 if (path_equivalent (GCC_get_path (iter->c), p))
3284 * Get a cost of a path for a tunnel considering existing connections.
3287 * @param path Candidate path.
3289 * @return Cost of the path (path length + number of overlapping nodes)
3292 GCT_get_path_cost (const struct CadetTunnel *t,
3293 const struct CadetPeerPath *path)
3295 struct CadetTConnection *iter;
3296 const struct CadetPeerPath *aux;
3297 unsigned int overlap;
3305 GNUNET_assert (NULL != t);
3307 for (i = 0; i < path->length; i++)
3309 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3311 aux = GCC_get_path (iter->c);
3315 for (j = 0; j < aux->length; j++)
3317 if (path->peers[i] == aux->peers[j])
3325 return path->length + overlap;
3330 * Get the static string for the peer this tunnel is directed.
3334 * @return Static string the destination peer's ID.
3337 GCT_2s (const struct CadetTunnel *t)
3342 return GCP_2s (t->peer);
3346 /******************************************************************************/
3347 /***************************** INFO/DEBUG *******************************/
3348 /******************************************************************************/
3351 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
3353 struct GNUNET_CRYPTO_EcdhePublicKey pub;
3354 struct CadetTunnelSkippedKey *iter;
3356 LOG2 (level, "TTT RK \t %s\n",
3357 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->RK));
3359 LOG2 (level, "TTT HKs \t %s\n",
3360 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKs));
3361 LOG2 (level, "TTT HKr \t %s\n",
3362 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKr));
3363 LOG2 (level, "TTT NHKs\t %s\n",
3364 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->NHKs));
3365 LOG2 (level, "TTT NHKr\t %s\n",
3366 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->NHKr));
3368 LOG2 (level, "TTT CKs \t %s\n",
3369 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKs));
3370 LOG2 (level, "TTT CKr \t %s\n",
3371 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKr));
3373 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
3374 LOG2 (level, "TTT DHRs\t %s\n",
3375 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &pub));
3376 LOG2 (level, "TTT DHRr\t %s\n",
3377 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->DHRr));
3379 LOG2 (level, "TTT Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
3380 LOG2 (level, "TTT PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
3381 LOG2 (level, "TTT Ratchet\t%u\n", ax->ratchet_flag);
3383 for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
3385 LOG2 (level, "TTT HK\t %s\n",
3386 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &iter->HK));
3387 LOG2 (level, "TTT MK\t %s\n",
3388 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &iter->MK));
3393 * Log all possible info about the tunnel state.
3395 * @param t Tunnel to debug.
3396 * @param level Debug level to use.
3399 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3401 struct CadetTChannel *iter_ch;
3402 struct CadetTConnection *iter_c;
3405 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3407 __FILE__, __FUNCTION__, __LINE__);
3411 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3412 LOG2 (level, "TTT cstate %s, estate %s\n",
3413 cstate2s (t->cstate), estate2s (t->estate));
3414 #if DUMP_KEYS_TO_STDERR
3415 ax_debug (t->ax, level);
3417 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3418 LOG2 (level, "TTT destroy %p\n", t->destroy_task);
3419 LOG2 (level, "TTT channels:\n");
3420 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = iter_ch->next)
3422 GCCH_debug (iter_ch->ch, level);
3425 LOG2 (level, "TTT connections:\n");
3426 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
3428 GCC_debug (iter_c->c, level);
3431 LOG2 (level, "TTT DEBUG TUNNEL END\n");
3436 * Iterate all tunnels.
3438 * @param iter Iterator.
3439 * @param cls Closure for @c iter.
3442 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3444 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3449 * Count all tunnels.
3451 * @return Number of tunnels to remote peers kept by this peer.
3454 GCT_count_all (void)
3456 return GNUNET_CONTAINER_multipeermap_size (tunnels);
3461 * Iterate all connections of a tunnel.
3463 * @param t Tunnel whose connections to iterate.
3464 * @param iter Iterator.
3465 * @param cls Closure for @c iter.
3468 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3470 struct CadetTConnection *ct;
3472 for (ct = t->connection_head; NULL != ct; ct = ct->next)
3478 * Iterate all channels of a tunnel.
3480 * @param t Tunnel whose channels to iterate.
3481 * @param iter Iterator.
3482 * @param cls Closure for @c iter.
3485 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3487 struct CadetTChannel *cht;
3489 for (cht = t->channel_head; NULL != cht; cht = cht->next)
3490 iter (cls, cht->ch);