2 This file is part of GNUnet.
3 Copyright (C) 2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 #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 /******************************************************************************/
47 /******************************** STRUCTS **********************************/
48 /******************************************************************************/
52 struct CadetTChannel *next;
53 struct CadetTChannel *prev;
54 struct CadetChannel *ch;
59 * Connection list and metadata.
61 struct CadetTConnection
66 struct CadetTConnection *next;
71 struct CadetTConnection *prev;
76 struct CadetConnection *c;
79 * Creation time, to keep oldest connection alive.
81 struct GNUNET_TIME_Absolute created;
84 * Connection throughput, to keep fastest connection alive.
90 * Structure used during a Key eXchange.
92 struct CadetTunnelKXCtx
95 * Encryption ("our") old "confirmed" key, for encrypting traffic sent by us
96 * end before the key exchange is finished or times out.
98 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
101 * Decryption ("their") old "confirmed" key, for decrypting traffic sent by
102 * the other end before the key exchange started.
104 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
107 * Same as @c e_key_old, for the case of two simultaneous KX.
108 * This can happen if cadet decides to start a re-key while the peer has also
109 * started its re-key (due to network delay this is impossible to avoid).
110 * In this case, the key material generated with the peer's old ephemeral
111 * *might* (but doesn't have to) be incorrect.
112 * Since no more than two re-keys can happen simultaneously, this is enough.
114 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old2;
117 * Same as @c d_key_old, for the case described in @c e_key_old2.
119 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old2;
122 * Challenge to send and expect in the PONG.
127 * When the rekey started. One minute after this the new key will be used.
129 struct GNUNET_TIME_Absolute rekey_start_time;
132 * Task for delayed destruction of the Key eXchange context, to allow delayed
133 * messages with the old key to be decrypted successfully.
135 struct GNUNET_SCHEDULER_Task *finish_task;
139 * Encryption systems possible.
141 enum CadetTunnelEncryption
144 * Default Axolotl system.
149 * Fallback OTR-style encryption.
155 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
157 struct CadetTunnelSkippedKey
162 struct CadetTunnelSkippedKey *next;
167 struct CadetTunnelSkippedKey *prev;
170 * When was this key stored (for timeout).
172 struct GNUNET_TIME_Absolute timestamp;
177 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
182 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
186 * Axolotl data, according to https://github.com/trevp/axolotl/wiki
188 struct CadetTunnelAxolotl
191 * A (double linked) list of stored message keys and associated header keys
192 * for "skipped" messages, i.e. messages that have not bee*n
193 * received despite the reception of more recent messages, (head)/
195 struct CadetTunnelSkippedKey *skipped_head;
198 * Skipped messages' keys DLL, tail.
200 struct CadetTunnelSkippedKey *skipped_tail;
203 * Elements in @a skipped_head <-> @a skipped_tail.
208 * 32-byte root key which gets updated by DH ratchet
210 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
213 * 32-byte header key (send)
215 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
218 * 32-byte header key (recv)
220 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
223 * 32-byte next header key (send)
225 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
228 * 32-byte next header key (recv)
230 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
233 * 32-byte chain keys (used for forward-secrecy updating, send)
235 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
238 * 32-byte chain keys (used for forward-secrecy updating, recv)
240 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
243 * ECDH for key exchange (A0 / B0)
245 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
248 * ECDH Ratchet key (send)
250 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
253 * ECDH Ratchet key (recv)
255 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
258 * Message number (reset to 0 with each new ratchet, send)
263 * Message numbers (reset to 0 with each new ratchet, recv)
268 * Previous message numbers (# of msgs sent under prev ratchet)
273 * True (#GNUNET_YES) if the party will send a new ratchet key in next msg.
279 * Struct containing all information regarding a tunnel to a peer.
284 * Endpoint of the tunnel.
286 struct CadetPeer *peer;
289 * Type of encryption used in the tunnel.
291 enum CadetTunnelEncryption enc_type;
296 struct CadetTunnelAxolotl *ax;
299 * State of the tunnel connectivity.
301 enum CadetTunnelCState cstate;
304 * State of the tunnel encryption.
306 enum CadetTunnelEState estate;
309 * Key eXchange context.
311 struct CadetTunnelKXCtx *kx_ctx;
314 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
317 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
320 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
322 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
325 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
327 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
330 * Task to start the rekey process.
332 struct GNUNET_SCHEDULER_Task * rekey_task;
335 * Paths that are actively used to reach the destination peer.
337 struct CadetTConnection *connection_head;
338 struct CadetTConnection *connection_tail;
341 * Next connection number.
346 * Channels inside this tunnel.
348 struct CadetTChannel *channel_head;
349 struct CadetTChannel *channel_tail;
352 * Channel ID for the next created channel.
354 CADET_ChannelNumber next_chid;
357 * Destroy flag: if true, destroy on last message.
359 struct GNUNET_SCHEDULER_Task * destroy_task;
362 * Queued messages, to transmit once tunnel gets connected.
364 struct CadetTunnelDelayed *tq_head;
365 struct CadetTunnelDelayed *tq_tail;
368 * Task to trim connections if too many are present.
370 struct GNUNET_SCHEDULER_Task * trim_connections_task;
373 * Ephemeral message in the queue (to avoid queueing more than one).
375 struct CadetConnectionQueue *ephm_h;
378 * Pong message in the queue.
380 struct CadetConnectionQueue *pong_h;
385 * Struct used to save messages in a non-ready tunnel to send once connected.
387 struct CadetTunnelDelayed
392 struct CadetTunnelDelayed *next;
393 struct CadetTunnelDelayed *prev;
398 struct CadetTunnel *t;
401 * Tunnel queue given to the channel to cancel request. Update on send_queued.
403 struct CadetTunnelQueue *tq;
408 /* struct GNUNET_MessageHeader *msg; */
413 * Handle for messages queued but not yet sent.
415 struct CadetTunnelQueue
418 * Connection queue handle, to cancel if necessary.
420 struct CadetConnectionQueue *cq;
423 * Handle in case message hasn't been given to a connection yet.
425 struct CadetTunnelDelayed *tqd;
428 * Continuation to call once sent.
433 * Closure for @c cont.
440 * Cached Axolotl key with signature.
442 struct CadetAxolotlSignedKey
445 * Information about what is being signed (@a permanent_key).
447 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
450 * Permanent public ECDH key.
452 struct GNUNET_CRYPTO_EcdhePublicKey permanent_key;
455 * An EdDSA signature of the permanent ECDH key with the Peer's ID key.
457 struct GNUNET_CRYPTO_EddsaSignature signature;
461 /******************************************************************************/
462 /******************************* GLOBALS ***********************************/
463 /******************************************************************************/
466 * Global handle to the statistics service.
468 extern struct GNUNET_STATISTICS_Handle *stats;
471 * Local peer own ID (memory efficient handle).
473 extern GNUNET_PEER_Id myid;
476 * Local peer own ID (full value).
478 extern struct GNUNET_PeerIdentity my_full_id;
482 * Don't try to recover tunnels if shutting down.
484 extern int shutting_down;
488 * Set of all tunnels, in order to trigger a new exchange on rekey.
489 * Indexed by peer's ID.
491 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
494 * Default TTL for payload packets.
496 static unsigned long long default_ttl;
500 * Own Peer ID private key.
502 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
504 /******************************** AXOLOTL ************************************/
506 static struct GNUNET_CRYPTO_EcdhePrivateKey *ax_key;
509 * Own Axolotl permanent public key (cache).
511 static struct CadetAxolotlSignedKey ax_identity;
513 /******************************** OTR ***********************************/
517 * Own global OTR ephemeral private key.
519 static struct GNUNET_CRYPTO_EcdhePrivateKey *otr_ephemeral_key;
522 * Cached message used to perform a OTR key exchange.
524 static struct GNUNET_CADET_KX_Ephemeral otr_kx_msg;
527 * Task to generate a new OTR ephemeral key.
529 static struct GNUNET_SCHEDULER_Task *rekey_task;
534 static struct GNUNET_TIME_Relative rekey_period;
537 /******************************************************************************/
538 /******************************** STATIC ***********************************/
539 /******************************************************************************/
542 * Get string description for tunnel connectivity state.
544 * @param cs Tunnel state.
546 * @return String representation.
549 cstate2s (enum CadetTunnelCState cs)
555 case CADET_TUNNEL_NEW:
556 return "CADET_TUNNEL_NEW";
557 case CADET_TUNNEL_SEARCHING:
558 return "CADET_TUNNEL_SEARCHING";
559 case CADET_TUNNEL_WAITING:
560 return "CADET_TUNNEL_WAITING";
561 case CADET_TUNNEL_READY:
562 return "CADET_TUNNEL_READY";
563 case CADET_TUNNEL_SHUTDOWN:
564 return "CADET_TUNNEL_SHUTDOWN";
566 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
574 * Get string description for tunnel encryption state.
576 * @param es Tunnel state.
578 * @return String representation.
581 estate2s (enum CadetTunnelEState es)
587 case CADET_TUNNEL_KEY_UNINITIALIZED:
588 return "CADET_TUNNEL_KEY_UNINITIALIZED";
589 case CADET_TUNNEL_KEY_SENT:
590 return "CADET_TUNNEL_KEY_SENT";
591 case CADET_TUNNEL_KEY_PING:
592 return "CADET_TUNNEL_KEY_PING";
593 case CADET_TUNNEL_KEY_OK:
594 return "CADET_TUNNEL_KEY_OK";
595 case CADET_TUNNEL_KEY_REKEY:
596 return "CADET_TUNNEL_KEY_REKEY";
598 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
606 * @brief Check if tunnel is ready to send traffic.
608 * Tunnel must be connected and with encryption correctly set up.
610 * @param t Tunnel to check.
612 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
615 is_ready (struct CadetTunnel *t)
619 GCT_debug (t, GNUNET_ERROR_TYPE_DEBUG);
620 ready = CADET_TUNNEL_READY == t->cstate
621 && (CADET_TUNNEL_KEY_OK == t->estate
622 || CADET_TUNNEL_KEY_REKEY == t->estate);
623 ready = ready || GCT_is_loopback (t);
629 * Check if a key is invalid (NULL pointer or all 0)
631 * @param key Key to check.
633 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
636 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
638 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
643 memset (&null_key, 0, sizeof (null_key));
644 if (0 == memcmp (key, &null_key, sizeof (null_key)))
651 * Ephemeral key message purpose size.
653 * @return Size of the part of the ephemeral key message that must be signed.
656 ephemeral_purpose_size (void)
658 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
659 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
660 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
661 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
662 sizeof (struct GNUNET_PeerIdentity);
667 * Ephemeral key message purpose size.
669 * @return Size of the part of the ephemeral key message that must be signed.
672 ax_purpose_size (void)
674 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
675 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
680 * Size of the encrypted part of a ping message.
682 * @return Size of the encrypted part of a ping message.
685 ping_encryption_size (void)
687 return sizeof (uint32_t);
692 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
694 * @param tch Tunnel's channel handle.
696 * @return Amount of messages the channel can still buffer towards the client.
699 get_channel_buffer (const struct CadetTChannel *tch)
703 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
704 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
706 return GCCH_get_buffer (tch->ch, fwd);
711 * Get the channel's allowance status.
713 * @param tch Tunnel's channel handle.
715 * @return #GNUNET_YES if we allowed the client to send data to us.
718 get_channel_allowed (const struct CadetTChannel *tch)
722 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
723 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
725 return GCCH_get_allowed (tch->ch, fwd);
730 * Get the connection's buffer.
732 * @param tc Tunnel's connection handle.
734 * @return Amount of messages the connection can still buffer.
737 get_connection_buffer (const struct CadetTConnection *tc)
741 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
742 fwd = GCC_is_origin (tc->c, GNUNET_YES);
744 return GCC_get_buffer (tc->c, fwd);
749 * Get the connection's allowance.
751 * @param tc Tunnel's connection handle.
753 * @return Amount of messages we have allowed the next peer to send us.
756 get_connection_allowed (const struct CadetTConnection *tc)
760 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
761 fwd = GCC_is_origin (tc->c, GNUNET_YES);
763 return GCC_get_allowed (tc->c, fwd);
768 * Check that a ephemeral key message s well formed and correctly signed.
770 * @param t Tunnel on which the message came.
771 * @param msg The ephemeral key message.
773 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
776 check_ephemeral (struct CadetTunnel *t,
777 const struct GNUNET_CADET_KX_Ephemeral *msg)
779 /* Check message size */
780 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
781 return GNUNET_SYSERR;
783 /* Check signature size */
784 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
785 return GNUNET_SYSERR;
788 if (0 != memcmp (&msg->origin_identity,
789 GCP_get_id (t->peer),
790 sizeof (struct GNUNET_PeerIdentity)))
791 return GNUNET_SYSERR;
793 /* Check signature */
795 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
798 &msg->origin_identity.public_key))
799 return GNUNET_SYSERR;
806 * Select the best key to use for encryption (send), based on KX status.
808 * Normally, return the current key. If there is a KX in progress and the old
809 * key is fresh enough, return the old key.
811 * @param t Tunnel to choose the key from.
813 * @return The optimal key to encrypt/hmac outgoing traffic.
815 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
816 select_key (const struct CadetTunnel *t)
818 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
820 if (NULL != t->kx_ctx
821 && NULL == t->kx_ctx->finish_task)
823 struct GNUNET_TIME_Relative age;
825 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
826 LOG (GNUNET_ERROR_TYPE_DEBUG,
827 " key exchange in progress, started %s ago\n",
828 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
829 // FIXME make duration of old keys configurable
830 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
832 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
833 key = &t->kx_ctx->e_key_old;
837 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
843 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
853 * @param plaintext Content to HMAC.
854 * @param size Size of @c plaintext.
855 * @param iv Initialization vector for the message.
856 * @param key Key to use.
857 * @param hmac[out] Destination to store the HMAC.
860 t_hmac (const void *plaintext, size_t size,
861 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
862 struct GNUNET_CADET_Hash *hmac)
864 static const char ctx[] = "cadet authentication key";
865 struct GNUNET_CRYPTO_AuthKey auth_key;
866 struct GNUNET_HashCode hash;
868 #if DUMP_KEYS_TO_STDERR
869 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC with key %s\n",
870 GNUNET_h2s ((struct GNUNET_HashCode *) key));
872 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
877 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
878 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
879 memcpy (hmac, &hash, sizeof (*hmac));
884 * Encrypt daforce_newest_keyta with the tunnel key.
886 * @param t Tunnel whose key to use.
887 * @param dst Destination for the encrypted data.
888 * @param src Source of the plaintext. Can overlap with @c dst.
889 * @param size Size of the plaintext.
890 * @param iv Initialization Vector to use.
891 * @param force_newest_key Force the use of the newest key, otherwise
892 * CADET will use the old key when allowed.
893 * This can happen in the case when a KX is going on
894 * and the old one hasn't expired.
897 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
898 size_t size, uint32_t iv, int force_newest_key)
900 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
901 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
904 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
906 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
907 #if DUMP_KEYS_TO_STDERR
908 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
909 GNUNET_h2s ((struct GNUNET_HashCode *) key));
911 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
912 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
913 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
914 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
923 * @param key Key to use.
924 * @param hash[out] Resulting HMAC.
925 * @param source Source key material (data to HMAC).
926 * @param len Length of @a source.
929 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
930 struct GNUNET_HashCode *hash,
931 void *source, unsigned int len)
933 static const char ctx[] = "axolotl HMAC-HASH";
934 struct GNUNET_CRYPTO_AuthKey auth_key;
936 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
939 GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
944 * Derive a key from a HMAC-HASH.
946 * @param key Key to use for the HMAC.
947 * @param out Key to generate.
948 * @param source Source key material (data to HMAC).
949 * @param len Length of @a source.
952 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
953 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
954 void *source, unsigned int len)
956 static const char ctx[] = "axolotl derive key";
957 struct GNUNET_HashCode h;
959 t_ax_hmac_hash (key, &h, source, len);
960 GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
961 &h, sizeof (h), NULL);
966 * Encrypt data with the tunnel key.
968 * @param t Tunnel whose key to use.
969 * @param dst Destination for the encrypted data.
970 * @param src Source of the plaintext. Can overlap with @c dst.
971 * @param size Size of the plaintext.
973 * @return Size of the encrypted data.
976 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
978 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
979 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
980 struct CadetTunnelAxolotl *ax;
983 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
987 if (GNUNET_YES == ax->ratchet_flag)
989 /* Advance ratchet */
990 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
991 struct GNUNET_HashCode dh;
992 struct GNUNET_HashCode hmac;
993 static const char ctx[] = "axolotl ratchet";
995 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
998 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
999 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
1000 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1001 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1002 &hmac, sizeof (hmac), NULL);
1009 ax->ratchet_flag = GNUNET_NO;
1012 t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
1013 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1015 #if DUMP_KEYS_TO_STDERR
1016 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
1017 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1020 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
1022 t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
1024 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1031 * Decrypt and verify data with the appropriate tunnel key.
1033 * @param key Key to use.
1034 * @param dst Destination for the plaintext.
1035 * @param src Source of the encrypted data. Can overlap with @c dst.
1036 * @param size Size of the encrypted data.
1037 * @param iv Initialization Vector to use.
1039 * @return Size of the decrypted data, -1 if an error was encountered.
1042 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1043 void *dst, const void *src, size_t size, uint32_t iv)
1045 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
1048 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
1049 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
1050 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
1051 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
1052 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
1053 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
1060 * Decrypt and verify data with the most recent tunnel key.
1062 * @param t Tunnel whose key to use.
1063 * @param dst Destination for the plaintext.
1064 * @param src Source of the encrypted data. Can overlap with @c dst.
1065 * @param size Size of the encrypted data.
1066 * @param iv Initialization Vector to use.
1068 * @return Size of the decrypted data, -1 if an error was encountered.
1071 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
1072 size_t size, uint32_t iv)
1076 #if DUMP_KEYS_TO_STDERR
1077 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
1078 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1080 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1082 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
1083 LOG (GNUNET_ERROR_TYPE_WARNING,
1084 "got data on %s without a valid key\n",
1086 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1090 out_size = decrypt (&t->d_key, dst, src, size, iv);
1097 * Decrypt and verify data with the appropriate tunnel key and verify that the
1098 * data has not been altered since it was sent by the remote peer.
1100 * @param t Tunnel whose key to use.
1101 * @param dst Destination for the plaintext.
1102 * @param src Source of the encrypted data. Can overlap with @c dst.
1103 * @param size Size of the encrypted data.
1104 * @param iv Initialization Vector to use.
1105 * @param msg_hmac HMAC of the message, cannot be NULL.
1107 * @return Size of the decrypted data, -1 if an error was encountered.
1110 t_decrypt_and_validate (struct CadetTunnel *t,
1111 void *dst, const void *src,
1112 size_t size, uint32_t iv,
1113 const struct GNUNET_CADET_Hash *msg_hmac)
1115 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1116 struct GNUNET_CADET_Hash hmac;
1119 /* Try primary (newest) key */
1121 decrypted_size = decrypt (key, dst, src, size, iv);
1122 t_hmac (src, size, iv, key, &hmac);
1123 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1124 return decrypted_size;
1126 /* If no key exchange is going on, we just failed. */
1127 if (NULL == t->kx_ctx)
1129 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1130 "Failed checksum validation on tunnel %s with no KX\n",
1132 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1136 /* Try secondary key, from previous KX period. */
1137 key = &t->kx_ctx->d_key_old;
1138 decrypted_size = decrypt (key, dst, src, size, iv);
1139 t_hmac (src, size, iv, key, &hmac);
1140 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1141 return decrypted_size;
1143 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1144 key = &t->kx_ctx->d_key_old2;
1145 decrypted_size = decrypt (key, dst, src, size, iv);
1146 t_hmac (src, size, iv, key, &hmac);
1147 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1148 return decrypted_size;
1150 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1151 "Failed checksum validation on tunnel %s with KX\n",
1153 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1158 * Decrypt and verify data with the appropriate tunnel key and verify that the
1159 * data has not been altered since it was sent by the remote peer.
1161 * @param t Tunnel whose key to use.
1162 * @param dst Destination for the plaintext.
1163 * @param src Source of the encrypted data. Can overlap with @c dst.
1164 * @param size Size of the encrypted data.
1165 * @param msg_hmac HMAC of the message, cannot be NULL.
1167 * @return Size of the decrypted data, -1 if an error was encountered.
1170 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1171 void *dst, const void *src, size_t size,
1172 const struct GNUNET_CADET_Hash *msg_hmac)
1174 struct CadetTunnelAxolotl *ax;
1189 * Create key material by doing ECDH on the local and remote ephemeral keys.
1191 * @param key_material Where to store the key material.
1192 * @param ephemeral_key Peer's public ephemeral key.
1195 derive_key_material (struct GNUNET_HashCode *key_material,
1196 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
1199 GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key,
1209 * Create a symmetic key from the identities of both ends and the key material
1212 * @param key Destination for the generated key.
1213 * @param sender ID of the peer that will encrypt with @c key.
1214 * @param receiver ID of the peer that will decrypt with @c key.
1215 * @param key_material Hash created with ECDH with the ephemeral keys.
1218 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1219 const struct GNUNET_PeerIdentity *sender,
1220 const struct GNUNET_PeerIdentity *receiver,
1221 const struct GNUNET_HashCode *key_material)
1223 const char salt[] = "CADET kx salt";
1225 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1226 salt, sizeof (salt),
1227 key_material, sizeof (struct GNUNET_HashCode),
1228 sender, sizeof (struct GNUNET_PeerIdentity),
1229 receiver, sizeof (struct GNUNET_PeerIdentity),
1235 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1237 * @param t Tunnel for which to create the keys.
1240 create_keys (struct CadetTunnel *t)
1242 struct GNUNET_HashCode km;
1244 derive_key_material (&km, &t->peers_ephemeral_key);
1245 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1246 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1247 #if DUMP_KEYS_TO_STDERR
1248 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1249 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
1250 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1251 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1252 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1253 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1254 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1255 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1256 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1262 * Create a new Key eXchange context for the tunnel.
1264 * If the old keys were verified, keep them for old traffic. Create a new KX
1265 * timestamp and a new nonce.
1267 * @param t Tunnel for which to create the KX ctx.
1270 create_kx_ctx (struct CadetTunnel *t)
1272 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1274 if (NULL != t->kx_ctx)
1276 if (NULL != t->kx_ctx->finish_task)
1278 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1279 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1280 t->kx_ctx->finish_task = NULL;
1285 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1286 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1290 if (CADET_TUNNEL_KEY_OK == t->estate)
1292 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1293 t->kx_ctx->d_key_old = t->d_key;
1294 t->kx_ctx->e_key_old = t->e_key;
1297 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1298 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1304 * @brief Finish the Key eXchange and destroy the old keys.
1306 * @param cls Closure (Tunnel for which to finish the KX).
1307 * @param tc Task context.
1310 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1312 struct CadetTunnel *t = cls;
1314 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1316 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1318 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1322 GNUNET_free (t->kx_ctx);
1328 * Destroy a Key eXchange context for the tunnel. This function only schedules
1329 * the destruction, the freeing of the memory (and clearing of old key material)
1330 * happens after a delay!
1332 * @param t Tunnel whose KX ctx to destroy.
1335 destroy_kx_ctx (struct CadetTunnel *t)
1337 struct GNUNET_TIME_Relative delay;
1339 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1342 if (is_key_null (&t->kx_ctx->e_key_old))
1344 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1348 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1349 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1351 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1357 * Pick a connection on which send the next data message.
1359 * @param t Tunnel on which to send the message.
1361 * @return The connection on which to send the next message.
1363 static struct CadetConnection *
1364 tunnel_get_connection (struct CadetTunnel *t)
1366 struct CadetTConnection *iter;
1367 struct CadetConnection *best;
1369 unsigned int lowest_q;
1371 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1373 lowest_q = UINT_MAX;
1374 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1376 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1377 GCC_2s (iter->c), GCC_get_state (iter->c));
1378 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1380 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1381 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1389 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1395 * Callback called when a queued message is sent.
1397 * Calculates the average time and connection packet tracking.
1399 * @param cls Closure (TunnelQueue handle).
1400 * @param c Connection this message was on.
1401 * @param q Connection queue handle (unused).
1402 * @param type Type of message sent.
1403 * @param fwd Was this a FWD going message?
1404 * @param size Size of the message.
1407 tun_message_sent (void *cls,
1408 struct CadetConnection *c,
1409 struct CadetConnectionQueue *q,
1410 uint16_t type, int fwd, size_t size)
1412 struct CadetTunnelQueue *qt = cls;
1413 struct CadetTunnel *t;
1415 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1417 GNUNET_assert (NULL != qt->cont);
1418 t = NULL == c ? NULL : GCC_get_tunnel (c);
1419 qt->cont (qt->cont_cls, t, qt, type, size);
1425 count_queued_data (const struct CadetTunnel *t)
1427 struct CadetTunnelDelayed *iter;
1430 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1437 * Delete a queued message: either was sent or the channel was destroyed
1438 * before the tunnel's key exchange had a chance to finish.
1440 * @param tqd Delayed queue handle.
1443 unqueue_data (struct CadetTunnelDelayed *tqd)
1445 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1451 * Cache a message to be sent once tunnel is online.
1453 * @param t Tunnel to hold the message.
1454 * @param msg Message itself (copy will be made).
1456 static struct CadetTunnelDelayed *
1457 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1459 struct CadetTunnelDelayed *tqd;
1460 uint16_t size = ntohs (msg->size);
1462 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1464 if (GNUNET_YES == is_ready (t))
1470 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1473 memcpy (&tqd[1], msg, size);
1474 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1480 * Sends an already built message on a tunnel, encrypting it and
1481 * choosing the best connection.
1483 * @param message Message to send. Function modifies it.
1484 * @param t Tunnel on which this message is transmitted.
1485 * @param c Connection to use (autoselect if NULL).
1486 * @param force Force the tunnel to take the message (buffer overfill).
1487 * @param cont Continuation to call once message is really sent.
1488 * @param cont_cls Closure for @c cont.
1489 * @param existing_q In case this a transmission of previously queued data,
1490 * this should be TunnelQueue given to the client.
1493 * @return Handle to cancel message.
1494 * NULL if @c cont is NULL or an error happens and message is dropped.
1496 static struct CadetTunnelQueue *
1497 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1498 struct CadetTunnel *t, struct CadetConnection *c,
1499 int force, GCT_sent cont, void *cont_cls,
1500 struct CadetTunnelQueue *existing_q)
1502 struct CadetTunnelQueue *tq;
1503 struct GNUNET_CADET_Encrypted *msg;
1504 size_t size = ntohs (message->size);
1505 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
1512 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1514 if (GNUNET_NO == is_ready (t))
1516 struct CadetTunnelDelayed *tqd;
1517 /* A non null existing_q indicates sending of queued data.
1518 * Should only happen after tunnel becomes ready.
1520 GNUNET_assert (NULL == existing_q);
1521 tqd = queue_data (t, message);
1524 tq = GNUNET_new (struct CadetTunnelQueue);
1528 tq->cont_cls = cont_cls;
1532 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1534 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1535 msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1536 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1539 if (CADET_Axolotl == t->enc_type)
1540 esize = t_ax_encrypt (t, &msg[1], message, size);
1542 esize = t_encrypt (t, &msg[1], message, size, iv, GNUNET_NO);
1543 GNUNET_assert (esize == size);
1544 t_hmac (&msg[1], size, iv, select_key (t), &msg->hmac);
1545 msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1548 c = tunnel_get_connection (t);
1551 /* Why is tunnel 'ready'? Should have been queued! */
1552 if (NULL != t->destroy_task)
1555 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1557 return NULL; /* Drop... */
1561 type = ntohs (message->type);
1564 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1565 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1566 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1567 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1569 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1571 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1572 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1573 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1574 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1575 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1576 msg->cid = *GCC_get_id (c);
1577 msg->ttl = htonl (default_ttl);
1581 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1583 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1585 fwd = GCC_is_origin (c, GNUNET_YES);
1589 GNUNET_break (NULL == GCC_send_prebuilt_message (&msg->header, type, mid, c,
1590 fwd, force, NULL, NULL));
1593 if (NULL == existing_q)
1595 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1602 tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
1603 &tun_message_sent, tq);
1604 GNUNET_assert (NULL != tq->cq);
1606 tq->cont_cls = cont_cls;
1613 * Send all cached messages that we can, tunnel is online.
1615 * @param t Tunnel that holds the messages. Cannot be loopback.
1618 send_queued_data (struct CadetTunnel *t)
1620 struct CadetTunnelDelayed *tqd;
1621 struct CadetTunnelDelayed *next;
1624 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1626 if (GCT_is_loopback (t))
1632 if (GNUNET_NO == is_ready (t))
1634 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1635 estate2s (t->estate), cstate2s (t->cstate));
1639 room = GCT_get_connections_buffer (t);
1640 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1641 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1642 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1644 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1647 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1648 tqd->t, NULL, GNUNET_YES,
1649 NULL != tqd->tq ? tqd->tq->cont : NULL,
1650 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1654 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1659 * Callback called when a queued message is sent.
1661 * @param cls Closure.
1662 * @param c Connection this message was on.
1663 * @param type Type of message sent.
1664 * @param fwd Was this a FWD going message?
1665 * @param size Size of the message.
1668 ephm_sent (void *cls,
1669 struct CadetConnection *c,
1670 struct CadetConnectionQueue *q,
1671 uint16_t type, int fwd, size_t size)
1673 struct CadetTunnel *t = cls;
1674 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
1679 * Callback called when a queued message is sent.
1681 * @param cls Closure.
1682 * @param c Connection this message was on.
1683 * @param type Type of message sent.
1684 * @param fwd Was this a FWD going message?
1685 * @param size Size of the message.
1688 pong_sent (void *cls,
1689 struct CadetConnection *c,
1690 struct CadetConnectionQueue *q,
1691 uint16_t type, int fwd, size_t size)
1693 struct CadetTunnel *t = cls;
1694 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
1700 * Sends key exchange message on a tunnel, choosing the best connection.
1701 * Should not be called on loopback tunnels.
1703 * @param t Tunnel on which this message is transmitted.
1704 * @param message Message to send. Function modifies it.
1706 * @return Handle to the message in the connection queue.
1708 static struct CadetConnectionQueue *
1709 send_kx (struct CadetTunnel *t,
1710 const struct GNUNET_MessageHeader *message)
1712 struct CadetConnection *c;
1713 struct GNUNET_CADET_KX *msg;
1714 size_t size = ntohs (message->size);
1715 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1720 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1722 /* Avoid loopback. */
1723 if (GCT_is_loopback (t))
1728 type = ntohs (message->type);
1730 /* Even if tunnel is "being destroyed", send anyway.
1731 * Could be a response to a rekey initiated by remote peer,
1732 * who is trying to create a new channel!
1735 /* Must have a connection, or be looking for one. */
1736 if (NULL == t->connection_head)
1738 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
1739 if (CADET_TUNNEL_SEARCHING != t->cstate)
1742 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1743 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
1748 msg = (struct GNUNET_CADET_KX *) cbuf;
1749 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1750 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1751 c = tunnel_get_connection (t);
1754 if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
1757 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1763 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1764 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
1765 GNUNET_assert (NULL == t->ephm_h);
1768 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1769 GNUNET_assert (NULL == t->pong_h);
1774 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
1777 memcpy (&msg[1], message, size);
1779 fwd = GCC_is_origin (c, GNUNET_YES);
1781 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
1788 * Send the ephemeral key on a tunnel.
1790 * @param t Tunnel on which to send the key.
1793 send_ephemeral (struct CadetTunnel *t)
1795 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1796 if (NULL != t->ephm_h)
1798 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1802 otr_kx_msg.sender_status = htonl (t->estate);
1803 otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1804 otr_kx_msg.nonce = t->kx_ctx->challenge;
1805 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", otr_kx_msg.nonce);
1806 t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
1807 ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
1808 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", otr_kx_msg.nonce);
1809 t->ephm_h = send_kx (t, &otr_kx_msg.header);
1814 * Send a pong message on a tunnel.
1816 * @param t Tunnel on which to send the pong.
1817 * @param challenge Value sent in the ping that we have to send back.
1820 send_pong (struct CadetTunnel *t, uint32_t challenge)
1822 struct GNUNET_CADET_KX_Pong msg;
1824 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1825 if (NULL != t->pong_h)
1827 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1830 msg.header.size = htons (sizeof (msg));
1831 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1832 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1833 msg.nonce = challenge;
1834 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1835 t_encrypt (t, &msg.nonce, &msg.nonce,
1836 sizeof (msg.nonce), msg.iv, GNUNET_YES);
1837 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1839 t->pong_h = send_kx (t, &msg.header);
1844 * Initiate a rekey with the remote peer.
1846 * @param cls Closure (tunnel).
1847 * @param tc TaskContext.
1850 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1852 struct CadetTunnel *t = cls;
1854 t->rekey_task = NULL;
1856 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1857 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1860 GNUNET_assert (NULL != t->kx_ctx);
1861 struct GNUNET_TIME_Relative duration;
1863 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1864 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1865 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1867 // FIXME make duration of old keys configurable
1868 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1870 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
1871 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1872 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1879 case CADET_TUNNEL_KEY_UNINITIALIZED:
1880 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
1883 case CADET_TUNNEL_KEY_SENT:
1886 case CADET_TUNNEL_KEY_OK:
1888 * - state should have changed during rekey_iterator
1889 * - task should have been canceled at pong_handle
1892 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1895 case CADET_TUNNEL_KEY_PING:
1896 case CADET_TUNNEL_KEY_REKEY:
1900 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1903 // FIXME exponential backoff
1904 struct GNUNET_TIME_Relative delay;
1906 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1907 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1908 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1909 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1910 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1915 * Our ephemeral key has changed, create new session key on all tunnels.
1917 * Each tunnel will start the Key Exchange with a random delay between
1918 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1919 * per second, on average.
1921 * @param cls Closure (size of the hashmap).
1922 * @param key Current public key.
1923 * @param value Value in the hash map (tunnel).
1925 * @return #GNUNET_YES, so we should continue to iterate,
1928 rekey_iterator (void *cls,
1929 const struct GNUNET_PeerIdentity *key,
1932 struct CadetTunnel *t = value;
1933 struct GNUNET_TIME_Relative delay;
1934 long n = (long) cls;
1937 if (NULL != t->rekey_task)
1940 if (GNUNET_YES == GCT_is_loopback (t))
1943 if (CADET_OTR != t->enc_type)
1946 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1947 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1948 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1950 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1957 * Create a new ephemeral key and key message, schedule next rekeying.
1959 * @param cls Closure (unused).
1960 * @param tc TaskContext.
1963 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1965 struct GNUNET_TIME_Absolute time;
1970 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1973 GNUNET_free_non_null (otr_ephemeral_key);
1974 otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1976 time = GNUNET_TIME_absolute_get ();
1977 otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1978 time = GNUNET_TIME_absolute_add (time, rekey_period);
1979 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1980 otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1981 GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
1982 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
1983 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
1985 GNUNET_assert (GNUNET_OK ==
1986 GNUNET_CRYPTO_eddsa_sign (id_key,
1987 &otr_kx_msg.purpose,
1988 &otr_kx_msg.signature));
1990 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1991 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1993 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
1994 &global_otr_rekey, NULL);
1999 * Called only on shutdown, destroy every tunnel.
2001 * @param cls Closure (unused).
2002 * @param key Current public key.
2003 * @param value Value in the hash map (tunnel).
2005 * @return #GNUNET_YES, so we should continue to iterate,
2008 destroy_iterator (void *cls,
2009 const struct GNUNET_PeerIdentity *key,
2012 struct CadetTunnel *t = value;
2014 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2021 * Notify remote peer that we don't know a channel he is talking about,
2022 * probably CHANNEL_DESTROY was missed.
2024 * @param t Tunnel on which to notify.
2025 * @param gid ID of the channel.
2028 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2030 struct GNUNET_CADET_ChannelManage msg;
2032 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2033 msg.header.size = htons (sizeof (msg));
2034 msg.chid = htonl (gid);
2036 LOG (GNUNET_ERROR_TYPE_DEBUG,
2037 "WARNING destroying unknown channel %u on tunnel %s\n",
2039 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2044 * Demultiplex data per channel and call appropriate channel handler.
2046 * @param t Tunnel on which the data came.
2047 * @param msg Data message.
2048 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2049 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2050 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2051 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2054 handle_data (struct CadetTunnel *t,
2055 const struct GNUNET_CADET_Data *msg,
2058 struct CadetChannel *ch;
2062 size = ntohs (msg->header.size);
2064 sizeof (struct GNUNET_CADET_Data) +
2065 sizeof (struct GNUNET_MessageHeader))
2070 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2071 GC_m2s (ntohs (msg[1].header.type)));
2074 ch = GCT_get_channel (t, ntohl (msg->chid));
2077 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2079 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2081 send_channel_destroy (t, ntohl (msg->chid));
2085 GCCH_handle_data (ch, msg, fwd);
2090 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2092 * @param t Tunnel on which the DATA ACK came.
2093 * @param msg DATA ACK message.
2094 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2095 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2096 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2097 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2100 handle_data_ack (struct CadetTunnel *t,
2101 const struct GNUNET_CADET_DataACK *msg,
2104 struct CadetChannel *ch;
2108 size = ntohs (msg->header.size);
2109 if (size != sizeof (struct GNUNET_CADET_DataACK))
2116 ch = GCT_get_channel (t, ntohl (msg->chid));
2119 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2121 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2126 GCCH_handle_data_ack (ch, msg, fwd);
2131 * Handle channel create.
2133 * @param t Tunnel on which the data came.
2134 * @param msg Data message.
2137 handle_ch_create (struct CadetTunnel *t,
2138 const struct GNUNET_CADET_ChannelCreate *msg)
2140 struct CadetChannel *ch;
2144 size = ntohs (msg->header.size);
2145 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2152 ch = GCT_get_channel (t, ntohl (msg->chid));
2153 if (NULL != ch && ! GCT_is_loopback (t))
2155 /* Probably a retransmission, safe to ignore */
2156 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2158 ch = GCCH_handle_create (t, msg);
2160 GCT_add_channel (t, ch);
2166 * Handle channel NACK: check correctness and call channel handler for NACKs.
2168 * @param t Tunnel on which the NACK came.
2169 * @param msg NACK message.
2172 handle_ch_nack (struct CadetTunnel *t,
2173 const struct GNUNET_CADET_ChannelManage *msg)
2175 struct CadetChannel *ch;
2179 size = ntohs (msg->header.size);
2180 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2187 ch = GCT_get_channel (t, ntohl (msg->chid));
2190 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2192 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2197 GCCH_handle_nack (ch);
2202 * Handle a CHANNEL ACK (SYNACK/ACK).
2204 * @param t Tunnel on which the CHANNEL ACK came.
2205 * @param msg CHANNEL ACK message.
2206 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2207 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2208 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2209 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2212 handle_ch_ack (struct CadetTunnel *t,
2213 const struct GNUNET_CADET_ChannelManage *msg,
2216 struct CadetChannel *ch;
2220 size = ntohs (msg->header.size);
2221 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2228 ch = GCT_get_channel (t, ntohl (msg->chid));
2231 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2233 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2238 GCCH_handle_ack (ch, msg, fwd);
2243 * Handle a channel destruction message.
2245 * @param t Tunnel on which the message came.
2246 * @param msg Channel destroy message.
2247 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2248 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2249 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2250 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2253 handle_ch_destroy (struct CadetTunnel *t,
2254 const struct GNUNET_CADET_ChannelManage *msg,
2257 struct CadetChannel *ch;
2261 size = ntohs (msg->header.size);
2262 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2269 ch = GCT_get_channel (t, ntohl (msg->chid));
2272 /* Probably a retransmission, safe to ignore */
2276 GCCH_handle_destroy (ch, msg, fwd);
2281 * Create a new Axolotl ephemeral (ratchet) key.
2286 new_ephemeral (struct CadetTunnel *t)
2288 GNUNET_free_non_null (t->ax->DHRs);
2289 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2294 * Free Axolotl data.
2299 destroy_ax (struct CadetTunnel *t)
2304 GNUNET_free_non_null (t->ax->DHRs);
2305 GNUNET_free_non_null (t->ax->kx_0);
2307 GNUNET_free (t->ax);
2314 * The peer's ephemeral key has changed: update the symmetrical keys.
2316 * @param t Tunnel this message came on.
2317 * @param msg Key eXchange message.
2320 handle_ephemeral (struct CadetTunnel *t,
2321 const struct GNUNET_CADET_KX_Ephemeral *msg)
2323 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2325 if (GNUNET_OK != check_ephemeral (t, msg))
2327 GNUNET_break_op (0);
2331 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2335 t->enc_type = CADET_OTR;
2336 if (NULL != t->rekey_task)
2337 GNUNET_SCHEDULER_cancel (t->rekey_task);
2339 rekey_tunnel (t, NULL);
2343 * If the key is different from what we know, derive the new E/D keys.
2344 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2346 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2347 sizeof (msg->ephemeral_key)))
2349 #if DUMP_KEYS_TO_STDERR
2350 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2351 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2352 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2353 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2355 t->peers_ephemeral_key = msg->ephemeral_key;
2359 if (CADET_TUNNEL_KEY_OK == t->estate)
2361 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2363 if (NULL != t->rekey_task)
2364 GNUNET_SCHEDULER_cancel (t->rekey_task);
2365 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2367 if (CADET_TUNNEL_KEY_SENT == t->estate)
2369 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2371 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2374 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2378 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2379 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2380 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2381 send_pong (t, nonce);
2387 * Peer has answer to our challenge.
2388 * If answer is successful, consider the key exchange finished and clean
2389 * up all related state.
2391 * @param t Tunnel this message came on.
2392 * @param msg Key eXchange Pong message.
2395 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2399 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2400 if (NULL == t->rekey_task)
2402 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2405 if (NULL == t->kx_ctx)
2407 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2411 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2412 if (challenge != t->kx_ctx->challenge)
2414 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2415 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2416 challenge, msg->nonce, t->kx_ctx->challenge);
2420 GNUNET_SCHEDULER_cancel (t->rekey_task);
2421 t->rekey_task = NULL;
2423 /* Don't free the old keys right away, but after a delay.
2424 * Rationale: the KX could have happened over a very fast connection,
2425 * with payload traffic still signed with the old key stuck in a slower
2427 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2431 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2436 * Handle Axolotl handshake.
2438 * @param t Tunnel this message came on.
2439 * @param msg Key eXchange Pong message.
2442 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2444 struct CadetTunnelAxolotl *ax;
2445 struct GNUNET_HashCode key_material[3];
2446 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2447 const struct GNUNET_CRYPTO_EcdhePublicKey *pub;
2448 const struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
2449 const char salt[] = "CADET Axolotl salt";
2450 const struct GNUNET_PeerIdentity *pid;
2453 LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2457 /* Something is wrong if ax is NULL. Whose fault it is? */
2458 GNUNET_break_op (CADET_OTR == t->enc_type);
2459 GNUNET_break (CADET_Axolotl == t->enc_type);
2463 if (GNUNET_OK != GCP_check_key (t->peer, &msg->permanent_key,
2464 &msg->purpose, &msg->signature))
2466 GNUNET_break_op (0);
2470 pid = GCT_get_destination (t);
2471 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2472 am_I_alice = GNUNET_YES;
2473 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2474 am_I_alice = GNUNET_NO;
2477 GNUNET_break_op (0);
2481 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2484 ax->DHRr = msg->ratchet_key;
2487 if (GNUNET_YES == am_I_alice)
2489 priv = ax_key; /* A */
2490 pub = &msg->ephemeral_key; /* B0 */
2494 priv = ax->kx_0; /* B0 */
2495 pub = &msg->permanent_key; /* A */
2497 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[0]);
2500 if (GNUNET_YES == am_I_alice)
2502 priv = ax->kx_0; /* A0 */
2503 pub = &msg->permanent_key; /* B */
2507 priv = ax_key; /* B */
2508 pub = &msg->ephemeral_key; /* A0 */
2510 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[1]);
2513 priv = ax->kx_0; /* A0 or B0 */
2514 pub = &msg->ephemeral_key; /* B0 or A0 */
2515 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[2]);
2517 #if DUMP_KEYS_TO_STDERR
2520 for (i = 0; i < 3; i++)
2521 LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2522 i, GNUNET_h2s (&key_material[i]));
2527 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2528 salt, sizeof (salt),
2529 &key_material, sizeof (key_material), NULL);
2532 if (GNUNET_YES == am_I_alice)
2538 ax->ratchet_flag = GNUNET_YES;
2546 ax->ratchet_flag = GNUNET_NO;
2548 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2553 * Demultiplex by message type and call appropriate handler for a message
2554 * towards a channel of a local tunnel.
2556 * @param t Tunnel this message came on.
2557 * @param msgh Message header.
2558 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2559 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2560 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2561 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2564 handle_decrypted (struct CadetTunnel *t,
2565 const struct GNUNET_MessageHeader *msgh,
2570 type = ntohs (msgh->type);
2571 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2575 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2576 /* Do nothing, connection aleady got updated. */
2577 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2580 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2581 /* Don't send hop ACK, wait for client to ACK */
2582 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2585 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2586 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2589 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2590 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2593 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2594 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
2597 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2598 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2601 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2602 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2606 GNUNET_break_op (0);
2607 LOG (GNUNET_ERROR_TYPE_WARNING,
2608 "end-to-end message not known (%u)\n",
2609 ntohs (msgh->type));
2610 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2614 /******************************************************************************/
2615 /******************************** API ***********************************/
2616 /******************************************************************************/
2618 * Decrypt old format and demultiplex by message type. Call appropriate handler
2619 * for a message towards a channel of a local tunnel.
2621 * @param t Tunnel this message came on.
2622 * @param msg Message header.
2625 GCT_handle_encrypted (struct CadetTunnel *t,
2626 const struct GNUNET_MessageHeader *msg)
2628 size_t size = ntohs (msg->size);
2629 size_t payload_size;
2632 uint16_t type = ntohs (msg->type);
2633 struct GNUNET_MessageHeader *msgh;
2636 if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
2638 const struct GNUNET_CADET_Encrypted *emsg;
2640 emsg = (struct GNUNET_CADET_Encrypted *) msg;
2641 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2642 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
2643 emsg->iv, &emsg->hmac);
2645 else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
2647 const struct GNUNET_CADET_AX *emsg;
2649 emsg = (struct GNUNET_CADET_AX *) msg;
2650 payload_size = size - sizeof (struct GNUNET_CADET_AX);
2651 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, &emsg[1],
2652 payload_size, &emsg->hmac);
2655 if (-1 == decrypted_size)
2657 GNUNET_break_op (0);
2662 while (off < decrypted_size)
2666 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2667 msize = ntohs (msgh->size);
2668 if (msize < sizeof (struct GNUNET_MessageHeader))
2670 GNUNET_break_op (0);
2673 handle_decrypted (t, msgh, GNUNET_SYSERR);
2680 * Demultiplex an encapsulated KX message by message type.
2682 * @param t Tunnel on which the message came.
2683 * @param message Payload of KX message.
2686 GCT_handle_kx (struct CadetTunnel *t,
2687 const struct GNUNET_MessageHeader *message)
2691 type = ntohs (message->type);
2692 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
2695 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2696 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
2699 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2700 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
2703 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2704 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
2708 GNUNET_break_op (0);
2709 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
2714 * Initialize the tunnel subsystem.
2716 * @param c Configuration handle.
2717 * @param key ECC private key, to derive all other keys and do crypto.
2720 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2721 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2723 int expected_overhead;
2725 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2727 expected_overhead = 0;
2728 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
2729 expected_overhead += sizeof (struct GNUNET_CADET_Data);
2730 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
2731 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2734 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2737 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2738 "CADET", "DEFAULT_TTL", "USING DEFAULT");
2742 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2745 rekey_period = GNUNET_TIME_UNIT_DAYS;
2750 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
2751 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2752 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2753 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2754 otr_kx_msg.origin_identity = my_full_id;
2755 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
2757 ax_key = GNUNET_CRYPTO_ecdhe_key_create ();
2758 GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &ax_identity.permanent_key);
2759 ax_identity.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_AXKX);
2760 ax_identity.purpose.size = htonl (ax_purpose_size ());
2761 GNUNET_assert (GNUNET_OK ==
2762 GNUNET_CRYPTO_eddsa_sign (id_key,
2763 &ax_identity.purpose,
2764 &ax_identity.signature));
2766 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2771 * Shut down the tunnel subsystem.
2776 if (NULL != rekey_task)
2778 GNUNET_SCHEDULER_cancel (rekey_task);
2781 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2782 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2783 GNUNET_free (ax_key);
2790 * @param destination Peer this tunnel is towards.
2792 struct CadetTunnel *
2793 GCT_new (struct CadetPeer *destination)
2795 struct CadetTunnel *t;
2797 t = GNUNET_new (struct CadetTunnel);
2799 t->peer = destination;
2802 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2803 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2809 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
2811 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2817 * Change the tunnel's connection state.
2819 * @param t Tunnel whose connection state to change.
2820 * @param cstate New connection state.
2823 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2827 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2828 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2829 if (myid != GCP_get_short_id (t->peer) &&
2830 CADET_TUNNEL_READY != t->cstate &&
2831 CADET_TUNNEL_READY == cstate)
2834 if (CADET_TUNNEL_KEY_OK == t->estate)
2836 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2837 send_queued_data (t);
2839 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2841 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
2846 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
2851 if (CADET_TUNNEL_READY == cstate
2852 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2854 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2855 GCP_stop_search (t->peer);
2861 * Change the tunnel encryption state.
2863 * @param t Tunnel whose encryption state to change, or NULL.
2864 * @param state New encryption state.
2867 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2869 enum CadetTunnelEState old;
2876 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2877 GCP_2s (t->peer), estate2s (old));
2878 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2879 GCP_2s (t->peer), estate2s (t->estate));
2881 /* Send queued data if enc state changes to OK */
2882 if (myid != GCP_get_short_id (t->peer) &&
2883 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
2885 send_queued_data (t);
2891 * @brief Check if tunnel has too many connections, and remove one if necessary.
2893 * Currently this means the newest connection, unless it is a direct one.
2894 * Implemented as a task to avoid freeing a connection that is in the middle
2895 * of being created/processed.
2897 * @param cls Closure (Tunnel to check).
2898 * @param tc Task context.
2901 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2903 struct CadetTunnel *t = cls;
2905 t->trim_connections_task = NULL;
2907 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2910 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2912 struct CadetTConnection *iter;
2913 struct CadetTConnection *c;
2915 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2917 if ((iter->created.abs_value_us > c->created.abs_value_us)
2918 && GNUNET_NO == GCC_is_direct (iter->c))
2925 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2927 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2940 * Add a connection to a tunnel.
2943 * @param c Connection.
2946 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2948 struct CadetTConnection *aux;
2950 GNUNET_assert (NULL != c);
2952 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2953 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2954 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2958 aux = GNUNET_new (struct CadetTConnection);
2960 aux->created = GNUNET_TIME_absolute_get ();
2962 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2964 if (CADET_TUNNEL_SEARCHING == t->cstate)
2965 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2967 if (NULL != t->trim_connections_task)
2968 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
2973 * Remove a connection from a tunnel.
2976 * @param c Connection.
2979 GCT_remove_connection (struct CadetTunnel *t,
2980 struct CadetConnection *c)
2982 struct CadetTConnection *aux;
2983 struct CadetTConnection *next;
2986 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2987 GCC_2s (c), GCT_2s (t));
2988 for (aux = t->connection_head; aux != NULL; aux = next)
2993 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2998 conns = GCT_count_connections (t);
3000 && NULL == t->destroy_task
3001 && CADET_TUNNEL_SHUTDOWN != t->cstate
3002 && GNUNET_NO == shutting_down)
3004 if (0 == GCT_count_any_connections (t))
3005 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3007 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3010 /* Start new connections if needed */
3011 if (CONNECTIONS_PER_TUNNEL > conns
3012 && NULL == t->destroy_task
3013 && CADET_TUNNEL_SHUTDOWN != t->cstate
3014 && GNUNET_NO == shutting_down)
3016 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
3017 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3021 /* If not marked as ready, no change is needed */
3022 if (CADET_TUNNEL_READY != t->cstate)
3025 /* Check if any connection is ready to maintain cstate */
3026 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3027 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3033 * Add a channel to a tunnel.
3036 * @param ch Channel.
3039 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3041 struct CadetTChannel *aux;
3043 GNUNET_assert (NULL != ch);
3045 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3047 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3049 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
3054 aux = GNUNET_new (struct CadetTChannel);
3056 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3057 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3059 if (NULL != t->destroy_task)
3061 GNUNET_SCHEDULER_cancel (t->destroy_task);
3062 t->destroy_task = NULL;
3063 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3069 * Remove a channel from a tunnel.
3072 * @param ch Channel.
3075 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3077 struct CadetTChannel *aux;
3079 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3080 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3084 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3085 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3094 * Search for a channel by global ID.
3096 * @param t Tunnel containing the channel.
3097 * @param chid Public channel number.
3099 * @return channel handler, NULL if doesn't exist
3101 struct CadetChannel *
3102 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3104 struct CadetTChannel *iter;
3109 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3111 if (GCCH_get_id (iter->ch) == chid)
3115 return NULL == iter ? NULL : iter->ch;
3120 * @brief Destroy a tunnel and free all resources.
3122 * Should only be called a while after the tunnel has been marked as destroyed,
3123 * in case there is a new channel added to the same peer shortly after marking
3124 * the tunnel. This way we avoid a new public key handshake.
3126 * @param cls Closure (tunnel to destroy).
3127 * @param tc Task context.
3130 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3132 struct CadetTunnel *t = cls;
3133 struct CadetTConnection *iter;
3135 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3136 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3138 LOG (GNUNET_ERROR_TYPE_WARNING,
3139 "Not destroying tunnel, due to shutdown. "
3140 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3143 t->destroy_task = NULL;
3144 t->cstate = CADET_TUNNEL_SHUTDOWN;
3146 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3148 GCC_send_destroy (iter->c);
3155 * Tunnel is empty: destroy it.
3157 * Notifies all connections about the destruction.
3159 * @param t Tunnel to destroy.
3162 GCT_destroy_empty (struct CadetTunnel *t)
3164 if (GNUNET_YES == shutting_down)
3165 return; /* Will be destroyed immediately anyway */
3167 if (NULL != t->destroy_task)
3169 LOG (GNUNET_ERROR_TYPE_WARNING,
3170 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3172 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3174 /* should never happen, tunnel can only become empty once, and the
3175 * task identifier should be NO_TASK (cleaned when the tunnel was created
3176 * or became un-empty)
3181 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3184 // FIXME make delay a config option
3185 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3186 &delayed_destroy, t);
3187 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3188 t, t->destroy_task);
3193 * Destroy tunnel if empty (no more channels).
3195 * @param t Tunnel to destroy if empty.
3198 GCT_destroy_if_empty (struct CadetTunnel *t)
3200 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3201 if (0 < GCT_count_channels (t))
3204 GCT_destroy_empty (t);
3209 * Destroy the tunnel.
3211 * This function does not generate any warning traffic to clients or peers.
3214 * Cancel messages belonging to this tunnel queued to neighbors.
3215 * Free any allocated resources linked to the tunnel.
3217 * @param t The tunnel to destroy.
3220 GCT_destroy (struct CadetTunnel *t)
3222 struct CadetTConnection *iter_c;
3223 struct CadetTConnection *next_c;
3224 struct CadetTChannel *iter_ch;
3225 struct CadetTChannel *next_ch;
3230 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3232 GNUNET_break (GNUNET_YES ==
3233 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3234 GCP_get_id (t->peer), t));
3236 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3238 next_c = iter_c->next;
3239 GCC_destroy (iter_c->c);
3241 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3243 next_ch = iter_ch->next;
3244 GCCH_destroy (iter_ch->ch);
3245 /* Should only happen on shutdown, but it's ok. */
3248 if (NULL != t->destroy_task)
3250 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3251 GNUNET_SCHEDULER_cancel (t->destroy_task);
3252 t->destroy_task = NULL;
3255 if (NULL != t->trim_connections_task)
3257 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3258 t->trim_connections_task);
3259 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3260 t->trim_connections_task = NULL;
3263 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3264 GCP_set_tunnel (t->peer, NULL);
3266 if (NULL != t->rekey_task)
3268 GNUNET_SCHEDULER_cancel (t->rekey_task);
3269 t->rekey_task = NULL;
3271 if (NULL != t->kx_ctx)
3273 if (NULL != t->kx_ctx->finish_task)
3274 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3275 GNUNET_free (t->kx_ctx);
3286 * @brief Use the given path for the tunnel.
3287 * Update the next and prev hops (and RCs).
3288 * (Re)start the path refresh in case the tunnel is locally owned.
3290 * @param t Tunnel to update.
3291 * @param p Path to use.
3293 * @return Connection created.
3295 struct CadetConnection *
3296 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3298 struct CadetConnection *c;
3299 struct GNUNET_CADET_Hash cid;
3300 unsigned int own_pos;
3302 if (NULL == t || NULL == p)
3308 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3314 for (own_pos = 0; own_pos < p->length; own_pos++)
3316 if (p->peers[own_pos] == myid)
3319 if (own_pos >= p->length)
3321 GNUNET_break_op (0);
3325 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3326 c = GCC_new (&cid, t, p, own_pos);
3329 /* Path was flawed */
3332 GCT_add_connection (t, c);
3338 * Count all created connections of a tunnel. Not necessarily ready connections!
3340 * @param t Tunnel on which to count.
3342 * @return Number of connections created, either being established or ready.
3345 GCT_count_any_connections (struct CadetTunnel *t)
3347 struct CadetTConnection *iter;
3353 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3361 * Count established (ready) connections of a tunnel.
3363 * @param t Tunnel on which to count.
3365 * @return Number of connections.
3368 GCT_count_connections (struct CadetTunnel *t)
3370 struct CadetTConnection *iter;
3376 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3377 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3385 * Count channels of a tunnel.
3387 * @param t Tunnel on which to count.
3389 * @return Number of channels.
3392 GCT_count_channels (struct CadetTunnel *t)
3394 struct CadetTChannel *iter;
3397 for (count = 0, iter = t->channel_head;
3399 iter = iter->next, count++) /* skip */;
3406 * Get the connectivity state of a tunnel.
3410 * @return Tunnel's connectivity state.
3412 enum CadetTunnelCState
3413 GCT_get_cstate (struct CadetTunnel *t)
3418 return (enum CadetTunnelCState) -1;
3425 * Get the encryption state of a tunnel.
3429 * @return Tunnel's encryption state.
3431 enum CadetTunnelEState
3432 GCT_get_estate (struct CadetTunnel *t)
3437 return (enum CadetTunnelEState) -1;
3443 * Get the maximum buffer space for a tunnel towards a local client.
3447 * @return Biggest buffer space offered by any channel in the tunnel.
3450 GCT_get_channels_buffer (struct CadetTunnel *t)
3452 struct CadetTChannel *iter;
3453 unsigned int buffer;
3454 unsigned int ch_buf;
3456 if (NULL == t->channel_head)
3458 /* Probably getting buffer for a channel create/handshake. */
3459 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3464 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3466 ch_buf = get_channel_buffer (iter);
3467 if (ch_buf > buffer)
3475 * Get the total buffer space for a tunnel for P2P traffic.
3479 * @return Buffer space offered by all connections in the tunnel.
3482 GCT_get_connections_buffer (struct CadetTunnel *t)
3484 struct CadetTConnection *iter;
3485 unsigned int buffer;
3487 if (GNUNET_NO == is_ready (t))
3489 if (count_queued_data (t) > 3)
3496 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3498 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3502 buffer += get_connection_buffer (iter);
3510 * Get the tunnel's destination.
3514 * @return ID of the destination peer.
3516 const struct GNUNET_PeerIdentity *
3517 GCT_get_destination (struct CadetTunnel *t)
3519 return GCP_get_id (t->peer);
3524 * Get the tunnel's next free global channel ID.
3528 * @return GID of a channel free to use.
3531 GCT_get_next_chid (struct CadetTunnel *t)
3533 CADET_ChannelNumber chid;
3534 CADET_ChannelNumber mask;
3537 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3538 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3539 * If peer's ID is bigger, start at 0x4... bit 30 = 1
3541 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3546 t->next_chid |= mask;
3548 while (NULL != GCT_get_channel (t, t->next_chid))
3550 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3551 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3552 t->next_chid |= mask;
3554 chid = t->next_chid;
3555 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3556 t->next_chid |= mask;
3563 * Send ACK on one or more channels due to buffer in connections.
3565 * @param t Channel which has some free buffer space.
3568 GCT_unchoke_channels (struct CadetTunnel *t)
3570 struct CadetTChannel *iter;
3571 unsigned int buffer;
3572 unsigned int channels = GCT_count_channels (t);
3573 unsigned int choked_n;
3574 struct CadetChannel *choked[channels];
3576 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3577 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3578 if (NULL != t->channel_head)
3579 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3581 /* Get buffer space */
3582 buffer = GCT_get_connections_buffer (t);
3588 /* Count and remember choked channels */
3590 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3592 if (GNUNET_NO == get_channel_allowed (iter))
3594 choked[choked_n++] = iter->ch;
3598 /* Unchoke random channels */
3599 while (0 < buffer && 0 < choked_n)
3601 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3603 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3606 choked[r] = choked[choked_n];
3612 * Send ACK on one or more connections due to buffer space to the client.
3614 * Iterates all connections of the tunnel and sends ACKs appropriately.
3619 GCT_send_connection_acks (struct CadetTunnel *t)
3621 struct CadetTConnection *iter;
3624 uint32_t allow_per_connection;
3626 unsigned int buffer;
3628 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3637 if (CADET_TUNNEL_READY != t->cstate)
3640 buffer = GCT_get_channels_buffer (t);
3641 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
3643 /* Count connections, how many messages are already allowed */
3644 cs = GCT_count_connections (t);
3645 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3647 allowed += get_connection_allowed (iter);
3649 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
3651 /* Make sure there is no overflow */
3652 if (allowed > buffer)
3655 /* Authorize connections to send more data */
3656 to_allow = buffer - allowed;
3658 for (iter = t->connection_head;
3659 NULL != iter && to_allow > 0;
3662 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3663 || get_connection_allowed (iter) > 64 / 3)
3667 allow_per_connection = to_allow/cs;
3668 to_allow -= allow_per_connection;
3670 GCC_allow (iter->c, allow_per_connection,
3671 GCC_is_origin (iter->c, GNUNET_NO));
3676 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
3677 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
3683 * Cancel a previously sent message while it's in the queue.
3685 * ONLY can be called before the continuation given to the send function
3686 * is called. Once the continuation is called, the message is no longer in the
3689 * @param q Handle to the queue.
3692 GCT_cancel (struct CadetTunnelQueue *q)
3697 /* tun_message_sent() will be called and free q */
3699 else if (NULL != q->tqd)
3701 unqueue_data (q->tqd);
3703 if (NULL != q->cont)
3704 q->cont (q->cont_cls, NULL, q, 0, 0);
3715 * Sends an already built message on a tunnel, encrypting it and
3716 * choosing the best connection if not provided.
3718 * @param message Message to send. Function modifies it.
3719 * @param t Tunnel on which this message is transmitted.
3720 * @param c Connection to use (autoselect if NULL).
3721 * @param force Force the tunnel to take the message (buffer overfill).
3722 * @param cont Continuation to call once message is really sent.
3723 * @param cont_cls Closure for @c cont.
3725 * @return Handle to cancel message. NULL if @c cont is NULL.
3727 struct CadetTunnelQueue *
3728 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3729 struct CadetTunnel *t, struct CadetConnection *c,
3730 int force, GCT_sent cont, void *cont_cls)
3732 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3737 * Send an Axolotl KX message.
3739 * @param t Tunnel on which to send it.
3742 GCT_send_ax_kx (struct CadetTunnel *t)
3744 struct GNUNET_CADET_AX_KX msg;
3746 LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
3748 msg.header.size = htons (sizeof (msg));
3749 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
3750 msg.permanent_key = ax_identity.permanent_key;
3751 msg.purpose = ax_identity.purpose;
3752 msg.signature = ax_identity.signature;
3753 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
3754 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
3756 t->ephm_h = send_kx (t, &msg.header);
3757 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
3762 * Sends an already built and encrypted message on a tunnel, choosing the best
3763 * connection. Useful for re-queueing messages queued on a destroyed connection.
3765 * @param message Message to send. Function modifies it.
3766 * @param t Tunnel on which this message is transmitted.
3769 GCT_resend_message (const struct GNUNET_MessageHeader *message,
3770 struct CadetTunnel *t)
3772 struct CadetConnection *c;
3775 c = tunnel_get_connection (t);
3778 /* TODO queue in tunnel, marked as encrypted */
3779 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
3782 fwd = GCC_is_origin (c, GNUNET_YES);
3783 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
3784 GNUNET_YES, NULL, NULL));
3789 * Is the tunnel directed towards the local peer?
3793 * @return #GNUNET_YES if it is loopback.
3796 GCT_is_loopback (const struct CadetTunnel *t)
3798 return (myid == GCP_get_short_id (t->peer));
3803 * Is the tunnel this path already?
3808 * @return #GNUNET_YES a connection uses this path.
3811 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3813 struct CadetTConnection *iter;
3815 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3816 if (path_equivalent (GCC_get_path (iter->c), p))
3824 * Get a cost of a path for a tunnel considering existing connections.
3827 * @param path Candidate path.
3829 * @return Cost of the path (path length + number of overlapping nodes)
3832 GCT_get_path_cost (const struct CadetTunnel *t,
3833 const struct CadetPeerPath *path)
3835 struct CadetTConnection *iter;
3836 const struct CadetPeerPath *aux;
3837 unsigned int overlap;
3845 GNUNET_assert (NULL != t);
3847 for (i = 0; i < path->length; i++)
3849 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3851 aux = GCC_get_path (iter->c);
3855 for (j = 0; j < aux->length; j++)
3857 if (path->peers[i] == aux->peers[j])
3865 return path->length + overlap;
3870 * Get the static string for the peer this tunnel is directed.
3874 * @return Static string the destination peer's ID.
3877 GCT_2s (const struct CadetTunnel *t)
3882 return GCP_2s (t->peer);
3886 /******************************************************************************/
3887 /***************************** INFO/DEBUG *******************************/
3888 /******************************************************************************/
3891 * Log all possible info about the tunnel state.
3893 * @param t Tunnel to debug.
3894 * @param level Debug level to use.
3897 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3899 struct CadetTChannel *iterch;
3900 struct CadetTConnection *iterc;
3903 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3905 __FILE__, __FUNCTION__, __LINE__);
3909 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3910 LOG2 (level, "TTT cstate %s, estate %s\n",
3911 cstate2s (t->cstate), estate2s (t->estate));
3912 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
3913 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
3914 #if DUMP_KEYS_TO_STDERR
3915 LOG2 (level, "TTT my EPHM\t %s\n",
3916 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
3917 LOG2 (level, "TTT peers EPHM:\t %s\n",
3918 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
3919 LOG2 (level, "TTT ENC key:\t %s\n",
3920 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
3921 LOG2 (level, "TTT DEC key:\t %s\n",
3922 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
3925 LOG2 (level, "TTT OLD ENC key:\t %s\n",
3926 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
3927 LOG2 (level, "TTT OLD DEC key:\t %s\n",
3928 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
3931 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3932 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
3934 LOG2 (level, "TTT channels:\n");
3935 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
3937 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
3940 LOG2 (level, "TTT connections:\n");
3941 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
3943 GCC_debug (iterc->c, level);
3946 LOG2 (level, "TTT DEBUG TUNNEL END\n");
3951 * Iterate all tunnels.
3953 * @param iter Iterator.
3954 * @param cls Closure for @c iter.
3957 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3959 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3964 * Count all tunnels.
3966 * @return Number of tunnels to remote peers kept by this peer.
3969 GCT_count_all (void)
3971 return GNUNET_CONTAINER_multipeermap_size (tunnels);
3976 * Iterate all connections of a tunnel.
3978 * @param t Tunnel whose connections to iterate.
3979 * @param iter Iterator.
3980 * @param cls Closure for @c iter.
3983 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3985 struct CadetTConnection *ct;
3987 for (ct = t->connection_head; NULL != ct; ct = ct->next)
3993 * Iterate all channels of a tunnel.
3995 * @param t Tunnel whose channels to iterate.
3996 * @param iter Iterator.
3997 * @param cls Closure for @c iter.
4000 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4002 struct CadetTChannel *cht;
4004 for (cht = t->channel_head; NULL != cht; cht = cht->next)
4005 iter (cls, cht->ch);