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:
1631 if (CADET_Axolotl == t->enc_type)
1633 ax_msg->cid = *GCC_get_id (c);
1637 otr_msg->cid = *GCC_get_id (c);
1638 otr_msg->ttl = htonl (default_ttl);
1643 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1645 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1647 fwd = GCC_is_origin (c, GNUNET_YES);
1651 GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type,
1652 mid, c, fwd, force, NULL, NULL));
1655 if (NULL == existing_q)
1657 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1664 tq->cq = GCC_send_prebuilt_message (&otr_msg->header, type, mid, c, fwd, force,
1665 &tun_message_sent, tq);
1666 GNUNET_assert (NULL != tq->cq);
1668 tq->cont_cls = cont_cls;
1675 * Send all cached messages that we can, tunnel is online.
1677 * @param t Tunnel that holds the messages. Cannot be loopback.
1680 send_queued_data (struct CadetTunnel *t)
1682 struct CadetTunnelDelayed *tqd;
1683 struct CadetTunnelDelayed *next;
1686 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1688 if (GCT_is_loopback (t))
1694 if (GNUNET_NO == is_ready (t))
1696 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1697 estate2s (t->estate), cstate2s (t->cstate));
1701 room = GCT_get_connections_buffer (t);
1702 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1703 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1704 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1706 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1709 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1710 tqd->t, NULL, GNUNET_YES,
1711 NULL != tqd->tq ? tqd->tq->cont : NULL,
1712 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1716 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1721 * Callback called when a queued message is sent.
1723 * @param cls Closure.
1724 * @param c Connection this message was on.
1725 * @param type Type of message sent.
1726 * @param fwd Was this a FWD going message?
1727 * @param size Size of the message.
1730 ephm_sent (void *cls,
1731 struct CadetConnection *c,
1732 struct CadetConnectionQueue *q,
1733 uint16_t type, int fwd, size_t size)
1735 struct CadetTunnel *t = cls;
1736 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
1741 * Callback called when a queued message is sent.
1743 * @param cls Closure.
1744 * @param c Connection this message was on.
1745 * @param type Type of message sent.
1746 * @param fwd Was this a FWD going message?
1747 * @param size Size of the message.
1750 pong_sent (void *cls,
1751 struct CadetConnection *c,
1752 struct CadetConnectionQueue *q,
1753 uint16_t type, int fwd, size_t size)
1755 struct CadetTunnel *t = cls;
1756 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
1762 * Sends key exchange message on a tunnel, choosing the best connection.
1763 * Should not be called on loopback tunnels.
1765 * @param t Tunnel on which this message is transmitted.
1766 * @param message Message to send. Function modifies it.
1768 * @return Handle to the message in the connection queue.
1770 static struct CadetConnectionQueue *
1771 send_kx (struct CadetTunnel *t,
1772 const struct GNUNET_MessageHeader *message)
1774 struct CadetConnection *c;
1775 struct GNUNET_CADET_KX *msg;
1776 size_t size = ntohs (message->size);
1777 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1782 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1784 /* Avoid loopback. */
1785 if (GCT_is_loopback (t))
1790 type = ntohs (message->type);
1792 /* Even if tunnel is "being destroyed", send anyway.
1793 * Could be a response to a rekey initiated by remote peer,
1794 * who is trying to create a new channel!
1797 /* Must have a connection, or be looking for one. */
1798 if (NULL == t->connection_head)
1800 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
1801 if (CADET_TUNNEL_SEARCHING != t->cstate)
1804 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1805 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
1810 msg = (struct GNUNET_CADET_KX *) cbuf;
1811 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1812 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1813 c = tunnel_get_connection (t);
1816 if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
1819 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1825 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1826 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
1827 GNUNET_assert (NULL == t->ephm_h);
1830 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1831 GNUNET_assert (NULL == t->pong_h);
1836 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
1839 memcpy (&msg[1], message, size);
1841 fwd = GCC_is_origin (c, GNUNET_YES);
1843 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
1850 * Send the ephemeral key on a tunnel.
1852 * @param t Tunnel on which to send the key.
1855 send_ephemeral (struct CadetTunnel *t)
1857 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1858 if (NULL != t->ephm_h)
1860 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1864 otr_kx_msg.sender_status = htonl (t->estate);
1865 otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1866 otr_kx_msg.nonce = t->kx_ctx->challenge;
1867 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", otr_kx_msg.nonce);
1868 t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
1869 ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
1870 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", otr_kx_msg.nonce);
1871 t->ephm_h = send_kx (t, &otr_kx_msg.header);
1876 * Send a pong message on a tunnel.
1878 * @param t Tunnel on which to send the pong.
1879 * @param challenge Value sent in the ping that we have to send back.
1882 send_pong (struct CadetTunnel *t, uint32_t challenge)
1884 struct GNUNET_CADET_KX_Pong msg;
1886 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1887 if (NULL != t->pong_h)
1889 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1892 msg.header.size = htons (sizeof (msg));
1893 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1894 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1895 msg.nonce = challenge;
1896 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1897 t_encrypt (t, &msg.nonce, &msg.nonce,
1898 sizeof (msg.nonce), msg.iv, GNUNET_YES);
1899 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1901 t->pong_h = send_kx (t, &msg.header);
1906 * Initiate a rekey with the remote peer.
1908 * @param cls Closure (tunnel).
1909 * @param tc TaskContext.
1912 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1914 struct CadetTunnel *t = cls;
1916 t->rekey_task = NULL;
1918 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1919 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1922 GNUNET_assert (NULL != t->kx_ctx);
1923 struct GNUNET_TIME_Relative duration;
1925 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1926 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1927 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1929 // FIXME make duration of old keys configurable
1930 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1932 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
1933 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1934 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1941 case CADET_TUNNEL_KEY_UNINITIALIZED:
1942 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
1945 case CADET_TUNNEL_KEY_SENT:
1948 case CADET_TUNNEL_KEY_OK:
1950 * - state should have changed during rekey_iterator
1951 * - task should have been canceled at pong_handle
1954 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1957 case CADET_TUNNEL_KEY_PING:
1958 case CADET_TUNNEL_KEY_REKEY:
1962 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1965 // FIXME exponential backoff
1966 struct GNUNET_TIME_Relative delay;
1968 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1969 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1970 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1971 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1972 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1977 * Our ephemeral key has changed, create new session key on all tunnels.
1979 * Each tunnel will start the Key Exchange with a random delay between
1980 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1981 * per second, on average.
1983 * @param cls Closure (size of the hashmap).
1984 * @param key Current public key.
1985 * @param value Value in the hash map (tunnel).
1987 * @return #GNUNET_YES, so we should continue to iterate,
1990 rekey_iterator (void *cls,
1991 const struct GNUNET_PeerIdentity *key,
1994 struct CadetTunnel *t = value;
1995 struct GNUNET_TIME_Relative delay;
1996 long n = (long) cls;
1999 if (NULL != t->rekey_task)
2002 if (GNUNET_YES == GCT_is_loopback (t))
2005 if (CADET_OTR != t->enc_type)
2008 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2009 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2010 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2012 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2019 * Create a new ephemeral key and key message, schedule next rekeying.
2021 * @param cls Closure (unused).
2022 * @param tc TaskContext.
2025 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2027 struct GNUNET_TIME_Absolute time;
2032 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2035 GNUNET_free_non_null (otr_ephemeral_key);
2036 otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2038 time = GNUNET_TIME_absolute_get ();
2039 otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2040 time = GNUNET_TIME_absolute_add (time, rekey_period);
2041 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2042 otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2043 GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2044 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2045 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
2047 GNUNET_assert (GNUNET_OK ==
2048 GNUNET_CRYPTO_eddsa_sign (id_key,
2049 &otr_kx_msg.purpose,
2050 &otr_kx_msg.signature));
2052 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2053 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2055 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2056 &global_otr_rekey, NULL);
2061 * Called only on shutdown, destroy every tunnel.
2063 * @param cls Closure (unused).
2064 * @param key Current public key.
2065 * @param value Value in the hash map (tunnel).
2067 * @return #GNUNET_YES, so we should continue to iterate,
2070 destroy_iterator (void *cls,
2071 const struct GNUNET_PeerIdentity *key,
2074 struct CadetTunnel *t = value;
2076 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2083 * Notify remote peer that we don't know a channel he is talking about,
2084 * probably CHANNEL_DESTROY was missed.
2086 * @param t Tunnel on which to notify.
2087 * @param gid ID of the channel.
2090 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2092 struct GNUNET_CADET_ChannelManage msg;
2094 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2095 msg.header.size = htons (sizeof (msg));
2096 msg.chid = htonl (gid);
2098 LOG (GNUNET_ERROR_TYPE_DEBUG,
2099 "WARNING destroying unknown channel %u on tunnel %s\n",
2101 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2106 * Demultiplex data per channel and call appropriate channel handler.
2108 * @param t Tunnel on which the data came.
2109 * @param msg Data message.
2110 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2111 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2112 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2113 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2116 handle_data (struct CadetTunnel *t,
2117 const struct GNUNET_CADET_Data *msg,
2120 struct CadetChannel *ch;
2124 size = ntohs (msg->header.size);
2126 sizeof (struct GNUNET_CADET_Data) +
2127 sizeof (struct GNUNET_MessageHeader))
2132 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2133 GC_m2s (ntohs (msg[1].header.type)));
2136 ch = GCT_get_channel (t, ntohl (msg->chid));
2139 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2141 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2143 send_channel_destroy (t, ntohl (msg->chid));
2147 GCCH_handle_data (ch, msg, fwd);
2152 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2154 * @param t Tunnel on which the DATA ACK came.
2155 * @param msg DATA ACK message.
2156 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2157 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2158 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2159 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2162 handle_data_ack (struct CadetTunnel *t,
2163 const struct GNUNET_CADET_DataACK *msg,
2166 struct CadetChannel *ch;
2170 size = ntohs (msg->header.size);
2171 if (size != sizeof (struct GNUNET_CADET_DataACK))
2178 ch = GCT_get_channel (t, ntohl (msg->chid));
2181 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2183 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2188 GCCH_handle_data_ack (ch, msg, fwd);
2193 * Handle channel create.
2195 * @param t Tunnel on which the data came.
2196 * @param msg Data message.
2199 handle_ch_create (struct CadetTunnel *t,
2200 const struct GNUNET_CADET_ChannelCreate *msg)
2202 struct CadetChannel *ch;
2206 size = ntohs (msg->header.size);
2207 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2214 ch = GCT_get_channel (t, ntohl (msg->chid));
2215 if (NULL != ch && ! GCT_is_loopback (t))
2217 /* Probably a retransmission, safe to ignore */
2218 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2220 ch = GCCH_handle_create (t, msg);
2222 GCT_add_channel (t, ch);
2228 * Handle channel NACK: check correctness and call channel handler for NACKs.
2230 * @param t Tunnel on which the NACK came.
2231 * @param msg NACK message.
2234 handle_ch_nack (struct CadetTunnel *t,
2235 const struct GNUNET_CADET_ChannelManage *msg)
2237 struct CadetChannel *ch;
2241 size = ntohs (msg->header.size);
2242 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2249 ch = GCT_get_channel (t, ntohl (msg->chid));
2252 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2254 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2259 GCCH_handle_nack (ch);
2264 * Handle a CHANNEL ACK (SYNACK/ACK).
2266 * @param t Tunnel on which the CHANNEL ACK came.
2267 * @param msg CHANNEL ACK message.
2268 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2269 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2270 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2271 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2274 handle_ch_ack (struct CadetTunnel *t,
2275 const struct GNUNET_CADET_ChannelManage *msg,
2278 struct CadetChannel *ch;
2282 size = ntohs (msg->header.size);
2283 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2290 ch = GCT_get_channel (t, ntohl (msg->chid));
2293 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2295 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2300 GCCH_handle_ack (ch, msg, fwd);
2305 * Handle a channel destruction message.
2307 * @param t Tunnel on which the message came.
2308 * @param msg Channel destroy message.
2309 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2310 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2311 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2312 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2315 handle_ch_destroy (struct CadetTunnel *t,
2316 const struct GNUNET_CADET_ChannelManage *msg,
2319 struct CadetChannel *ch;
2323 size = ntohs (msg->header.size);
2324 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2331 ch = GCT_get_channel (t, ntohl (msg->chid));
2334 /* Probably a retransmission, safe to ignore */
2338 GCCH_handle_destroy (ch, msg, fwd);
2343 * Create a new Axolotl ephemeral (ratchet) key.
2348 new_ephemeral (struct CadetTunnel *t)
2350 GNUNET_free_non_null (t->ax->DHRs);
2351 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2356 * Free Axolotl data.
2361 destroy_ax (struct CadetTunnel *t)
2366 GNUNET_free_non_null (t->ax->DHRs);
2367 GNUNET_free_non_null (t->ax->kx_0);
2369 GNUNET_free (t->ax);
2376 * The peer's ephemeral key has changed: update the symmetrical keys.
2378 * @param t Tunnel this message came on.
2379 * @param msg Key eXchange message.
2382 handle_ephemeral (struct CadetTunnel *t,
2383 const struct GNUNET_CADET_KX_Ephemeral *msg)
2385 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2387 if (GNUNET_OK != check_ephemeral (t, msg))
2389 GNUNET_break_op (0);
2393 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2397 t->enc_type = CADET_OTR;
2398 if (NULL != t->rekey_task)
2399 GNUNET_SCHEDULER_cancel (t->rekey_task);
2401 rekey_tunnel (t, NULL);
2405 * If the key is different from what we know, derive the new E/D keys.
2406 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2408 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2409 sizeof (msg->ephemeral_key)))
2411 #if DUMP_KEYS_TO_STDERR
2412 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2413 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2414 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2415 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2417 t->peers_ephemeral_key = msg->ephemeral_key;
2421 if (CADET_TUNNEL_KEY_OK == t->estate)
2423 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2425 if (NULL != t->rekey_task)
2426 GNUNET_SCHEDULER_cancel (t->rekey_task);
2427 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2429 if (CADET_TUNNEL_KEY_SENT == t->estate)
2431 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2433 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2436 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2440 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2441 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2442 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2443 send_pong (t, nonce);
2449 * Peer has answer to our challenge.
2450 * If answer is successful, consider the key exchange finished and clean
2451 * up all related state.
2453 * @param t Tunnel this message came on.
2454 * @param msg Key eXchange Pong message.
2457 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2461 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2462 if (NULL == t->rekey_task)
2464 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2467 if (NULL == t->kx_ctx)
2469 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2473 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2474 if (challenge != t->kx_ctx->challenge)
2476 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2477 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2478 challenge, msg->nonce, t->kx_ctx->challenge);
2482 GNUNET_SCHEDULER_cancel (t->rekey_task);
2483 t->rekey_task = NULL;
2485 /* Don't free the old keys right away, but after a delay.
2486 * Rationale: the KX could have happened over a very fast connection,
2487 * with payload traffic still signed with the old key stuck in a slower
2489 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2493 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2498 * Handle Axolotl handshake.
2500 * @param t Tunnel this message came on.
2501 * @param msg Key eXchange Pong message.
2504 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2506 struct CadetTunnelAxolotl *ax;
2507 struct GNUNET_HashCode key_material[3];
2508 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2509 const struct GNUNET_CRYPTO_EcdhePublicKey *pub;
2510 const struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
2511 const char salt[] = "CADET Axolotl salt";
2512 const struct GNUNET_PeerIdentity *pid;
2515 LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2519 /* Something is wrong if ax is NULL. Whose fault it is? */
2520 GNUNET_break_op (CADET_OTR == t->enc_type);
2521 GNUNET_break (CADET_Axolotl == t->enc_type);
2525 if (GNUNET_OK != GCP_check_key (t->peer, &msg->permanent_key,
2526 &msg->purpose, &msg->signature))
2528 GNUNET_break_op (0);
2532 pid = GCT_get_destination (t);
2533 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2534 am_I_alice = GNUNET_YES;
2535 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2536 am_I_alice = GNUNET_NO;
2539 GNUNET_break_op (0);
2543 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2546 ax->DHRr = msg->ratchet_key;
2549 if (GNUNET_YES == am_I_alice)
2551 priv = ax_key; /* A */
2552 pub = &msg->ephemeral_key; /* B0 */
2556 priv = ax->kx_0; /* B0 */
2557 pub = &msg->permanent_key; /* A */
2559 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[0]);
2562 if (GNUNET_YES == am_I_alice)
2564 priv = ax->kx_0; /* A0 */
2565 pub = &msg->permanent_key; /* B */
2569 priv = ax_key; /* B */
2570 pub = &msg->ephemeral_key; /* A0 */
2572 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[1]);
2575 priv = ax->kx_0; /* A0 or B0 */
2576 pub = &msg->ephemeral_key; /* B0 or A0 */
2577 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[2]);
2579 #if DUMP_KEYS_TO_STDERR
2582 for (i = 0; i < 3; i++)
2583 LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2584 i, GNUNET_h2s (&key_material[i]));
2589 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2590 salt, sizeof (salt),
2591 &key_material, sizeof (key_material), NULL);
2594 if (GNUNET_YES == am_I_alice)
2600 ax->ratchet_flag = GNUNET_YES;
2608 ax->ratchet_flag = GNUNET_NO;
2610 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2615 * Demultiplex by message type and call appropriate handler for a message
2616 * towards a channel of a local tunnel.
2618 * @param t Tunnel this message came on.
2619 * @param msgh Message header.
2620 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2621 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2622 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2623 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2626 handle_decrypted (struct CadetTunnel *t,
2627 const struct GNUNET_MessageHeader *msgh,
2632 type = ntohs (msgh->type);
2633 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2637 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2638 /* Do nothing, connection aleady got updated. */
2639 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2642 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2643 /* Don't send hop ACK, wait for client to ACK */
2644 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2647 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2648 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2651 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2652 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2655 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2656 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
2659 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2660 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2663 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2664 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2668 GNUNET_break_op (0);
2669 LOG (GNUNET_ERROR_TYPE_WARNING,
2670 "end-to-end message not known (%u)\n",
2671 ntohs (msgh->type));
2672 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2676 /******************************************************************************/
2677 /******************************** API ***********************************/
2678 /******************************************************************************/
2680 * Decrypt old format and demultiplex by message type. Call appropriate handler
2681 * for a message towards a channel of a local tunnel.
2683 * @param t Tunnel this message came on.
2684 * @param msg Message header.
2687 GCT_handle_encrypted (struct CadetTunnel *t,
2688 const struct GNUNET_MessageHeader *msg)
2690 size_t size = ntohs (msg->size);
2691 size_t payload_size;
2694 uint16_t type = ntohs (msg->type);
2695 struct GNUNET_MessageHeader *msgh;
2698 if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
2700 const struct GNUNET_CADET_Encrypted *emsg;
2702 emsg = (struct GNUNET_CADET_Encrypted *) msg;
2703 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2704 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
2705 emsg->iv, &emsg->hmac);
2707 else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
2709 const struct GNUNET_CADET_AX *emsg;
2711 emsg = (struct GNUNET_CADET_AX *) msg;
2712 payload_size = size - sizeof (struct GNUNET_CADET_AX);
2713 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, &emsg[1],
2714 payload_size, &emsg->hmac);
2717 if (-1 == decrypted_size)
2719 GNUNET_break_op (0);
2724 while (off < decrypted_size)
2728 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2729 msize = ntohs (msgh->size);
2730 if (msize < sizeof (struct GNUNET_MessageHeader))
2732 GNUNET_break_op (0);
2735 handle_decrypted (t, msgh, GNUNET_SYSERR);
2742 * Demultiplex an encapsulated KX message by message type.
2744 * @param t Tunnel on which the message came.
2745 * @param message Payload of KX message.
2748 GCT_handle_kx (struct CadetTunnel *t,
2749 const struct GNUNET_MessageHeader *message)
2753 type = ntohs (message->type);
2754 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
2757 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2758 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
2761 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2762 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
2765 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2766 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
2770 GNUNET_break_op (0);
2771 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
2776 * Initialize the tunnel subsystem.
2778 * @param c Configuration handle.
2779 * @param key ECC private key, to derive all other keys and do crypto.
2782 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2783 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2785 int expected_overhead;
2787 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2789 expected_overhead = 0;
2790 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
2791 expected_overhead += sizeof (struct GNUNET_CADET_Data);
2792 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
2793 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2796 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2799 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2800 "CADET", "DEFAULT_TTL", "USING DEFAULT");
2804 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2807 rekey_period = GNUNET_TIME_UNIT_DAYS;
2812 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
2813 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2814 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2815 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2816 otr_kx_msg.origin_identity = my_full_id;
2817 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
2819 ax_key = GNUNET_CRYPTO_ecdhe_key_create ();
2820 GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &ax_identity.permanent_key);
2821 ax_identity.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_AXKX);
2822 ax_identity.purpose.size = htonl (ax_purpose_size ());
2823 GNUNET_assert (GNUNET_OK ==
2824 GNUNET_CRYPTO_eddsa_sign (id_key,
2825 &ax_identity.purpose,
2826 &ax_identity.signature));
2828 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2833 * Shut down the tunnel subsystem.
2838 if (NULL != rekey_task)
2840 GNUNET_SCHEDULER_cancel (rekey_task);
2843 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2844 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2845 GNUNET_free (ax_key);
2852 * @param destination Peer this tunnel is towards.
2854 struct CadetTunnel *
2855 GCT_new (struct CadetPeer *destination)
2857 struct CadetTunnel *t;
2859 t = GNUNET_new (struct CadetTunnel);
2861 t->peer = destination;
2864 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2865 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2871 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
2873 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2879 * Change the tunnel's connection state.
2881 * @param t Tunnel whose connection state to change.
2882 * @param cstate New connection state.
2885 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2889 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2890 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2891 if (myid != GCP_get_short_id (t->peer) &&
2892 CADET_TUNNEL_READY != t->cstate &&
2893 CADET_TUNNEL_READY == cstate)
2896 if (CADET_TUNNEL_KEY_OK == t->estate)
2898 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2899 send_queued_data (t);
2901 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2903 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
2908 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
2913 if (CADET_TUNNEL_READY == cstate
2914 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2916 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2917 GCP_stop_search (t->peer);
2923 * Change the tunnel encryption state.
2925 * @param t Tunnel whose encryption state to change, or NULL.
2926 * @param state New encryption state.
2929 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2931 enum CadetTunnelEState old;
2938 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2939 GCP_2s (t->peer), estate2s (old));
2940 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2941 GCP_2s (t->peer), estate2s (t->estate));
2943 /* Send queued data if enc state changes to OK */
2944 if (myid != GCP_get_short_id (t->peer) &&
2945 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
2947 send_queued_data (t);
2953 * @brief Check if tunnel has too many connections, and remove one if necessary.
2955 * Currently this means the newest connection, unless it is a direct one.
2956 * Implemented as a task to avoid freeing a connection that is in the middle
2957 * of being created/processed.
2959 * @param cls Closure (Tunnel to check).
2960 * @param tc Task context.
2963 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2965 struct CadetTunnel *t = cls;
2967 t->trim_connections_task = NULL;
2969 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2972 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2974 struct CadetTConnection *iter;
2975 struct CadetTConnection *c;
2977 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2979 if ((iter->created.abs_value_us > c->created.abs_value_us)
2980 && GNUNET_NO == GCC_is_direct (iter->c))
2987 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2989 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3002 * Add a connection to a tunnel.
3005 * @param c Connection.
3008 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3010 struct CadetTConnection *aux;
3012 GNUNET_assert (NULL != c);
3014 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3015 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3016 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3020 aux = GNUNET_new (struct CadetTConnection);
3022 aux->created = GNUNET_TIME_absolute_get ();
3024 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3026 if (CADET_TUNNEL_SEARCHING == t->cstate)
3027 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3029 if (NULL != t->trim_connections_task)
3030 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3035 * Remove a connection from a tunnel.
3038 * @param c Connection.
3041 GCT_remove_connection (struct CadetTunnel *t,
3042 struct CadetConnection *c)
3044 struct CadetTConnection *aux;
3045 struct CadetTConnection *next;
3048 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3049 GCC_2s (c), GCT_2s (t));
3050 for (aux = t->connection_head; aux != NULL; aux = next)
3055 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3060 conns = GCT_count_connections (t);
3062 && NULL == t->destroy_task
3063 && CADET_TUNNEL_SHUTDOWN != t->cstate
3064 && GNUNET_NO == shutting_down)
3066 if (0 == GCT_count_any_connections (t))
3067 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3069 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3072 /* Start new connections if needed */
3073 if (CONNECTIONS_PER_TUNNEL > conns
3074 && NULL == t->destroy_task
3075 && CADET_TUNNEL_SHUTDOWN != t->cstate
3076 && GNUNET_NO == shutting_down)
3078 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
3079 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3083 /* If not marked as ready, no change is needed */
3084 if (CADET_TUNNEL_READY != t->cstate)
3087 /* Check if any connection is ready to maintain cstate */
3088 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3089 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3095 * Add a channel to a tunnel.
3098 * @param ch Channel.
3101 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3103 struct CadetTChannel *aux;
3105 GNUNET_assert (NULL != ch);
3107 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3109 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3111 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
3116 aux = GNUNET_new (struct CadetTChannel);
3118 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3119 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3121 if (NULL != t->destroy_task)
3123 GNUNET_SCHEDULER_cancel (t->destroy_task);
3124 t->destroy_task = NULL;
3125 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3131 * Remove a channel from a tunnel.
3134 * @param ch Channel.
3137 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3139 struct CadetTChannel *aux;
3141 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3142 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3146 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3147 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3156 * Search for a channel by global ID.
3158 * @param t Tunnel containing the channel.
3159 * @param chid Public channel number.
3161 * @return channel handler, NULL if doesn't exist
3163 struct CadetChannel *
3164 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3166 struct CadetTChannel *iter;
3171 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3173 if (GCCH_get_id (iter->ch) == chid)
3177 return NULL == iter ? NULL : iter->ch;
3182 * @brief Destroy a tunnel and free all resources.
3184 * Should only be called a while after the tunnel has been marked as destroyed,
3185 * in case there is a new channel added to the same peer shortly after marking
3186 * the tunnel. This way we avoid a new public key handshake.
3188 * @param cls Closure (tunnel to destroy).
3189 * @param tc Task context.
3192 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3194 struct CadetTunnel *t = cls;
3195 struct CadetTConnection *iter;
3197 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3198 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3200 LOG (GNUNET_ERROR_TYPE_WARNING,
3201 "Not destroying tunnel, due to shutdown. "
3202 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3205 t->destroy_task = NULL;
3206 t->cstate = CADET_TUNNEL_SHUTDOWN;
3208 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3210 GCC_send_destroy (iter->c);
3217 * Tunnel is empty: destroy it.
3219 * Notifies all connections about the destruction.
3221 * @param t Tunnel to destroy.
3224 GCT_destroy_empty (struct CadetTunnel *t)
3226 if (GNUNET_YES == shutting_down)
3227 return; /* Will be destroyed immediately anyway */
3229 if (NULL != t->destroy_task)
3231 LOG (GNUNET_ERROR_TYPE_WARNING,
3232 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3234 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3236 /* should never happen, tunnel can only become empty once, and the
3237 * task identifier should be NO_TASK (cleaned when the tunnel was created
3238 * or became un-empty)
3243 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3246 // FIXME make delay a config option
3247 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3248 &delayed_destroy, t);
3249 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3250 t, t->destroy_task);
3255 * Destroy tunnel if empty (no more channels).
3257 * @param t Tunnel to destroy if empty.
3260 GCT_destroy_if_empty (struct CadetTunnel *t)
3262 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3263 if (0 < GCT_count_channels (t))
3266 GCT_destroy_empty (t);
3271 * Destroy the tunnel.
3273 * This function does not generate any warning traffic to clients or peers.
3276 * Cancel messages belonging to this tunnel queued to neighbors.
3277 * Free any allocated resources linked to the tunnel.
3279 * @param t The tunnel to destroy.
3282 GCT_destroy (struct CadetTunnel *t)
3284 struct CadetTConnection *iter_c;
3285 struct CadetTConnection *next_c;
3286 struct CadetTChannel *iter_ch;
3287 struct CadetTChannel *next_ch;
3292 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3294 GNUNET_break (GNUNET_YES ==
3295 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3296 GCP_get_id (t->peer), t));
3298 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3300 next_c = iter_c->next;
3301 GCC_destroy (iter_c->c);
3303 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3305 next_ch = iter_ch->next;
3306 GCCH_destroy (iter_ch->ch);
3307 /* Should only happen on shutdown, but it's ok. */
3310 if (NULL != t->destroy_task)
3312 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3313 GNUNET_SCHEDULER_cancel (t->destroy_task);
3314 t->destroy_task = NULL;
3317 if (NULL != t->trim_connections_task)
3319 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3320 t->trim_connections_task);
3321 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3322 t->trim_connections_task = NULL;
3325 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3326 GCP_set_tunnel (t->peer, NULL);
3328 if (NULL != t->rekey_task)
3330 GNUNET_SCHEDULER_cancel (t->rekey_task);
3331 t->rekey_task = NULL;
3333 if (NULL != t->kx_ctx)
3335 if (NULL != t->kx_ctx->finish_task)
3336 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3337 GNUNET_free (t->kx_ctx);
3348 * @brief Use the given path for the tunnel.
3349 * Update the next and prev hops (and RCs).
3350 * (Re)start the path refresh in case the tunnel is locally owned.
3352 * @param t Tunnel to update.
3353 * @param p Path to use.
3355 * @return Connection created.
3357 struct CadetConnection *
3358 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3360 struct CadetConnection *c;
3361 struct GNUNET_CADET_Hash cid;
3362 unsigned int own_pos;
3364 if (NULL == t || NULL == p)
3370 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3376 for (own_pos = 0; own_pos < p->length; own_pos++)
3378 if (p->peers[own_pos] == myid)
3381 if (own_pos >= p->length)
3383 GNUNET_break_op (0);
3387 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3388 c = GCC_new (&cid, t, p, own_pos);
3391 /* Path was flawed */
3394 GCT_add_connection (t, c);
3400 * Count all created connections of a tunnel. Not necessarily ready connections!
3402 * @param t Tunnel on which to count.
3404 * @return Number of connections created, either being established or ready.
3407 GCT_count_any_connections (struct CadetTunnel *t)
3409 struct CadetTConnection *iter;
3415 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3423 * Count established (ready) connections of a tunnel.
3425 * @param t Tunnel on which to count.
3427 * @return Number of connections.
3430 GCT_count_connections (struct CadetTunnel *t)
3432 struct CadetTConnection *iter;
3438 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3439 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3447 * Count channels of a tunnel.
3449 * @param t Tunnel on which to count.
3451 * @return Number of channels.
3454 GCT_count_channels (struct CadetTunnel *t)
3456 struct CadetTChannel *iter;
3459 for (count = 0, iter = t->channel_head;
3461 iter = iter->next, count++) /* skip */;
3468 * Get the connectivity state of a tunnel.
3472 * @return Tunnel's connectivity state.
3474 enum CadetTunnelCState
3475 GCT_get_cstate (struct CadetTunnel *t)
3480 return (enum CadetTunnelCState) -1;
3487 * Get the encryption state of a tunnel.
3491 * @return Tunnel's encryption state.
3493 enum CadetTunnelEState
3494 GCT_get_estate (struct CadetTunnel *t)
3499 return (enum CadetTunnelEState) -1;
3505 * Get the maximum buffer space for a tunnel towards a local client.
3509 * @return Biggest buffer space offered by any channel in the tunnel.
3512 GCT_get_channels_buffer (struct CadetTunnel *t)
3514 struct CadetTChannel *iter;
3515 unsigned int buffer;
3516 unsigned int ch_buf;
3518 if (NULL == t->channel_head)
3520 /* Probably getting buffer for a channel create/handshake. */
3521 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3526 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3528 ch_buf = get_channel_buffer (iter);
3529 if (ch_buf > buffer)
3537 * Get the total buffer space for a tunnel for P2P traffic.
3541 * @return Buffer space offered by all connections in the tunnel.
3544 GCT_get_connections_buffer (struct CadetTunnel *t)
3546 struct CadetTConnection *iter;
3547 unsigned int buffer;
3549 if (GNUNET_NO == is_ready (t))
3551 if (count_queued_data (t) > 3)
3558 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3560 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3564 buffer += get_connection_buffer (iter);
3572 * Get the tunnel's destination.
3576 * @return ID of the destination peer.
3578 const struct GNUNET_PeerIdentity *
3579 GCT_get_destination (struct CadetTunnel *t)
3581 return GCP_get_id (t->peer);
3586 * Get the tunnel's next free global channel ID.
3590 * @return GID of a channel free to use.
3593 GCT_get_next_chid (struct CadetTunnel *t)
3595 CADET_ChannelNumber chid;
3596 CADET_ChannelNumber mask;
3599 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3600 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3601 * If peer's ID is bigger, start at 0x4... bit 30 = 1
3603 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3608 t->next_chid |= mask;
3610 while (NULL != GCT_get_channel (t, t->next_chid))
3612 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3613 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3614 t->next_chid |= mask;
3616 chid = t->next_chid;
3617 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3618 t->next_chid |= mask;
3625 * Send ACK on one or more channels due to buffer in connections.
3627 * @param t Channel which has some free buffer space.
3630 GCT_unchoke_channels (struct CadetTunnel *t)
3632 struct CadetTChannel *iter;
3633 unsigned int buffer;
3634 unsigned int channels = GCT_count_channels (t);
3635 unsigned int choked_n;
3636 struct CadetChannel *choked[channels];
3638 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3639 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3640 if (NULL != t->channel_head)
3641 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3643 /* Get buffer space */
3644 buffer = GCT_get_connections_buffer (t);
3650 /* Count and remember choked channels */
3652 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3654 if (GNUNET_NO == get_channel_allowed (iter))
3656 choked[choked_n++] = iter->ch;
3660 /* Unchoke random channels */
3661 while (0 < buffer && 0 < choked_n)
3663 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3665 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3668 choked[r] = choked[choked_n];
3674 * Send ACK on one or more connections due to buffer space to the client.
3676 * Iterates all connections of the tunnel and sends ACKs appropriately.
3681 GCT_send_connection_acks (struct CadetTunnel *t)
3683 struct CadetTConnection *iter;
3686 uint32_t allow_per_connection;
3688 unsigned int buffer;
3690 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3699 if (CADET_TUNNEL_READY != t->cstate)
3702 buffer = GCT_get_channels_buffer (t);
3703 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
3705 /* Count connections, how many messages are already allowed */
3706 cs = GCT_count_connections (t);
3707 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3709 allowed += get_connection_allowed (iter);
3711 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
3713 /* Make sure there is no overflow */
3714 if (allowed > buffer)
3717 /* Authorize connections to send more data */
3718 to_allow = buffer - allowed;
3720 for (iter = t->connection_head;
3721 NULL != iter && to_allow > 0;
3724 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3725 || get_connection_allowed (iter) > 64 / 3)
3729 allow_per_connection = to_allow/cs;
3730 to_allow -= allow_per_connection;
3732 GCC_allow (iter->c, allow_per_connection,
3733 GCC_is_origin (iter->c, GNUNET_NO));
3738 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
3739 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
3745 * Cancel a previously sent message while it's in the queue.
3747 * ONLY can be called before the continuation given to the send function
3748 * is called. Once the continuation is called, the message is no longer in the
3751 * @param q Handle to the queue.
3754 GCT_cancel (struct CadetTunnelQueue *q)
3759 /* tun_message_sent() will be called and free q */
3761 else if (NULL != q->tqd)
3763 unqueue_data (q->tqd);
3765 if (NULL != q->cont)
3766 q->cont (q->cont_cls, NULL, q, 0, 0);
3777 * Sends an already built message on a tunnel, encrypting it and
3778 * choosing the best connection if not provided.
3780 * @param message Message to send. Function modifies it.
3781 * @param t Tunnel on which this message is transmitted.
3782 * @param c Connection to use (autoselect if NULL).
3783 * @param force Force the tunnel to take the message (buffer overfill).
3784 * @param cont Continuation to call once message is really sent.
3785 * @param cont_cls Closure for @c cont.
3787 * @return Handle to cancel message. NULL if @c cont is NULL.
3789 struct CadetTunnelQueue *
3790 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3791 struct CadetTunnel *t, struct CadetConnection *c,
3792 int force, GCT_sent cont, void *cont_cls)
3794 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3799 * Send an Axolotl KX message.
3801 * @param t Tunnel on which to send it.
3804 GCT_send_ax_kx (struct CadetTunnel *t)
3806 struct GNUNET_CADET_AX_KX msg;
3808 LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
3810 msg.header.size = htons (sizeof (msg));
3811 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
3812 msg.permanent_key = ax_identity.permanent_key;
3813 msg.purpose = ax_identity.purpose;
3814 msg.signature = ax_identity.signature;
3815 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
3816 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
3818 t->ephm_h = send_kx (t, &msg.header);
3819 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
3824 * Sends an already built and encrypted message on a tunnel, choosing the best
3825 * connection. Useful for re-queueing messages queued on a destroyed connection.
3827 * @param message Message to send. Function modifies it.
3828 * @param t Tunnel on which this message is transmitted.
3831 GCT_resend_message (const struct GNUNET_MessageHeader *message,
3832 struct CadetTunnel *t)
3834 struct CadetConnection *c;
3837 c = tunnel_get_connection (t);
3840 /* TODO queue in tunnel, marked as encrypted */
3841 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
3844 fwd = GCC_is_origin (c, GNUNET_YES);
3845 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
3846 GNUNET_YES, NULL, NULL));
3851 * Is the tunnel directed towards the local peer?
3855 * @return #GNUNET_YES if it is loopback.
3858 GCT_is_loopback (const struct CadetTunnel *t)
3860 return (myid == GCP_get_short_id (t->peer));
3865 * Is the tunnel this path already?
3870 * @return #GNUNET_YES a connection uses this path.
3873 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3875 struct CadetTConnection *iter;
3877 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3878 if (path_equivalent (GCC_get_path (iter->c), p))
3886 * Get a cost of a path for a tunnel considering existing connections.
3889 * @param path Candidate path.
3891 * @return Cost of the path (path length + number of overlapping nodes)
3894 GCT_get_path_cost (const struct CadetTunnel *t,
3895 const struct CadetPeerPath *path)
3897 struct CadetTConnection *iter;
3898 const struct CadetPeerPath *aux;
3899 unsigned int overlap;
3907 GNUNET_assert (NULL != t);
3909 for (i = 0; i < path->length; i++)
3911 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3913 aux = GCC_get_path (iter->c);
3917 for (j = 0; j < aux->length; j++)
3919 if (path->peers[i] == aux->peers[j])
3927 return path->length + overlap;
3932 * Get the static string for the peer this tunnel is directed.
3936 * @return Static string the destination peer's ID.
3939 GCT_2s (const struct CadetTunnel *t)
3944 return GCP_2s (t->peer);
3948 /******************************************************************************/
3949 /***************************** INFO/DEBUG *******************************/
3950 /******************************************************************************/
3953 * Log all possible info about the tunnel state.
3955 * @param t Tunnel to debug.
3956 * @param level Debug level to use.
3959 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3961 struct CadetTChannel *iterch;
3962 struct CadetTConnection *iterc;
3965 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3967 __FILE__, __FUNCTION__, __LINE__);
3971 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3972 LOG2 (level, "TTT cstate %s, estate %s\n",
3973 cstate2s (t->cstate), estate2s (t->estate));
3974 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
3975 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
3976 #if DUMP_KEYS_TO_STDERR
3977 LOG2 (level, "TTT my EPHM\t %s\n",
3978 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
3979 LOG2 (level, "TTT peers EPHM:\t %s\n",
3980 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
3981 LOG2 (level, "TTT ENC key:\t %s\n",
3982 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
3983 LOG2 (level, "TTT DEC key:\t %s\n",
3984 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
3987 LOG2 (level, "TTT OLD ENC key:\t %s\n",
3988 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
3989 LOG2 (level, "TTT OLD DEC key:\t %s\n",
3990 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
3993 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3994 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
3996 LOG2 (level, "TTT channels:\n");
3997 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
3999 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
4002 LOG2 (level, "TTT connections:\n");
4003 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4005 GCC_debug (iterc->c, level);
4008 LOG2 (level, "TTT DEBUG TUNNEL END\n");
4013 * Iterate all tunnels.
4015 * @param iter Iterator.
4016 * @param cls Closure for @c iter.
4019 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4021 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4026 * Count all tunnels.
4028 * @return Number of tunnels to remote peers kept by this peer.
4031 GCT_count_all (void)
4033 return GNUNET_CONTAINER_multipeermap_size (tunnels);
4038 * Iterate all connections of a tunnel.
4040 * @param t Tunnel whose connections to iterate.
4041 * @param iter Iterator.
4042 * @param cls Closure for @c iter.
4045 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4047 struct CadetTConnection *ct;
4049 for (ct = t->connection_head; NULL != ct; ct = ct->next)
4055 * Iterate all channels of a tunnel.
4057 * @param t Tunnel whose channels to iterate.
4058 * @param iter Iterator.
4059 * @param cls Closure for @c iter.
4062 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4064 struct CadetTChannel *cht;
4066 for (cht = t->channel_head; NULL != cht; cht = cht->next)
4067 iter (cls, cht->ch);