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 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
47 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
50 /******************************************************************************/
51 /******************************** STRUCTS **********************************/
52 /******************************************************************************/
56 struct CadetTChannel *next;
57 struct CadetTChannel *prev;
58 struct CadetChannel *ch;
63 * Connection list and metadata.
65 struct CadetTConnection
70 struct CadetTConnection *next;
75 struct CadetTConnection *prev;
80 struct CadetConnection *c;
83 * Creation time, to keep oldest connection alive.
85 struct GNUNET_TIME_Absolute created;
88 * Connection throughput, to keep fastest connection alive.
94 * Structure used during a Key eXchange.
96 struct CadetTunnelKXCtx
99 * Encryption ("our") old "confirmed" key, for encrypting traffic sent by us
100 * end before the key exchange is finished or times out.
102 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
105 * Decryption ("their") old "confirmed" key, for decrypting traffic sent by
106 * the other end before the key exchange started.
108 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
111 * Same as @c e_key_old, for the case of two simultaneous KX.
112 * This can happen if cadet decides to start a re-key while the peer has also
113 * started its re-key (due to network delay this is impossible to avoid).
114 * In this case, the key material generated with the peer's old ephemeral
115 * *might* (but doesn't have to) be incorrect.
116 * Since no more than two re-keys can happen simultaneously, this is enough.
118 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old2;
121 * Same as @c d_key_old, for the case described in @c e_key_old2.
123 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old2;
126 * Challenge to send and expect in the PONG.
131 * When the rekey started. One minute after this the new key will be used.
133 struct GNUNET_TIME_Absolute rekey_start_time;
136 * Task for delayed destruction of the Key eXchange context, to allow delayed
137 * messages with the old key to be decrypted successfully.
139 struct GNUNET_SCHEDULER_Task *finish_task;
143 * Encryption systems possible.
145 enum CadetTunnelEncryption
148 * Default Axolotl system.
153 * Fallback OTR-style encryption.
159 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
161 struct CadetTunnelSkippedKey
166 struct CadetTunnelSkippedKey *next;
171 struct CadetTunnelSkippedKey *prev;
174 * When was this key stored (for timeout).
176 struct GNUNET_TIME_Absolute timestamp;
181 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
186 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
190 * Axolotl data, according to https://github.com/trevp/axolotl/wiki
192 struct CadetTunnelAxolotl
195 * A (double linked) list of stored message keys and associated header keys
196 * for "skipped" messages, i.e. messages that have not bee*n
197 * received despite the reception of more recent messages, (head)/
199 struct CadetTunnelSkippedKey *skipped_head;
202 * Skipped messages' keys DLL, tail.
204 struct CadetTunnelSkippedKey *skipped_tail;
207 * Elements in @a skipped_head <-> @a skipped_tail.
212 * 32-byte root key which gets updated by DH ratchet
214 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
217 * 32-byte header key (send)
219 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
222 * 32-byte header key (recv)
224 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
227 * 32-byte next header key (send)
229 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
232 * 32-byte next header key (recv)
234 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
237 * 32-byte chain keys (used for forward-secrecy updating, send)
239 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
242 * 32-byte chain keys (used for forward-secrecy updating, recv)
244 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
247 * ECDH for key exchange (A0 / B0)
249 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
252 * ECDH Ratchet key (send)
254 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
257 * ECDH Ratchet key (recv)
259 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
262 * Message number (reset to 0 with each new ratchet, send)
267 * Message numbers (reset to 0 with each new ratchet, recv)
272 * Previous message numbers (# of msgs sent under prev ratchet)
277 * True (#GNUNET_YES) if the party will send a new ratchet key in next msg.
283 * Struct containing all information regarding a tunnel to a peer.
288 * Endpoint of the tunnel.
290 struct CadetPeer *peer;
293 * Type of encryption used in the tunnel.
295 enum CadetTunnelEncryption enc_type;
300 struct CadetTunnelAxolotl *ax;
303 * State of the tunnel connectivity.
305 enum CadetTunnelCState cstate;
308 * State of the tunnel encryption.
310 enum CadetTunnelEState estate;
313 * Key eXchange context.
315 struct CadetTunnelKXCtx *kx_ctx;
318 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
321 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
324 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
326 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
329 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
331 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
334 * Task to start the rekey process.
336 struct GNUNET_SCHEDULER_Task * rekey_task;
339 * Paths that are actively used to reach the destination peer.
341 struct CadetTConnection *connection_head;
342 struct CadetTConnection *connection_tail;
345 * Next connection number.
350 * Channels inside this tunnel.
352 struct CadetTChannel *channel_head;
353 struct CadetTChannel *channel_tail;
356 * Channel ID for the next created channel.
358 CADET_ChannelNumber next_chid;
361 * Destroy flag: if true, destroy on last message.
363 struct GNUNET_SCHEDULER_Task * destroy_task;
366 * Queued messages, to transmit once tunnel gets connected.
368 struct CadetTunnelDelayed *tq_head;
369 struct CadetTunnelDelayed *tq_tail;
372 * Task to trim connections if too many are present.
374 struct GNUNET_SCHEDULER_Task * trim_connections_task;
377 * Ephemeral message in the queue (to avoid queueing more than one).
379 struct CadetConnectionQueue *ephm_h;
382 * Pong message in the queue.
384 struct CadetConnectionQueue *pong_h;
389 * Struct used to save messages in a non-ready tunnel to send once connected.
391 struct CadetTunnelDelayed
396 struct CadetTunnelDelayed *next;
397 struct CadetTunnelDelayed *prev;
402 struct CadetTunnel *t;
405 * Tunnel queue given to the channel to cancel request. Update on send_queued.
407 struct CadetTunnelQueue *tq;
412 /* struct GNUNET_MessageHeader *msg; */
417 * Handle for messages queued but not yet sent.
419 struct CadetTunnelQueue
422 * Connection queue handle, to cancel if necessary.
424 struct CadetConnectionQueue *cq;
427 * Handle in case message hasn't been given to a connection yet.
429 struct CadetTunnelDelayed *tqd;
432 * Continuation to call once sent.
437 * Closure for @c cont.
444 * Cached Axolotl key with signature.
446 struct CadetAxolotlSignedKey
449 * Information about what is being signed (@a permanent_key).
451 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
454 * Permanent public ECDH key.
456 struct GNUNET_CRYPTO_EcdhePublicKey permanent_key;
459 * An EdDSA signature of the permanent ECDH key with the Peer's ID key.
461 struct GNUNET_CRYPTO_EddsaSignature signature;
465 /******************************************************************************/
466 /******************************* GLOBALS ***********************************/
467 /******************************************************************************/
470 * Global handle to the statistics service.
472 extern struct GNUNET_STATISTICS_Handle *stats;
475 * Local peer own ID (memory efficient handle).
477 extern GNUNET_PEER_Id myid;
480 * Local peer own ID (full value).
482 extern struct GNUNET_PeerIdentity my_full_id;
486 * Don't try to recover tunnels if shutting down.
488 extern int shutting_down;
492 * Set of all tunnels, in order to trigger a new exchange on rekey.
493 * Indexed by peer's ID.
495 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
498 * Default TTL for payload packets.
500 static unsigned long long default_ttl;
504 * Own Peer ID private key.
506 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
508 /******************************** AXOLOTL ************************************/
510 static struct GNUNET_CRYPTO_EcdhePrivateKey *ax_key;
513 * Own Axolotl permanent public key (cache).
515 static struct CadetAxolotlSignedKey ax_identity;
517 /******************************** OTR ***********************************/
521 * Own global OTR ephemeral private key.
523 static struct GNUNET_CRYPTO_EcdhePrivateKey *otr_ephemeral_key;
526 * Cached message used to perform a OTR key exchange.
528 static struct GNUNET_CADET_KX_Ephemeral otr_kx_msg;
531 * Task to generate a new OTR ephemeral key.
533 static struct GNUNET_SCHEDULER_Task *rekey_task;
538 static struct GNUNET_TIME_Relative rekey_period;
541 /******************************************************************************/
542 /******************************** STATIC ***********************************/
543 /******************************************************************************/
546 * Get string description for tunnel connectivity state.
548 * @param cs Tunnel state.
550 * @return String representation.
553 cstate2s (enum CadetTunnelCState cs)
559 case CADET_TUNNEL_NEW:
560 return "CADET_TUNNEL_NEW";
561 case CADET_TUNNEL_SEARCHING:
562 return "CADET_TUNNEL_SEARCHING";
563 case CADET_TUNNEL_WAITING:
564 return "CADET_TUNNEL_WAITING";
565 case CADET_TUNNEL_READY:
566 return "CADET_TUNNEL_READY";
567 case CADET_TUNNEL_SHUTDOWN:
568 return "CADET_TUNNEL_SHUTDOWN";
570 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
578 * Get string description for tunnel encryption state.
580 * @param es Tunnel state.
582 * @return String representation.
585 estate2s (enum CadetTunnelEState es)
591 case CADET_TUNNEL_KEY_UNINITIALIZED:
592 return "CADET_TUNNEL_KEY_UNINITIALIZED";
593 case CADET_TUNNEL_KEY_SENT:
594 return "CADET_TUNNEL_KEY_SENT";
595 case CADET_TUNNEL_KEY_PING:
596 return "CADET_TUNNEL_KEY_PING";
597 case CADET_TUNNEL_KEY_OK:
598 return "CADET_TUNNEL_KEY_OK";
599 case CADET_TUNNEL_KEY_REKEY:
600 return "CADET_TUNNEL_KEY_REKEY";
602 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
610 * @brief Check if tunnel is ready to send traffic.
612 * Tunnel must be connected and with encryption correctly set up.
614 * @param t Tunnel to check.
616 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
619 is_ready (struct CadetTunnel *t)
623 GCT_debug (t, GNUNET_ERROR_TYPE_DEBUG);
624 ready = CADET_TUNNEL_READY == t->cstate
625 && (CADET_TUNNEL_KEY_OK == t->estate
626 || CADET_TUNNEL_KEY_REKEY == t->estate);
627 ready = ready || GCT_is_loopback (t);
633 * Check if a key is invalid (NULL pointer or all 0)
635 * @param key Key to check.
637 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
640 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
642 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
647 memset (&null_key, 0, sizeof (null_key));
648 if (0 == memcmp (key, &null_key, sizeof (null_key)))
655 * Ephemeral key message purpose size.
657 * @return Size of the part of the ephemeral key message that must be signed.
660 ephemeral_purpose_size (void)
662 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
663 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
664 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
665 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
666 sizeof (struct GNUNET_PeerIdentity);
671 * Ephemeral key message purpose size.
673 * @return Size of the part of the ephemeral key message that must be signed.
676 ax_purpose_size (void)
678 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
679 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
684 * Size of the encrypted part of a ping message.
686 * @return Size of the encrypted part of a ping message.
689 ping_encryption_size (void)
691 return sizeof (uint32_t);
696 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
698 * @param tch Tunnel's channel handle.
700 * @return Amount of messages the channel can still buffer towards the client.
703 get_channel_buffer (const struct CadetTChannel *tch)
707 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
708 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
710 return GCCH_get_buffer (tch->ch, fwd);
715 * Get the channel's allowance status.
717 * @param tch Tunnel's channel handle.
719 * @return #GNUNET_YES if we allowed the client to send data to us.
722 get_channel_allowed (const struct CadetTChannel *tch)
726 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
727 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
729 return GCCH_get_allowed (tch->ch, fwd);
734 * Get the connection's buffer.
736 * @param tc Tunnel's connection handle.
738 * @return Amount of messages the connection can still buffer.
741 get_connection_buffer (const struct CadetTConnection *tc)
745 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
746 fwd = GCC_is_origin (tc->c, GNUNET_YES);
748 return GCC_get_buffer (tc->c, fwd);
753 * Get the connection's allowance.
755 * @param tc Tunnel's connection handle.
757 * @return Amount of messages we have allowed the next peer to send us.
760 get_connection_allowed (const struct CadetTConnection *tc)
764 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
765 fwd = GCC_is_origin (tc->c, GNUNET_YES);
767 return GCC_get_allowed (tc->c, fwd);
772 * Check that a ephemeral key message s well formed and correctly signed.
774 * @param t Tunnel on which the message came.
775 * @param msg The ephemeral key message.
777 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
780 check_ephemeral (struct CadetTunnel *t,
781 const struct GNUNET_CADET_KX_Ephemeral *msg)
783 /* Check message size */
784 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
785 return GNUNET_SYSERR;
787 /* Check signature size */
788 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
789 return GNUNET_SYSERR;
792 if (0 != memcmp (&msg->origin_identity,
793 GCP_get_id (t->peer),
794 sizeof (struct GNUNET_PeerIdentity)))
795 return GNUNET_SYSERR;
797 /* Check signature */
799 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
802 &msg->origin_identity.public_key))
803 return GNUNET_SYSERR;
810 * Select the best key to use for encryption (send), based on KX status.
812 * Normally, return the current key. If there is a KX in progress and the old
813 * key is fresh enough, return the old key.
815 * @param t Tunnel to choose the key from.
817 * @return The optimal key to encrypt/hmac outgoing traffic.
819 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
820 select_key (const struct CadetTunnel *t)
822 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
824 if (NULL != t->kx_ctx
825 && NULL == t->kx_ctx->finish_task)
827 struct GNUNET_TIME_Relative age;
829 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
830 LOG (GNUNET_ERROR_TYPE_DEBUG,
831 " key exchange in progress, started %s ago\n",
832 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
833 // FIXME make duration of old keys configurable
834 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
836 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
837 key = &t->kx_ctx->e_key_old;
841 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
847 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
857 * @param plaintext Content to HMAC.
858 * @param size Size of @c plaintext.
859 * @param iv Initialization vector for the message.
860 * @param key Key to use.
861 * @param hmac[out] Destination to store the HMAC.
864 t_hmac (const void *plaintext, size_t size,
865 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
866 struct GNUNET_CADET_Hash *hmac)
868 static const char ctx[] = "cadet authentication key";
869 struct GNUNET_CRYPTO_AuthKey auth_key;
870 struct GNUNET_HashCode hash;
872 #if DUMP_KEYS_TO_STDERR
873 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC with key %s\n",
874 GNUNET_h2s ((struct GNUNET_HashCode *) key));
876 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
881 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
882 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
883 memcpy (hmac, &hash, sizeof (*hmac));
888 * Encrypt daforce_newest_keyta with the tunnel key.
890 * @param t Tunnel whose key to use.
891 * @param dst Destination for the encrypted data.
892 * @param src Source of the plaintext. Can overlap with @c dst.
893 * @param size Size of the plaintext.
894 * @param iv Initialization Vector to use.
895 * @param force_newest_key Force the use of the newest key, otherwise
896 * CADET will use the old key when allowed.
897 * This can happen in the case when a KX is going on
898 * and the old one hasn't expired.
901 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
902 size_t size, uint32_t iv, int force_newest_key)
904 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
905 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
908 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
910 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
911 #if DUMP_KEYS_TO_STDERR
912 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
913 GNUNET_h2s ((struct GNUNET_HashCode *) key));
915 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
916 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
917 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
918 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
927 * @param key Key to use.
928 * @param hash[out] Resulting HMAC.
929 * @param source Source key material (data to HMAC).
930 * @param len Length of @a source.
933 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
934 struct GNUNET_HashCode *hash,
935 void *source, unsigned int len)
937 static const char ctx[] = "axolotl HMAC-HASH";
938 struct GNUNET_CRYPTO_AuthKey auth_key;
940 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
943 GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
948 * Derive a key from a HMAC-HASH.
950 * @param key Key to use for the HMAC.
951 * @param out Key to generate.
952 * @param source Source key material (data to HMAC).
953 * @param len Length of @a source.
956 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
957 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
958 void *source, unsigned int len)
960 static const char ctx[] = "axolotl derive key";
961 struct GNUNET_HashCode h;
963 t_ax_hmac_hash (key, &h, source, len);
964 GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
965 &h, sizeof (h), NULL);
970 * Encrypt data with the axolotl tunnel key.
972 * @param t Tunnel whose key to use.
973 * @param dst Destination for the encrypted data.
974 * @param src Source of the plaintext. Can overlap with @c dst.
975 * @param size Size of the plaintext.
977 * @return Size of the encrypted data.
980 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
982 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
983 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
984 struct CadetTunnelAxolotl *ax;
987 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
991 if (GNUNET_YES == ax->ratchet_flag)
993 /* Advance ratchet */
994 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
995 struct GNUNET_HashCode dh;
996 struct GNUNET_HashCode hmac;
997 static const char ctx[] = "axolotl ratchet";
999 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
1002 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
1003 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
1004 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1005 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1006 &hmac, sizeof (hmac), NULL);
1013 ax->ratchet_flag = GNUNET_NO;
1016 t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
1017 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1019 #if DUMP_KEYS_TO_STDERR
1020 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC with key %s\n",
1021 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1024 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
1026 t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
1028 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1035 * Encrypt header with the axolotl header key.
1037 * @param t Tunnel whose key to use.
1038 * @param msg Message whose header to encrypt.
1041 t_h_encrypt (struct CadetTunnel *t, struct GNUNET_CADET_AX *msg)
1043 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1044 struct CadetTunnelAxolotl *ax;
1047 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_encrypt start\n");
1050 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKs, NULL, 0, NULL);
1052 #if DUMP_KEYS_TO_STDERR
1053 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC_H with key %s\n",
1054 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
1057 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns, AX_HEADER_SIZE,
1058 &ax->HKs, &iv, &msg->Ns);
1060 GNUNET_assert (AX_HEADER_SIZE == out_size);
1062 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1067 * Decrypt and verify data with the appropriate tunnel key.
1069 * @param key Key to use.
1070 * @param dst Destination for the plaintext.
1071 * @param src Source of the encrypted data. Can overlap with @c dst.
1072 * @param size Size of the encrypted data.
1073 * @param iv Initialization Vector to use.
1075 * @return Size of the decrypted data, -1 if an error was encountered.
1078 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1079 void *dst, const void *src, size_t size, uint32_t iv)
1081 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
1084 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
1085 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
1086 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
1087 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
1088 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
1089 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
1096 * Decrypt and verify data with the most recent tunnel key.
1098 * @param t Tunnel whose key to use.
1099 * @param dst Destination for the plaintext.
1100 * @param src Source of the encrypted data. Can overlap with @c dst.
1101 * @param size Size of the encrypted data.
1102 * @param iv Initialization Vector to use.
1104 * @return Size of the decrypted data, -1 if an error was encountered.
1107 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
1108 size_t size, uint32_t iv)
1112 #if DUMP_KEYS_TO_STDERR
1113 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
1114 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1116 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1118 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
1119 LOG (GNUNET_ERROR_TYPE_WARNING,
1120 "got data on %s without a valid key\n",
1122 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1126 out_size = decrypt (&t->d_key, dst, src, size, iv);
1133 * Decrypt and verify data with the appropriate tunnel key and verify that the
1134 * data has not been altered since it was sent by the remote peer.
1136 * @param t Tunnel whose key to use.
1137 * @param dst Destination for the plaintext.
1138 * @param src Source of the encrypted data. Can overlap with @c dst.
1139 * @param size Size of the encrypted data.
1140 * @param iv Initialization Vector to use.
1141 * @param msg_hmac HMAC of the message, cannot be NULL.
1143 * @return Size of the decrypted data, -1 if an error was encountered.
1146 t_decrypt_and_validate (struct CadetTunnel *t,
1147 void *dst, const void *src,
1148 size_t size, uint32_t iv,
1149 const struct GNUNET_CADET_Hash *msg_hmac)
1151 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1152 struct GNUNET_CADET_Hash hmac;
1155 /* Try primary (newest) key */
1157 decrypted_size = decrypt (key, dst, src, size, iv);
1158 t_hmac (src, size, iv, key, &hmac);
1159 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1160 return decrypted_size;
1162 /* If no key exchange is going on, we just failed. */
1163 if (NULL == t->kx_ctx)
1165 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1166 "Failed checksum validation on tunnel %s with no KX\n",
1168 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1172 /* Try secondary key, from previous KX period. */
1173 key = &t->kx_ctx->d_key_old;
1174 decrypted_size = decrypt (key, dst, src, size, iv);
1175 t_hmac (src, size, iv, key, &hmac);
1176 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1177 return decrypted_size;
1179 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1180 key = &t->kx_ctx->d_key_old2;
1181 decrypted_size = decrypt (key, dst, src, size, iv);
1182 t_hmac (src, size, iv, key, &hmac);
1183 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1184 return decrypted_size;
1186 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1187 "Failed checksum validation on tunnel %s with KX\n",
1189 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1194 * Decrypt and verify data with the appropriate tunnel key and verify that the
1195 * data has not been altered since it was sent by the remote peer.
1197 * @param t Tunnel whose key to use.
1198 * @param dst Destination for the plaintext.
1199 * @param src Source of the encrypted data. Can overlap with @c dst.
1200 * @param size Size of the encrypted data.
1201 * @param msg_hmac HMAC of the message, cannot be NULL.
1203 * @return Size of the decrypted data, -1 if an error was encountered.
1206 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1207 void *dst, const void *src, size_t size,
1208 const struct GNUNET_CADET_Hash *msg_hmac)
1210 struct CadetTunnelAxolotl *ax;
1227 * Create key material by doing ECDH on the local and remote ephemeral keys.
1229 * @param key_material Where to store the key material.
1230 * @param ephemeral_key Peer's public ephemeral key.
1233 derive_key_material (struct GNUNET_HashCode *key_material,
1234 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
1237 GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key,
1247 * Create a symmetic key from the identities of both ends and the key material
1250 * @param key Destination for the generated key.
1251 * @param sender ID of the peer that will encrypt with @c key.
1252 * @param receiver ID of the peer that will decrypt with @c key.
1253 * @param key_material Hash created with ECDH with the ephemeral keys.
1256 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1257 const struct GNUNET_PeerIdentity *sender,
1258 const struct GNUNET_PeerIdentity *receiver,
1259 const struct GNUNET_HashCode *key_material)
1261 const char salt[] = "CADET kx salt";
1263 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1264 salt, sizeof (salt),
1265 key_material, sizeof (struct GNUNET_HashCode),
1266 sender, sizeof (struct GNUNET_PeerIdentity),
1267 receiver, sizeof (struct GNUNET_PeerIdentity),
1273 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1275 * @param t Tunnel for which to create the keys.
1278 create_keys (struct CadetTunnel *t)
1280 struct GNUNET_HashCode km;
1282 derive_key_material (&km, &t->peers_ephemeral_key);
1283 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1284 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1285 #if DUMP_KEYS_TO_STDERR
1286 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1287 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
1288 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1289 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1290 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1291 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1292 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1293 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1294 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1300 * Create a new Key eXchange context for the tunnel.
1302 * If the old keys were verified, keep them for old traffic. Create a new KX
1303 * timestamp and a new nonce.
1305 * @param t Tunnel for which to create the KX ctx.
1308 create_kx_ctx (struct CadetTunnel *t)
1310 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1312 if (NULL != t->kx_ctx)
1314 if (NULL != t->kx_ctx->finish_task)
1316 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1317 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1318 t->kx_ctx->finish_task = NULL;
1323 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1324 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1328 if (CADET_TUNNEL_KEY_OK == t->estate)
1330 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1331 t->kx_ctx->d_key_old = t->d_key;
1332 t->kx_ctx->e_key_old = t->e_key;
1335 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1336 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1342 * @brief Finish the Key eXchange and destroy the old keys.
1344 * @param cls Closure (Tunnel for which to finish the KX).
1345 * @param tc Task context.
1348 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1350 struct CadetTunnel *t = cls;
1352 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1354 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1356 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1360 GNUNET_free (t->kx_ctx);
1366 * Destroy a Key eXchange context for the tunnel. This function only schedules
1367 * the destruction, the freeing of the memory (and clearing of old key material)
1368 * happens after a delay!
1370 * @param t Tunnel whose KX ctx to destroy.
1373 destroy_kx_ctx (struct CadetTunnel *t)
1375 struct GNUNET_TIME_Relative delay;
1377 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1380 if (is_key_null (&t->kx_ctx->e_key_old))
1382 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1386 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1387 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1389 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1395 * Pick a connection on which send the next data message.
1397 * @param t Tunnel on which to send the message.
1399 * @return The connection on which to send the next message.
1401 static struct CadetConnection *
1402 tunnel_get_connection (struct CadetTunnel *t)
1404 struct CadetTConnection *iter;
1405 struct CadetConnection *best;
1407 unsigned int lowest_q;
1409 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1411 lowest_q = UINT_MAX;
1412 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1414 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1415 GCC_2s (iter->c), GCC_get_state (iter->c));
1416 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1418 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1419 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1427 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1433 * Callback called when a queued message is sent.
1435 * Calculates the average time and connection packet tracking.
1437 * @param cls Closure (TunnelQueue handle).
1438 * @param c Connection this message was on.
1439 * @param q Connection queue handle (unused).
1440 * @param type Type of message sent.
1441 * @param fwd Was this a FWD going message?
1442 * @param size Size of the message.
1445 tun_message_sent (void *cls,
1446 struct CadetConnection *c,
1447 struct CadetConnectionQueue *q,
1448 uint16_t type, int fwd, size_t size)
1450 struct CadetTunnelQueue *qt = cls;
1451 struct CadetTunnel *t;
1453 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1455 GNUNET_assert (NULL != qt->cont);
1456 t = NULL == c ? NULL : GCC_get_tunnel (c);
1457 qt->cont (qt->cont_cls, t, qt, type, size);
1463 count_queued_data (const struct CadetTunnel *t)
1465 struct CadetTunnelDelayed *iter;
1468 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1475 * Delete a queued message: either was sent or the channel was destroyed
1476 * before the tunnel's key exchange had a chance to finish.
1478 * @param tqd Delayed queue handle.
1481 unqueue_data (struct CadetTunnelDelayed *tqd)
1483 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1489 * Cache a message to be sent once tunnel is online.
1491 * @param t Tunnel to hold the message.
1492 * @param msg Message itself (copy will be made).
1494 static struct CadetTunnelDelayed *
1495 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1497 struct CadetTunnelDelayed *tqd;
1498 uint16_t size = ntohs (msg->size);
1500 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1502 if (GNUNET_YES == is_ready (t))
1508 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1511 memcpy (&tqd[1], msg, size);
1512 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1518 * Sends an already built message on a tunnel, encrypting it and
1519 * choosing the best connection.
1521 * @param message Message to send. Function modifies it.
1522 * @param t Tunnel on which this message is transmitted.
1523 * @param c Connection to use (autoselect if NULL).
1524 * @param force Force the tunnel to take the message (buffer overfill).
1525 * @param cont Continuation to call once message is really sent.
1526 * @param cont_cls Closure for @c cont.
1527 * @param existing_q In case this a transmission of previously queued data,
1528 * this should be TunnelQueue given to the client.
1531 * @return Handle to cancel message.
1532 * NULL if @c cont is NULL or an error happens and message is dropped.
1534 static struct CadetTunnelQueue *
1535 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1536 struct CadetTunnel *t, struct CadetConnection *c,
1537 int force, GCT_sent cont, void *cont_cls,
1538 struct CadetTunnelQueue *existing_q)
1540 struct GNUNET_MessageHeader *msg;
1541 struct GNUNET_CADET_Encrypted *otr_msg;
1542 struct GNUNET_CADET_AX *ax_msg;
1543 struct CadetTunnelQueue *tq;
1544 size_t size = ntohs (message->size);
1545 const uint16_t max_overhead = sizeof (struct GNUNET_CADET_Encrypted)
1546 + sizeof (struct GNUNET_CADET_AX);
1547 char cbuf[max_overhead + size];
1554 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1556 if (GNUNET_NO == is_ready (t))
1558 struct CadetTunnelDelayed *tqd;
1559 /* A non null existing_q indicates sending of queued data.
1560 * Should only happen after tunnel becomes ready.
1562 GNUNET_assert (NULL == existing_q);
1563 tqd = queue_data (t, message);
1566 tq = GNUNET_new (struct CadetTunnelQueue);
1570 tq->cont_cls = cont_cls;
1574 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1576 if (CADET_Axolotl == t->enc_type)
1578 ax_msg = (struct GNUNET_CADET_AX *) cbuf;
1579 msg = &ax_msg->header;
1580 msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1581 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_AX);
1582 esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1583 ax_msg->Ns = htonl (t->ax->Ns++);
1584 ax_msg->PNs = htonl (t->ax->PNs);
1585 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1586 t_h_encrypt (t, ax_msg);
1587 t_hmac (&ax_msg->Ns, AX_HEADER_SIZE, 0, &t->ax->HKs, &ax_msg->hmac);
1591 otr_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1592 msg = &otr_msg->header;
1593 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1595 esize = t_encrypt (t, &otr_msg[1], message, size, iv, GNUNET_NO);
1596 t_hmac (&otr_msg[1], size, iv, select_key (t), &otr_msg->hmac);
1597 msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1598 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1600 GNUNET_assert (esize == size);
1603 c = tunnel_get_connection (t);
1606 /* Why is tunnel 'ready'? Should have been queued! */
1607 if (NULL != t->destroy_task)
1610 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1612 return NULL; /* Drop... */
1616 type = ntohs (message->type);
1619 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1620 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1621 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1622 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1624 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1626 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1627 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1628 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1629 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1630 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1634 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1636 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1638 fwd = GCC_is_origin (c, GNUNET_YES);
1642 GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type,
1643 mid, c, fwd, force, NULL, NULL));
1646 if (NULL == existing_q)
1648 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1655 tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1656 &tun_message_sent, tq);
1657 GNUNET_assert (NULL != tq->cq);
1659 tq->cont_cls = cont_cls;
1666 * Send all cached messages that we can, tunnel is online.
1668 * @param t Tunnel that holds the messages. Cannot be loopback.
1671 send_queued_data (struct CadetTunnel *t)
1673 struct CadetTunnelDelayed *tqd;
1674 struct CadetTunnelDelayed *next;
1677 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1679 if (GCT_is_loopback (t))
1685 if (GNUNET_NO == is_ready (t))
1687 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1688 estate2s (t->estate), cstate2s (t->cstate));
1692 room = GCT_get_connections_buffer (t);
1693 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1694 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1695 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1697 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1700 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1701 tqd->t, NULL, GNUNET_YES,
1702 NULL != tqd->tq ? tqd->tq->cont : NULL,
1703 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1707 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1712 * Callback called when a queued message is sent.
1714 * @param cls Closure.
1715 * @param c Connection this message was on.
1716 * @param type Type of message sent.
1717 * @param fwd Was this a FWD going message?
1718 * @param size Size of the message.
1721 ephm_sent (void *cls,
1722 struct CadetConnection *c,
1723 struct CadetConnectionQueue *q,
1724 uint16_t type, int fwd, size_t size)
1726 struct CadetTunnel *t = cls;
1727 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
1732 * Callback called when a queued message is sent.
1734 * @param cls Closure.
1735 * @param c Connection this message was on.
1736 * @param type Type of message sent.
1737 * @param fwd Was this a FWD going message?
1738 * @param size Size of the message.
1741 pong_sent (void *cls,
1742 struct CadetConnection *c,
1743 struct CadetConnectionQueue *q,
1744 uint16_t type, int fwd, size_t size)
1746 struct CadetTunnel *t = cls;
1747 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
1753 * Sends key exchange message on a tunnel, choosing the best connection.
1754 * Should not be called on loopback tunnels.
1756 * @param t Tunnel on which this message is transmitted.
1757 * @param message Message to send. Function modifies it.
1759 * @return Handle to the message in the connection queue.
1761 static struct CadetConnectionQueue *
1762 send_kx (struct CadetTunnel *t,
1763 const struct GNUNET_MessageHeader *message)
1765 struct CadetConnection *c;
1766 struct GNUNET_CADET_KX *msg;
1767 size_t size = ntohs (message->size);
1768 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1773 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1775 /* Avoid loopback. */
1776 if (GCT_is_loopback (t))
1781 type = ntohs (message->type);
1783 /* Even if tunnel is "being destroyed", send anyway.
1784 * Could be a response to a rekey initiated by remote peer,
1785 * who is trying to create a new channel!
1788 /* Must have a connection, or be looking for one. */
1789 if (NULL == t->connection_head)
1791 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
1792 if (CADET_TUNNEL_SEARCHING != t->cstate)
1795 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1796 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
1801 msg = (struct GNUNET_CADET_KX *) cbuf;
1802 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1803 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1804 c = tunnel_get_connection (t);
1807 if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
1810 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1816 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1817 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
1818 GNUNET_assert (NULL == t->ephm_h);
1821 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1822 GNUNET_assert (NULL == t->pong_h);
1827 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
1830 memcpy (&msg[1], message, size);
1832 fwd = GCC_is_origin (c, GNUNET_YES);
1834 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
1841 * Send the ephemeral key on a tunnel.
1843 * @param t Tunnel on which to send the key.
1846 send_ephemeral (struct CadetTunnel *t)
1848 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1849 if (NULL != t->ephm_h)
1851 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1855 otr_kx_msg.sender_status = htonl (t->estate);
1856 otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1857 otr_kx_msg.nonce = t->kx_ctx->challenge;
1858 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", otr_kx_msg.nonce);
1859 t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
1860 ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
1861 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", otr_kx_msg.nonce);
1862 t->ephm_h = send_kx (t, &otr_kx_msg.header);
1867 * Send a pong message on a tunnel.
1869 * @param t Tunnel on which to send the pong.
1870 * @param challenge Value sent in the ping that we have to send back.
1873 send_pong (struct CadetTunnel *t, uint32_t challenge)
1875 struct GNUNET_CADET_KX_Pong msg;
1877 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1878 if (NULL != t->pong_h)
1880 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1883 msg.header.size = htons (sizeof (msg));
1884 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1885 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1886 msg.nonce = challenge;
1887 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1888 t_encrypt (t, &msg.nonce, &msg.nonce,
1889 sizeof (msg.nonce), msg.iv, GNUNET_YES);
1890 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1892 t->pong_h = send_kx (t, &msg.header);
1897 * Initiate a rekey with the remote peer.
1899 * @param cls Closure (tunnel).
1900 * @param tc TaskContext.
1903 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1905 struct CadetTunnel *t = cls;
1907 t->rekey_task = NULL;
1909 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1910 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1913 GNUNET_assert (NULL != t->kx_ctx);
1914 struct GNUNET_TIME_Relative duration;
1916 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1917 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1918 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1920 // FIXME make duration of old keys configurable
1921 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1923 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
1924 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1925 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1932 case CADET_TUNNEL_KEY_UNINITIALIZED:
1933 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
1936 case CADET_TUNNEL_KEY_SENT:
1939 case CADET_TUNNEL_KEY_OK:
1941 * - state should have changed during rekey_iterator
1942 * - task should have been canceled at pong_handle
1945 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1948 case CADET_TUNNEL_KEY_PING:
1949 case CADET_TUNNEL_KEY_REKEY:
1953 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1956 // FIXME exponential backoff
1957 struct GNUNET_TIME_Relative delay;
1959 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1960 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1961 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1962 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1963 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1968 * Our ephemeral key has changed, create new session key on all tunnels.
1970 * Each tunnel will start the Key Exchange with a random delay between
1971 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1972 * per second, on average.
1974 * @param cls Closure (size of the hashmap).
1975 * @param key Current public key.
1976 * @param value Value in the hash map (tunnel).
1978 * @return #GNUNET_YES, so we should continue to iterate,
1981 rekey_iterator (void *cls,
1982 const struct GNUNET_PeerIdentity *key,
1985 struct CadetTunnel *t = value;
1986 struct GNUNET_TIME_Relative delay;
1987 long n = (long) cls;
1990 if (NULL != t->rekey_task)
1993 if (GNUNET_YES == GCT_is_loopback (t))
1996 if (CADET_OTR != t->enc_type)
1999 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2000 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2001 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2003 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2010 * Create a new ephemeral key and key message, schedule next rekeying.
2012 * @param cls Closure (unused).
2013 * @param tc TaskContext.
2016 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2018 struct GNUNET_TIME_Absolute time;
2023 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2026 GNUNET_free_non_null (otr_ephemeral_key);
2027 otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2029 time = GNUNET_TIME_absolute_get ();
2030 otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2031 time = GNUNET_TIME_absolute_add (time, rekey_period);
2032 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2033 otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2034 GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2035 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2036 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
2038 GNUNET_assert (GNUNET_OK ==
2039 GNUNET_CRYPTO_eddsa_sign (id_key,
2040 &otr_kx_msg.purpose,
2041 &otr_kx_msg.signature));
2043 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2044 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2046 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2047 &global_otr_rekey, NULL);
2052 * Called only on shutdown, destroy every tunnel.
2054 * @param cls Closure (unused).
2055 * @param key Current public key.
2056 * @param value Value in the hash map (tunnel).
2058 * @return #GNUNET_YES, so we should continue to iterate,
2061 destroy_iterator (void *cls,
2062 const struct GNUNET_PeerIdentity *key,
2065 struct CadetTunnel *t = value;
2067 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2074 * Notify remote peer that we don't know a channel he is talking about,
2075 * probably CHANNEL_DESTROY was missed.
2077 * @param t Tunnel on which to notify.
2078 * @param gid ID of the channel.
2081 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2083 struct GNUNET_CADET_ChannelManage msg;
2085 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2086 msg.header.size = htons (sizeof (msg));
2087 msg.chid = htonl (gid);
2089 LOG (GNUNET_ERROR_TYPE_DEBUG,
2090 "WARNING destroying unknown channel %u on tunnel %s\n",
2092 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2097 * Demultiplex data per channel and call appropriate channel handler.
2099 * @param t Tunnel on which the data came.
2100 * @param msg Data message.
2101 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2102 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2103 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2104 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2107 handle_data (struct CadetTunnel *t,
2108 const struct GNUNET_CADET_Data *msg,
2111 struct CadetChannel *ch;
2115 size = ntohs (msg->header.size);
2117 sizeof (struct GNUNET_CADET_Data) +
2118 sizeof (struct GNUNET_MessageHeader))
2123 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2124 GC_m2s (ntohs (msg[1].header.type)));
2127 ch = GCT_get_channel (t, ntohl (msg->chid));
2130 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2132 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2134 send_channel_destroy (t, ntohl (msg->chid));
2138 GCCH_handle_data (ch, msg, fwd);
2143 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2145 * @param t Tunnel on which the DATA ACK came.
2146 * @param msg DATA ACK message.
2147 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2148 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2149 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2150 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2153 handle_data_ack (struct CadetTunnel *t,
2154 const struct GNUNET_CADET_DataACK *msg,
2157 struct CadetChannel *ch;
2161 size = ntohs (msg->header.size);
2162 if (size != sizeof (struct GNUNET_CADET_DataACK))
2169 ch = GCT_get_channel (t, ntohl (msg->chid));
2172 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2174 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2179 GCCH_handle_data_ack (ch, msg, fwd);
2184 * Handle channel create.
2186 * @param t Tunnel on which the data came.
2187 * @param msg Data message.
2190 handle_ch_create (struct CadetTunnel *t,
2191 const struct GNUNET_CADET_ChannelCreate *msg)
2193 struct CadetChannel *ch;
2197 size = ntohs (msg->header.size);
2198 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2205 ch = GCT_get_channel (t, ntohl (msg->chid));
2206 if (NULL != ch && ! GCT_is_loopback (t))
2208 /* Probably a retransmission, safe to ignore */
2209 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2211 ch = GCCH_handle_create (t, msg);
2213 GCT_add_channel (t, ch);
2219 * Handle channel NACK: check correctness and call channel handler for NACKs.
2221 * @param t Tunnel on which the NACK came.
2222 * @param msg NACK message.
2225 handle_ch_nack (struct CadetTunnel *t,
2226 const struct GNUNET_CADET_ChannelManage *msg)
2228 struct CadetChannel *ch;
2232 size = ntohs (msg->header.size);
2233 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2240 ch = GCT_get_channel (t, ntohl (msg->chid));
2243 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2245 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2250 GCCH_handle_nack (ch);
2255 * Handle a CHANNEL ACK (SYNACK/ACK).
2257 * @param t Tunnel on which the CHANNEL ACK came.
2258 * @param msg CHANNEL ACK message.
2259 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2260 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2261 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2262 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2265 handle_ch_ack (struct CadetTunnel *t,
2266 const struct GNUNET_CADET_ChannelManage *msg,
2269 struct CadetChannel *ch;
2273 size = ntohs (msg->header.size);
2274 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2281 ch = GCT_get_channel (t, ntohl (msg->chid));
2284 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2286 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2291 GCCH_handle_ack (ch, msg, fwd);
2296 * Handle a channel destruction message.
2298 * @param t Tunnel on which the message came.
2299 * @param msg Channel destroy message.
2300 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2301 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2302 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2303 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2306 handle_ch_destroy (struct CadetTunnel *t,
2307 const struct GNUNET_CADET_ChannelManage *msg,
2310 struct CadetChannel *ch;
2314 size = ntohs (msg->header.size);
2315 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2322 ch = GCT_get_channel (t, ntohl (msg->chid));
2325 /* Probably a retransmission, safe to ignore */
2329 GCCH_handle_destroy (ch, msg, fwd);
2334 * Create a new Axolotl ephemeral (ratchet) key.
2339 new_ephemeral (struct CadetTunnel *t)
2341 GNUNET_free_non_null (t->ax->DHRs);
2342 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2347 * Free Axolotl data.
2352 destroy_ax (struct CadetTunnel *t)
2357 GNUNET_free_non_null (t->ax->DHRs);
2358 GNUNET_free_non_null (t->ax->kx_0);
2360 GNUNET_free (t->ax);
2367 * The peer's ephemeral key has changed: update the symmetrical keys.
2369 * @param t Tunnel this message came on.
2370 * @param msg Key eXchange message.
2373 handle_ephemeral (struct CadetTunnel *t,
2374 const struct GNUNET_CADET_KX_Ephemeral *msg)
2376 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2378 if (GNUNET_OK != check_ephemeral (t, msg))
2380 GNUNET_break_op (0);
2384 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2388 t->enc_type = CADET_OTR;
2389 if (NULL != t->rekey_task)
2390 GNUNET_SCHEDULER_cancel (t->rekey_task);
2392 rekey_tunnel (t, NULL);
2396 * If the key is different from what we know, derive the new E/D keys.
2397 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2399 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2400 sizeof (msg->ephemeral_key)))
2402 #if DUMP_KEYS_TO_STDERR
2403 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2404 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2405 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2406 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2408 t->peers_ephemeral_key = msg->ephemeral_key;
2412 if (CADET_TUNNEL_KEY_OK == t->estate)
2414 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2416 if (NULL != t->rekey_task)
2417 GNUNET_SCHEDULER_cancel (t->rekey_task);
2418 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2420 if (CADET_TUNNEL_KEY_SENT == t->estate)
2422 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2424 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2427 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2431 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2432 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2433 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2434 send_pong (t, nonce);
2440 * Peer has answer to our challenge.
2441 * If answer is successful, consider the key exchange finished and clean
2442 * up all related state.
2444 * @param t Tunnel this message came on.
2445 * @param msg Key eXchange Pong message.
2448 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2452 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2453 if (NULL == t->rekey_task)
2455 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2458 if (NULL == t->kx_ctx)
2460 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2464 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2465 if (challenge != t->kx_ctx->challenge)
2467 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2468 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2469 challenge, msg->nonce, t->kx_ctx->challenge);
2473 GNUNET_SCHEDULER_cancel (t->rekey_task);
2474 t->rekey_task = NULL;
2476 /* Don't free the old keys right away, but after a delay.
2477 * Rationale: the KX could have happened over a very fast connection,
2478 * with payload traffic still signed with the old key stuck in a slower
2480 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2484 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2489 * Handle Axolotl handshake.
2491 * @param t Tunnel this message came on.
2492 * @param msg Key eXchange Pong message.
2495 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2497 struct CadetTunnelAxolotl *ax;
2498 struct GNUNET_HashCode key_material[3];
2499 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2500 const struct GNUNET_CRYPTO_EcdhePublicKey *pub;
2501 const struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
2502 const char salt[] = "CADET Axolotl salt";
2503 const struct GNUNET_PeerIdentity *pid;
2506 LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2510 /* Something is wrong if ax is NULL. Whose fault it is? */
2511 GNUNET_break_op (CADET_OTR == t->enc_type);
2512 GNUNET_break (CADET_Axolotl == t->enc_type);
2516 if (GNUNET_OK != GCP_check_key (t->peer, &msg->permanent_key,
2517 &msg->purpose, &msg->signature))
2519 GNUNET_break_op (0);
2523 pid = GCT_get_destination (t);
2524 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2525 am_I_alice = GNUNET_YES;
2526 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2527 am_I_alice = GNUNET_NO;
2530 GNUNET_break_op (0);
2534 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2537 ax->DHRr = msg->ratchet_key;
2540 if (GNUNET_YES == am_I_alice)
2542 priv = ax_key; /* A */
2543 pub = &msg->ephemeral_key; /* B0 */
2547 priv = ax->kx_0; /* B0 */
2548 pub = &msg->permanent_key; /* A */
2550 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[0]);
2553 if (GNUNET_YES == am_I_alice)
2555 priv = ax->kx_0; /* A0 */
2556 pub = &msg->permanent_key; /* B */
2560 priv = ax_key; /* B */
2561 pub = &msg->ephemeral_key; /* A0 */
2563 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[1]);
2566 priv = ax->kx_0; /* A0 or B0 */
2567 pub = &msg->ephemeral_key; /* B0 or A0 */
2568 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[2]);
2570 #if DUMP_KEYS_TO_STDERR
2573 for (i = 0; i < 3; i++)
2574 LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2575 i, GNUNET_h2s (&key_material[i]));
2580 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2581 salt, sizeof (salt),
2582 &key_material, sizeof (key_material), NULL);
2585 if (GNUNET_YES == am_I_alice)
2591 ax->ratchet_flag = GNUNET_YES;
2599 ax->ratchet_flag = GNUNET_NO;
2601 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2606 * Demultiplex by message type and call appropriate handler for a message
2607 * towards a channel of a local tunnel.
2609 * @param t Tunnel this message came on.
2610 * @param msgh Message header.
2611 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2612 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2613 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2614 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2617 handle_decrypted (struct CadetTunnel *t,
2618 const struct GNUNET_MessageHeader *msgh,
2623 type = ntohs (msgh->type);
2624 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2628 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2629 /* Do nothing, connection aleady got updated. */
2630 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2633 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2634 /* Don't send hop ACK, wait for client to ACK */
2635 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2638 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2639 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2642 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2643 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2646 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2647 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
2650 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2651 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2654 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2655 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2659 GNUNET_break_op (0);
2660 LOG (GNUNET_ERROR_TYPE_WARNING,
2661 "end-to-end message not known (%u)\n",
2662 ntohs (msgh->type));
2663 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2667 /******************************************************************************/
2668 /******************************** API ***********************************/
2669 /******************************************************************************/
2671 * Decrypt old format and demultiplex by message type. Call appropriate handler
2672 * for a message towards a channel of a local tunnel.
2674 * @param t Tunnel this message came on.
2675 * @param msg Message header.
2678 GCT_handle_encrypted (struct CadetTunnel *t,
2679 const struct GNUNET_MessageHeader *msg)
2681 size_t size = ntohs (msg->size);
2682 size_t payload_size;
2685 uint16_t type = ntohs (msg->type);
2686 struct GNUNET_MessageHeader *msgh;
2689 if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
2691 const struct GNUNET_CADET_Encrypted *emsg;
2693 emsg = (struct GNUNET_CADET_Encrypted *) msg;
2694 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2695 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
2696 emsg->iv, &emsg->hmac);
2698 else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
2700 const struct GNUNET_CADET_AX *emsg;
2702 emsg = (struct GNUNET_CADET_AX *) msg;
2703 payload_size = size - sizeof (struct GNUNET_CADET_AX);
2704 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, &emsg[1],
2705 payload_size, &emsg->hmac);
2708 if (-1 == decrypted_size)
2710 GNUNET_break_op (0);
2715 while (off < decrypted_size)
2719 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2720 msize = ntohs (msgh->size);
2721 if (msize < sizeof (struct GNUNET_MessageHeader))
2723 GNUNET_break_op (0);
2726 handle_decrypted (t, msgh, GNUNET_SYSERR);
2733 * Demultiplex an encapsulated KX message by message type.
2735 * @param t Tunnel on which the message came.
2736 * @param message Payload of KX message.
2739 GCT_handle_kx (struct CadetTunnel *t,
2740 const struct GNUNET_MessageHeader *message)
2744 type = ntohs (message->type);
2745 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
2748 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2749 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
2752 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2753 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
2756 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2757 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
2761 GNUNET_break_op (0);
2762 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
2767 * Initialize the tunnel subsystem.
2769 * @param c Configuration handle.
2770 * @param key ECC private key, to derive all other keys and do crypto.
2773 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2774 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2776 int expected_overhead;
2778 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2780 expected_overhead = 0;
2781 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
2782 expected_overhead += sizeof (struct GNUNET_CADET_Data);
2783 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
2784 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2787 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2790 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2791 "CADET", "DEFAULT_TTL", "USING DEFAULT");
2795 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2798 rekey_period = GNUNET_TIME_UNIT_DAYS;
2803 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
2804 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2805 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2806 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2807 otr_kx_msg.origin_identity = my_full_id;
2808 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
2810 ax_key = GNUNET_CRYPTO_ecdhe_key_create ();
2811 GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &ax_identity.permanent_key);
2812 ax_identity.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_AXKX);
2813 ax_identity.purpose.size = htonl (ax_purpose_size ());
2814 GNUNET_assert (GNUNET_OK ==
2815 GNUNET_CRYPTO_eddsa_sign (id_key,
2816 &ax_identity.purpose,
2817 &ax_identity.signature));
2819 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2824 * Shut down the tunnel subsystem.
2829 if (NULL != rekey_task)
2831 GNUNET_SCHEDULER_cancel (rekey_task);
2834 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2835 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2836 GNUNET_free (ax_key);
2843 * @param destination Peer this tunnel is towards.
2845 struct CadetTunnel *
2846 GCT_new (struct CadetPeer *destination)
2848 struct CadetTunnel *t;
2850 t = GNUNET_new (struct CadetTunnel);
2852 t->peer = destination;
2855 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2856 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2862 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
2864 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2870 * Change the tunnel's connection state.
2872 * @param t Tunnel whose connection state to change.
2873 * @param cstate New connection state.
2876 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2880 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2881 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2882 if (myid != GCP_get_short_id (t->peer) &&
2883 CADET_TUNNEL_READY != t->cstate &&
2884 CADET_TUNNEL_READY == cstate)
2887 if (CADET_TUNNEL_KEY_OK == t->estate)
2889 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2890 send_queued_data (t);
2892 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2894 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
2899 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
2904 if (CADET_TUNNEL_READY == cstate
2905 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2907 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2908 GCP_stop_search (t->peer);
2914 * Change the tunnel encryption state.
2916 * @param t Tunnel whose encryption state to change, or NULL.
2917 * @param state New encryption state.
2920 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2922 enum CadetTunnelEState old;
2929 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2930 GCP_2s (t->peer), estate2s (old));
2931 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2932 GCP_2s (t->peer), estate2s (t->estate));
2934 /* Send queued data if enc state changes to OK */
2935 if (myid != GCP_get_short_id (t->peer) &&
2936 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
2938 send_queued_data (t);
2944 * @brief Check if tunnel has too many connections, and remove one if necessary.
2946 * Currently this means the newest connection, unless it is a direct one.
2947 * Implemented as a task to avoid freeing a connection that is in the middle
2948 * of being created/processed.
2950 * @param cls Closure (Tunnel to check).
2951 * @param tc Task context.
2954 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2956 struct CadetTunnel *t = cls;
2958 t->trim_connections_task = NULL;
2960 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2963 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2965 struct CadetTConnection *iter;
2966 struct CadetTConnection *c;
2968 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2970 if ((iter->created.abs_value_us > c->created.abs_value_us)
2971 && GNUNET_NO == GCC_is_direct (iter->c))
2978 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2980 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2993 * Add a connection to a tunnel.
2996 * @param c Connection.
2999 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3001 struct CadetTConnection *aux;
3003 GNUNET_assert (NULL != c);
3005 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3006 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3007 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3011 aux = GNUNET_new (struct CadetTConnection);
3013 aux->created = GNUNET_TIME_absolute_get ();
3015 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3017 if (CADET_TUNNEL_SEARCHING == t->cstate)
3018 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3020 if (NULL != t->trim_connections_task)
3021 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3026 * Remove a connection from a tunnel.
3029 * @param c Connection.
3032 GCT_remove_connection (struct CadetTunnel *t,
3033 struct CadetConnection *c)
3035 struct CadetTConnection *aux;
3036 struct CadetTConnection *next;
3039 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3040 GCC_2s (c), GCT_2s (t));
3041 for (aux = t->connection_head; aux != NULL; aux = next)
3046 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3051 conns = GCT_count_connections (t);
3053 && NULL == t->destroy_task
3054 && CADET_TUNNEL_SHUTDOWN != t->cstate
3055 && GNUNET_NO == shutting_down)
3057 if (0 == GCT_count_any_connections (t))
3058 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3060 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3063 /* Start new connections if needed */
3064 if (CONNECTIONS_PER_TUNNEL > conns
3065 && NULL == t->destroy_task
3066 && CADET_TUNNEL_SHUTDOWN != t->cstate
3067 && GNUNET_NO == shutting_down)
3069 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
3070 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3074 /* If not marked as ready, no change is needed */
3075 if (CADET_TUNNEL_READY != t->cstate)
3078 /* Check if any connection is ready to maintain cstate */
3079 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3080 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3086 * Add a channel to a tunnel.
3089 * @param ch Channel.
3092 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3094 struct CadetTChannel *aux;
3096 GNUNET_assert (NULL != ch);
3098 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3100 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3102 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
3107 aux = GNUNET_new (struct CadetTChannel);
3109 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3110 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3112 if (NULL != t->destroy_task)
3114 GNUNET_SCHEDULER_cancel (t->destroy_task);
3115 t->destroy_task = NULL;
3116 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3122 * Remove a channel from a tunnel.
3125 * @param ch Channel.
3128 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3130 struct CadetTChannel *aux;
3132 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3133 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3137 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3138 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3147 * Search for a channel by global ID.
3149 * @param t Tunnel containing the channel.
3150 * @param chid Public channel number.
3152 * @return channel handler, NULL if doesn't exist
3154 struct CadetChannel *
3155 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3157 struct CadetTChannel *iter;
3162 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3164 if (GCCH_get_id (iter->ch) == chid)
3168 return NULL == iter ? NULL : iter->ch;
3173 * @brief Destroy a tunnel and free all resources.
3175 * Should only be called a while after the tunnel has been marked as destroyed,
3176 * in case there is a new channel added to the same peer shortly after marking
3177 * the tunnel. This way we avoid a new public key handshake.
3179 * @param cls Closure (tunnel to destroy).
3180 * @param tc Task context.
3183 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3185 struct CadetTunnel *t = cls;
3186 struct CadetTConnection *iter;
3188 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3189 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3191 LOG (GNUNET_ERROR_TYPE_WARNING,
3192 "Not destroying tunnel, due to shutdown. "
3193 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3196 t->destroy_task = NULL;
3197 t->cstate = CADET_TUNNEL_SHUTDOWN;
3199 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3201 GCC_send_destroy (iter->c);
3208 * Tunnel is empty: destroy it.
3210 * Notifies all connections about the destruction.
3212 * @param t Tunnel to destroy.
3215 GCT_destroy_empty (struct CadetTunnel *t)
3217 if (GNUNET_YES == shutting_down)
3218 return; /* Will be destroyed immediately anyway */
3220 if (NULL != t->destroy_task)
3222 LOG (GNUNET_ERROR_TYPE_WARNING,
3223 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3225 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3227 /* should never happen, tunnel can only become empty once, and the
3228 * task identifier should be NO_TASK (cleaned when the tunnel was created
3229 * or became un-empty)
3234 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3237 // FIXME make delay a config option
3238 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3239 &delayed_destroy, t);
3240 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3241 t, t->destroy_task);
3246 * Destroy tunnel if empty (no more channels).
3248 * @param t Tunnel to destroy if empty.
3251 GCT_destroy_if_empty (struct CadetTunnel *t)
3253 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3254 if (0 < GCT_count_channels (t))
3257 GCT_destroy_empty (t);
3262 * Destroy the tunnel.
3264 * This function does not generate any warning traffic to clients or peers.
3267 * Cancel messages belonging to this tunnel queued to neighbors.
3268 * Free any allocated resources linked to the tunnel.
3270 * @param t The tunnel to destroy.
3273 GCT_destroy (struct CadetTunnel *t)
3275 struct CadetTConnection *iter_c;
3276 struct CadetTConnection *next_c;
3277 struct CadetTChannel *iter_ch;
3278 struct CadetTChannel *next_ch;
3283 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3285 GNUNET_break (GNUNET_YES ==
3286 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3287 GCP_get_id (t->peer), t));
3289 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3291 next_c = iter_c->next;
3292 GCC_destroy (iter_c->c);
3294 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3296 next_ch = iter_ch->next;
3297 GCCH_destroy (iter_ch->ch);
3298 /* Should only happen on shutdown, but it's ok. */
3301 if (NULL != t->destroy_task)
3303 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3304 GNUNET_SCHEDULER_cancel (t->destroy_task);
3305 t->destroy_task = NULL;
3308 if (NULL != t->trim_connections_task)
3310 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3311 t->trim_connections_task);
3312 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3313 t->trim_connections_task = NULL;
3316 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3317 GCP_set_tunnel (t->peer, NULL);
3319 if (NULL != t->rekey_task)
3321 GNUNET_SCHEDULER_cancel (t->rekey_task);
3322 t->rekey_task = NULL;
3324 if (NULL != t->kx_ctx)
3326 if (NULL != t->kx_ctx->finish_task)
3327 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3328 GNUNET_free (t->kx_ctx);
3339 * @brief Use the given path for the tunnel.
3340 * Update the next and prev hops (and RCs).
3341 * (Re)start the path refresh in case the tunnel is locally owned.
3343 * @param t Tunnel to update.
3344 * @param p Path to use.
3346 * @return Connection created.
3348 struct CadetConnection *
3349 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3351 struct CadetConnection *c;
3352 struct GNUNET_CADET_Hash cid;
3353 unsigned int own_pos;
3355 if (NULL == t || NULL == p)
3361 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3367 for (own_pos = 0; own_pos < p->length; own_pos++)
3369 if (p->peers[own_pos] == myid)
3372 if (own_pos >= p->length)
3374 GNUNET_break_op (0);
3378 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3379 c = GCC_new (&cid, t, p, own_pos);
3382 /* Path was flawed */
3385 GCT_add_connection (t, c);
3391 * Count all created connections of a tunnel. Not necessarily ready connections!
3393 * @param t Tunnel on which to count.
3395 * @return Number of connections created, either being established or ready.
3398 GCT_count_any_connections (struct CadetTunnel *t)
3400 struct CadetTConnection *iter;
3406 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3414 * Count established (ready) connections of a tunnel.
3416 * @param t Tunnel on which to count.
3418 * @return Number of connections.
3421 GCT_count_connections (struct CadetTunnel *t)
3423 struct CadetTConnection *iter;
3429 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3430 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3438 * Count channels of a tunnel.
3440 * @param t Tunnel on which to count.
3442 * @return Number of channels.
3445 GCT_count_channels (struct CadetTunnel *t)
3447 struct CadetTChannel *iter;
3450 for (count = 0, iter = t->channel_head;
3452 iter = iter->next, count++) /* skip */;
3459 * Get the connectivity state of a tunnel.
3463 * @return Tunnel's connectivity state.
3465 enum CadetTunnelCState
3466 GCT_get_cstate (struct CadetTunnel *t)
3471 return (enum CadetTunnelCState) -1;
3478 * Get the encryption state of a tunnel.
3482 * @return Tunnel's encryption state.
3484 enum CadetTunnelEState
3485 GCT_get_estate (struct CadetTunnel *t)
3490 return (enum CadetTunnelEState) -1;
3496 * Get the maximum buffer space for a tunnel towards a local client.
3500 * @return Biggest buffer space offered by any channel in the tunnel.
3503 GCT_get_channels_buffer (struct CadetTunnel *t)
3505 struct CadetTChannel *iter;
3506 unsigned int buffer;
3507 unsigned int ch_buf;
3509 if (NULL == t->channel_head)
3511 /* Probably getting buffer for a channel create/handshake. */
3512 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3517 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3519 ch_buf = get_channel_buffer (iter);
3520 if (ch_buf > buffer)
3528 * Get the total buffer space for a tunnel for P2P traffic.
3532 * @return Buffer space offered by all connections in the tunnel.
3535 GCT_get_connections_buffer (struct CadetTunnel *t)
3537 struct CadetTConnection *iter;
3538 unsigned int buffer;
3540 if (GNUNET_NO == is_ready (t))
3542 if (count_queued_data (t) > 3)
3549 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3551 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3555 buffer += get_connection_buffer (iter);
3563 * Get the tunnel's destination.
3567 * @return ID of the destination peer.
3569 const struct GNUNET_PeerIdentity *
3570 GCT_get_destination (struct CadetTunnel *t)
3572 return GCP_get_id (t->peer);
3577 * Get the tunnel's next free global channel ID.
3581 * @return GID of a channel free to use.
3584 GCT_get_next_chid (struct CadetTunnel *t)
3586 CADET_ChannelNumber chid;
3587 CADET_ChannelNumber mask;
3590 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3591 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3592 * If peer's ID is bigger, start at 0x4... bit 30 = 1
3594 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3599 t->next_chid |= mask;
3601 while (NULL != GCT_get_channel (t, t->next_chid))
3603 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3604 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3605 t->next_chid |= mask;
3607 chid = t->next_chid;
3608 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3609 t->next_chid |= mask;
3616 * Send ACK on one or more channels due to buffer in connections.
3618 * @param t Channel which has some free buffer space.
3621 GCT_unchoke_channels (struct CadetTunnel *t)
3623 struct CadetTChannel *iter;
3624 unsigned int buffer;
3625 unsigned int channels = GCT_count_channels (t);
3626 unsigned int choked_n;
3627 struct CadetChannel *choked[channels];
3629 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3630 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3631 if (NULL != t->channel_head)
3632 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3634 /* Get buffer space */
3635 buffer = GCT_get_connections_buffer (t);
3641 /* Count and remember choked channels */
3643 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3645 if (GNUNET_NO == get_channel_allowed (iter))
3647 choked[choked_n++] = iter->ch;
3651 /* Unchoke random channels */
3652 while (0 < buffer && 0 < choked_n)
3654 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3656 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3659 choked[r] = choked[choked_n];
3665 * Send ACK on one or more connections due to buffer space to the client.
3667 * Iterates all connections of the tunnel and sends ACKs appropriately.
3672 GCT_send_connection_acks (struct CadetTunnel *t)
3674 struct CadetTConnection *iter;
3677 uint32_t allow_per_connection;
3679 unsigned int buffer;
3681 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3690 if (CADET_TUNNEL_READY != t->cstate)
3693 buffer = GCT_get_channels_buffer (t);
3694 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
3696 /* Count connections, how many messages are already allowed */
3697 cs = GCT_count_connections (t);
3698 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3700 allowed += get_connection_allowed (iter);
3702 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
3704 /* Make sure there is no overflow */
3705 if (allowed > buffer)
3708 /* Authorize connections to send more data */
3709 to_allow = buffer - allowed;
3711 for (iter = t->connection_head;
3712 NULL != iter && to_allow > 0;
3715 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3716 || get_connection_allowed (iter) > 64 / 3)
3720 allow_per_connection = to_allow/cs;
3721 to_allow -= allow_per_connection;
3723 GCC_allow (iter->c, allow_per_connection,
3724 GCC_is_origin (iter->c, GNUNET_NO));
3729 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
3730 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
3736 * Cancel a previously sent message while it's in the queue.
3738 * ONLY can be called before the continuation given to the send function
3739 * is called. Once the continuation is called, the message is no longer in the
3742 * @param q Handle to the queue.
3745 GCT_cancel (struct CadetTunnelQueue *q)
3750 /* tun_message_sent() will be called and free q */
3752 else if (NULL != q->tqd)
3754 unqueue_data (q->tqd);
3756 if (NULL != q->cont)
3757 q->cont (q->cont_cls, NULL, q, 0, 0);
3768 * Sends an already built message on a tunnel, encrypting it and
3769 * choosing the best connection if not provided.
3771 * @param message Message to send. Function modifies it.
3772 * @param t Tunnel on which this message is transmitted.
3773 * @param c Connection to use (autoselect if NULL).
3774 * @param force Force the tunnel to take the message (buffer overfill).
3775 * @param cont Continuation to call once message is really sent.
3776 * @param cont_cls Closure for @c cont.
3778 * @return Handle to cancel message. NULL if @c cont is NULL.
3780 struct CadetTunnelQueue *
3781 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3782 struct CadetTunnel *t, struct CadetConnection *c,
3783 int force, GCT_sent cont, void *cont_cls)
3785 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3790 * Send an Axolotl KX message.
3792 * @param t Tunnel on which to send it.
3795 GCT_send_ax_kx (struct CadetTunnel *t)
3797 struct GNUNET_CADET_AX_KX msg;
3799 LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
3801 msg.header.size = htons (sizeof (msg));
3802 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
3803 msg.permanent_key = ax_identity.permanent_key;
3804 msg.purpose = ax_identity.purpose;
3805 msg.signature = ax_identity.signature;
3806 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
3807 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
3809 t->ephm_h = send_kx (t, &msg.header);
3810 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
3815 * Sends an already built and encrypted message on a tunnel, choosing the best
3816 * connection. Useful for re-queueing messages queued on a destroyed connection.
3818 * @param message Message to send. Function modifies it.
3819 * @param t Tunnel on which this message is transmitted.
3822 GCT_resend_message (const struct GNUNET_MessageHeader *message,
3823 struct CadetTunnel *t)
3825 struct CadetConnection *c;
3828 c = tunnel_get_connection (t);
3831 /* TODO queue in tunnel, marked as encrypted */
3832 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
3835 fwd = GCC_is_origin (c, GNUNET_YES);
3836 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
3837 GNUNET_YES, NULL, NULL));
3842 * Is the tunnel directed towards the local peer?
3846 * @return #GNUNET_YES if it is loopback.
3849 GCT_is_loopback (const struct CadetTunnel *t)
3851 return (myid == GCP_get_short_id (t->peer));
3856 * Is the tunnel this path already?
3861 * @return #GNUNET_YES a connection uses this path.
3864 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3866 struct CadetTConnection *iter;
3868 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3869 if (path_equivalent (GCC_get_path (iter->c), p))
3877 * Get a cost of a path for a tunnel considering existing connections.
3880 * @param path Candidate path.
3882 * @return Cost of the path (path length + number of overlapping nodes)
3885 GCT_get_path_cost (const struct CadetTunnel *t,
3886 const struct CadetPeerPath *path)
3888 struct CadetTConnection *iter;
3889 const struct CadetPeerPath *aux;
3890 unsigned int overlap;
3898 GNUNET_assert (NULL != t);
3900 for (i = 0; i < path->length; i++)
3902 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3904 aux = GCC_get_path (iter->c);
3908 for (j = 0; j < aux->length; j++)
3910 if (path->peers[i] == aux->peers[j])
3918 return path->length + overlap;
3923 * Get the static string for the peer this tunnel is directed.
3927 * @return Static string the destination peer's ID.
3930 GCT_2s (const struct CadetTunnel *t)
3935 return GCP_2s (t->peer);
3939 /******************************************************************************/
3940 /***************************** INFO/DEBUG *******************************/
3941 /******************************************************************************/
3944 * Log all possible info about the tunnel state.
3946 * @param t Tunnel to debug.
3947 * @param level Debug level to use.
3950 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3952 struct CadetTChannel *iterch;
3953 struct CadetTConnection *iterc;
3956 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3958 __FILE__, __FUNCTION__, __LINE__);
3962 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3963 LOG2 (level, "TTT cstate %s, estate %s\n",
3964 cstate2s (t->cstate), estate2s (t->estate));
3965 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
3966 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
3967 #if DUMP_KEYS_TO_STDERR
3968 LOG2 (level, "TTT my EPHM\t %s\n",
3969 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
3970 LOG2 (level, "TTT peers EPHM:\t %s\n",
3971 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
3972 LOG2 (level, "TTT ENC key:\t %s\n",
3973 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
3974 LOG2 (level, "TTT DEC key:\t %s\n",
3975 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
3978 LOG2 (level, "TTT OLD ENC key:\t %s\n",
3979 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
3980 LOG2 (level, "TTT OLD DEC key:\t %s\n",
3981 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
3984 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3985 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
3987 LOG2 (level, "TTT channels:\n");
3988 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
3990 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
3993 LOG2 (level, "TTT connections:\n");
3994 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
3996 GCC_debug (iterc->c, level);
3999 LOG2 (level, "TTT DEBUG TUNNEL END\n");
4004 * Iterate all tunnels.
4006 * @param iter Iterator.
4007 * @param cls Closure for @c iter.
4010 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4012 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4017 * Count all tunnels.
4019 * @return Number of tunnels to remote peers kept by this peer.
4022 GCT_count_all (void)
4024 return GNUNET_CONTAINER_multipeermap_size (tunnels);
4029 * Iterate all connections of a tunnel.
4031 * @param t Tunnel whose connections to iterate.
4032 * @param iter Iterator.
4033 * @param cls Closure for @c iter.
4036 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4038 struct CadetTConnection *ct;
4040 for (ct = t->connection_head; NULL != ct; ct = ct->next)
4046 * Iterate all channels of a tunnel.
4048 * @param t Tunnel whose channels to iterate.
4049 * @param iter Iterator.
4050 * @param cls Closure for @c iter.
4053 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4055 struct CadetTChannel *cht;
4057 for (cht = t->channel_head; NULL != cht; cht = cht->next)
4058 iter (cls, cht->ch);