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 @url 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 Identity key (recv).
254 struct GNUNET_CRYPTO_EcdhePublicKey DHIr;
257 * ECDH Ratchet key (send).
259 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
262 * ECDH Ratchet key (recv).
264 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
267 * Message number (reset to 0 with each new ratchet, send)
272 * Message numbers (reset to 0 with each new ratchet, recv)
277 * Previous message numbers (# of msgs sent under prev ratchet)
282 * True (#GNUNET_YES) if the party will send a new ratchet key in next msg.
288 * Struct containing all information regarding a tunnel to a peer.
293 * Endpoint of the tunnel.
295 struct CadetPeer *peer;
298 * Type of encryption used in the tunnel.
300 enum CadetTunnelEncryption enc_type;
305 struct CadetTunnelAxolotl *ax;
308 * State of the tunnel connectivity.
310 enum CadetTunnelCState cstate;
313 * State of the tunnel encryption.
315 enum CadetTunnelEState estate;
318 * Key eXchange context.
320 struct CadetTunnelKXCtx *kx_ctx;
323 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
326 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
329 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
331 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
334 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
336 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
339 * Task to start the rekey process.
341 struct GNUNET_SCHEDULER_Task * rekey_task;
344 * Paths that are actively used to reach the destination peer.
346 struct CadetTConnection *connection_head;
347 struct CadetTConnection *connection_tail;
350 * Next connection number.
355 * Channels inside this tunnel.
357 struct CadetTChannel *channel_head;
358 struct CadetTChannel *channel_tail;
361 * Channel ID for the next created channel.
363 CADET_ChannelNumber next_chid;
366 * Destroy flag: if true, destroy on last message.
368 struct GNUNET_SCHEDULER_Task * destroy_task;
371 * Queued messages, to transmit once tunnel gets connected.
373 struct CadetTunnelDelayed *tq_head;
374 struct CadetTunnelDelayed *tq_tail;
377 * Task to trim connections if too many are present.
379 struct GNUNET_SCHEDULER_Task * trim_connections_task;
382 * Ephemeral message in the queue (to avoid queueing more than one).
384 struct CadetConnectionQueue *ephm_h;
387 * Pong message in the queue.
389 struct CadetConnectionQueue *pong_h;
394 * Struct used to save messages in a non-ready tunnel to send once connected.
396 struct CadetTunnelDelayed
401 struct CadetTunnelDelayed *next;
402 struct CadetTunnelDelayed *prev;
407 struct CadetTunnel *t;
410 * Tunnel queue given to the channel to cancel request. Update on send_queued.
412 struct CadetTunnelQueue *tq;
417 /* struct GNUNET_MessageHeader *msg; */
422 * Handle for messages queued but not yet sent.
424 struct CadetTunnelQueue
427 * Connection queue handle, to cancel if necessary.
429 struct CadetConnectionQueue *cq;
432 * Handle in case message hasn't been given to a connection yet.
434 struct CadetTunnelDelayed *tqd;
437 * Continuation to call once sent.
442 * Closure for @c cont.
449 * Cached Axolotl key with signature.
451 struct CadetAxolotlSignedKey
454 * Information about what is being signed (@a permanent_key).
456 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
459 * Permanent public ECDH key.
461 struct GNUNET_CRYPTO_EcdhePublicKey permanent_key;
464 * An EdDSA signature of the permanent ECDH key with the Peer's ID key.
466 struct GNUNET_CRYPTO_EddsaSignature signature;
470 /******************************************************************************/
471 /******************************* GLOBALS ***********************************/
472 /******************************************************************************/
475 * Global handle to the statistics service.
477 extern struct GNUNET_STATISTICS_Handle *stats;
480 * Local peer own ID (memory efficient handle).
482 extern GNUNET_PEER_Id myid;
485 * Local peer own ID (full value).
487 extern struct GNUNET_PeerIdentity my_full_id;
491 * Don't try to recover tunnels if shutting down.
493 extern int shutting_down;
497 * Set of all tunnels, in order to trigger a new exchange on rekey.
498 * Indexed by peer's ID.
500 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
503 * Default TTL for payload packets.
505 static unsigned long long default_ttl;
509 * Own Peer ID private key.
511 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
513 /******************************** AXOLOTL ************************************/
515 static struct GNUNET_CRYPTO_EcdhePrivateKey *ax_key;
518 * Own Axolotl permanent public key (cache).
520 static struct CadetAxolotlSignedKey ax_identity;
522 /******************************** OTR ***********************************/
526 * Own global OTR ephemeral private key.
528 static struct GNUNET_CRYPTO_EcdhePrivateKey *otr_ephemeral_key;
531 * Cached message used to perform a OTR key exchange.
533 static struct GNUNET_CADET_KX_Ephemeral otr_kx_msg;
536 * Task to generate a new OTR ephemeral key.
538 static struct GNUNET_SCHEDULER_Task *rekey_task;
543 static struct GNUNET_TIME_Relative rekey_period;
546 /******************************************************************************/
547 /******************************** STATIC ***********************************/
548 /******************************************************************************/
551 * Get string description for tunnel connectivity state.
553 * @param cs Tunnel state.
555 * @return String representation.
558 cstate2s (enum CadetTunnelCState cs)
564 case CADET_TUNNEL_NEW:
565 return "CADET_TUNNEL_NEW";
566 case CADET_TUNNEL_SEARCHING:
567 return "CADET_TUNNEL_SEARCHING";
568 case CADET_TUNNEL_WAITING:
569 return "CADET_TUNNEL_WAITING";
570 case CADET_TUNNEL_READY:
571 return "CADET_TUNNEL_READY";
572 case CADET_TUNNEL_SHUTDOWN:
573 return "CADET_TUNNEL_SHUTDOWN";
575 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
583 * Get string description for tunnel encryption state.
585 * @param es Tunnel state.
587 * @return String representation.
590 estate2s (enum CadetTunnelEState es)
596 case CADET_TUNNEL_KEY_UNINITIALIZED:
597 return "CADET_TUNNEL_KEY_UNINITIALIZED";
598 case CADET_TUNNEL_KEY_SENT:
599 return "CADET_TUNNEL_KEY_SENT";
600 case CADET_TUNNEL_KEY_PING:
601 return "CADET_TUNNEL_KEY_PING";
602 case CADET_TUNNEL_KEY_OK:
603 return "CADET_TUNNEL_KEY_OK";
604 case CADET_TUNNEL_KEY_REKEY:
605 return "CADET_TUNNEL_KEY_REKEY";
607 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
615 * @brief Check if tunnel is ready to send traffic.
617 * Tunnel must be connected and with encryption correctly set up.
619 * @param t Tunnel to check.
621 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
624 is_ready (struct CadetTunnel *t)
628 GCT_debug (t, GNUNET_ERROR_TYPE_DEBUG);
629 ready = CADET_TUNNEL_READY == t->cstate
630 && (CADET_TUNNEL_KEY_OK == t->estate
631 || CADET_TUNNEL_KEY_REKEY == t->estate);
632 ready = ready || GCT_is_loopback (t);
638 * Check if a key is invalid (NULL pointer or all 0)
640 * @param key Key to check.
642 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
645 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
647 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
652 memset (&null_key, 0, sizeof (null_key));
653 if (0 == memcmp (key, &null_key, sizeof (null_key)))
660 * Ephemeral key message purpose size.
662 * @return Size of the part of the ephemeral key message that must be signed.
665 ephemeral_purpose_size (void)
667 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
668 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
669 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
670 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
671 sizeof (struct GNUNET_PeerIdentity);
676 * Ephemeral key message purpose size.
678 * @return Size of the part of the ephemeral key message that must be signed.
681 ax_purpose_size (void)
683 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
684 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
689 * Size of the encrypted part of a ping message.
691 * @return Size of the encrypted part of a ping message.
694 ping_encryption_size (void)
696 return sizeof (uint32_t);
701 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
703 * @param tch Tunnel's channel handle.
705 * @return Amount of messages the channel can still buffer towards the client.
708 get_channel_buffer (const struct CadetTChannel *tch)
712 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
713 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
715 return GCCH_get_buffer (tch->ch, fwd);
720 * Get the channel's allowance status.
722 * @param tch Tunnel's channel handle.
724 * @return #GNUNET_YES if we allowed the client to send data to us.
727 get_channel_allowed (const struct CadetTChannel *tch)
731 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
732 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
734 return GCCH_get_allowed (tch->ch, fwd);
739 * Get the connection's buffer.
741 * @param tc Tunnel's connection handle.
743 * @return Amount of messages the connection can still buffer.
746 get_connection_buffer (const struct CadetTConnection *tc)
750 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
751 fwd = GCC_is_origin (tc->c, GNUNET_YES);
753 return GCC_get_buffer (tc->c, fwd);
758 * Get the connection's allowance.
760 * @param tc Tunnel's connection handle.
762 * @return Amount of messages we have allowed the next peer to send us.
765 get_connection_allowed (const struct CadetTConnection *tc)
769 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
770 fwd = GCC_is_origin (tc->c, GNUNET_YES);
772 return GCC_get_allowed (tc->c, fwd);
777 * Check that a ephemeral key message s well formed and correctly signed.
779 * @param t Tunnel on which the message came.
780 * @param msg The ephemeral key message.
782 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
785 check_ephemeral (struct CadetTunnel *t,
786 const struct GNUNET_CADET_KX_Ephemeral *msg)
788 /* Check message size */
789 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
790 return GNUNET_SYSERR;
792 /* Check signature size */
793 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
794 return GNUNET_SYSERR;
797 if (0 != memcmp (&msg->origin_identity,
798 GCP_get_id (t->peer),
799 sizeof (struct GNUNET_PeerIdentity)))
800 return GNUNET_SYSERR;
802 /* Check signature */
804 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
807 &msg->origin_identity.public_key))
808 return GNUNET_SYSERR;
815 * Select the best key to use for encryption (send), based on KX status.
817 * Normally, return the current key. If there is a KX in progress and the old
818 * key is fresh enough, return the old key.
820 * @param t Tunnel to choose the key from.
822 * @return The optimal key to encrypt/hmac outgoing traffic.
824 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
825 select_key (const struct CadetTunnel *t)
827 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
829 if (NULL != t->kx_ctx
830 && NULL == t->kx_ctx->finish_task)
832 struct GNUNET_TIME_Relative age;
834 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
835 LOG (GNUNET_ERROR_TYPE_DEBUG,
836 " key exchange in progress, started %s ago\n",
837 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
838 // FIXME make duration of old keys configurable
839 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
841 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
842 key = &t->kx_ctx->e_key_old;
846 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
852 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
862 * @param plaintext Content to HMAC.
863 * @param size Size of @c plaintext.
864 * @param iv Initialization vector for the message.
865 * @param key Key to use.
866 * @param hmac[out] Destination to store the HMAC.
869 t_hmac (const void *plaintext, size_t size,
870 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
871 struct GNUNET_CADET_Hash *hmac)
873 static const char ctx[] = "cadet authentication key";
874 struct GNUNET_CRYPTO_AuthKey auth_key;
875 struct GNUNET_HashCode hash;
877 #if DUMP_KEYS_TO_STDERR
878 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC with key %s\n",
879 GNUNET_h2s ((struct GNUNET_HashCode *) key));
881 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
886 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
887 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
888 memcpy (hmac, &hash, sizeof (*hmac));
893 * Encrypt daforce_newest_keyta with the tunnel key.
895 * @param t Tunnel whose key to use.
896 * @param dst Destination for the encrypted data.
897 * @param src Source of the plaintext. Can overlap with @c dst.
898 * @param size Size of the plaintext.
899 * @param iv Initialization Vector to use.
900 * @param force_newest_key Force the use of the newest key, otherwise
901 * CADET will use the old key when allowed.
902 * This can happen in the case when a KX is going on
903 * and the old one hasn't expired.
906 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
907 size_t size, uint32_t iv, int force_newest_key)
909 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
910 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
913 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
915 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
916 #if DUMP_KEYS_TO_STDERR
917 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
918 GNUNET_h2s ((struct GNUNET_HashCode *) key));
920 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
921 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
922 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
923 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
932 * @param key Key to use.
933 * @param hash[out] Resulting HMAC.
934 * @param source Source key material (data to HMAC).
935 * @param len Length of @a source.
938 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
939 struct GNUNET_HashCode *hash,
940 void *source, unsigned int len)
942 static const char ctx[] = "axolotl HMAC-HASH";
943 struct GNUNET_CRYPTO_AuthKey auth_key;
945 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
948 GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
953 * Derive a key from a HMAC-HASH.
955 * @param key Key to use for the HMAC.
956 * @param out Key to generate.
957 * @param source Source key material (data to HMAC).
958 * @param len Length of @a source.
961 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
962 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
963 void *source, unsigned int len)
965 static const char ctx[] = "axolotl derive key";
966 struct GNUNET_HashCode h;
968 t_ax_hmac_hash (key, &h, source, len);
969 GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
970 &h, sizeof (h), NULL);
975 * Encrypt data with the axolotl tunnel key.
977 * @param t Tunnel whose key to use.
978 * @param dst Destination for the encrypted data.
979 * @param src Source of the plaintext. Can overlap with @c dst.
980 * @param size Size of the plaintext.
982 * @return Size of the encrypted data.
985 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
987 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
988 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
989 struct CadetTunnelAxolotl *ax;
992 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
996 if (GNUNET_YES == ax->ratchet_flag)
998 /* Advance ratchet */
999 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
1000 struct GNUNET_HashCode dh;
1001 struct GNUNET_HashCode hmac;
1002 static const char ctx[] = "axolotl ratchet";
1004 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
1007 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
1008 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
1009 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1010 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1011 &hmac, sizeof (hmac), NULL);
1018 ax->ratchet_flag = GNUNET_NO;
1021 t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
1022 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1024 #if DUMP_KEYS_TO_STDERR
1025 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC with key %s\n",
1026 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1029 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
1031 t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
1033 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1040 * Encrypt header with the axolotl header key.
1042 * @param t Tunnel whose key to use.
1043 * @param msg Message whose header to encrypt.
1046 t_h_encrypt (struct CadetTunnel *t, struct GNUNET_CADET_AX *msg)
1048 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1049 struct CadetTunnelAxolotl *ax;
1052 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_encrypt start\n");
1055 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKs, NULL, 0, NULL);
1057 #if DUMP_KEYS_TO_STDERR
1058 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC_H with key %s\n",
1059 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
1062 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns, AX_HEADER_SIZE,
1063 &ax->HKs, &iv, &msg->Ns);
1065 GNUNET_assert (AX_HEADER_SIZE == out_size);
1067 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1072 * Decrypt and verify data with the appropriate tunnel key.
1074 * @param key Key to use.
1075 * @param dst Destination for the plaintext.
1076 * @param src Source of the encrypted data. Can overlap with @c dst.
1077 * @param size Size of the encrypted data.
1078 * @param iv Initialization Vector to use.
1080 * @return Size of the decrypted data, -1 if an error was encountered.
1083 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1084 void *dst, const void *src, size_t size, uint32_t iv)
1086 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
1089 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
1090 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
1091 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
1092 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
1093 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
1094 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
1101 * Decrypt and verify data with the most recent tunnel key.
1103 * @param t Tunnel whose key to use.
1104 * @param dst Destination for the plaintext.
1105 * @param src Source of the encrypted data. Can overlap with @c dst.
1106 * @param size Size of the encrypted data.
1107 * @param iv Initialization Vector to use.
1109 * @return Size of the decrypted data, -1 if an error was encountered.
1112 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
1113 size_t size, uint32_t iv)
1117 #if DUMP_KEYS_TO_STDERR
1118 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
1119 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1121 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1123 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
1124 LOG (GNUNET_ERROR_TYPE_WARNING,
1125 "got data on %s without a valid key\n",
1127 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1131 out_size = decrypt (&t->d_key, dst, src, size, iv);
1138 * Decrypt and verify data with the appropriate tunnel key and verify that the
1139 * data has not been altered since it was sent by the remote peer.
1141 * @param t Tunnel whose key to use.
1142 * @param dst Destination for the plaintext.
1143 * @param src Source of the encrypted data. Can overlap with @c dst.
1144 * @param size Size of the encrypted data.
1145 * @param iv Initialization Vector to use.
1146 * @param msg_hmac HMAC of the message, cannot be NULL.
1148 * @return Size of the decrypted data, -1 if an error was encountered.
1151 t_decrypt_and_validate (struct CadetTunnel *t,
1152 void *dst, const void *src,
1153 size_t size, uint32_t iv,
1154 const struct GNUNET_CADET_Hash *msg_hmac)
1156 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1157 struct GNUNET_CADET_Hash hmac;
1160 /* Try primary (newest) key */
1162 decrypted_size = decrypt (key, dst, src, size, iv);
1163 t_hmac (src, size, iv, key, &hmac);
1164 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1165 return decrypted_size;
1167 /* If no key exchange is going on, we just failed. */
1168 if (NULL == t->kx_ctx)
1170 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1171 "Failed checksum validation on tunnel %s with no KX\n",
1173 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1177 /* Try secondary key, from previous KX period. */
1178 key = &t->kx_ctx->d_key_old;
1179 decrypted_size = decrypt (key, dst, src, size, iv);
1180 t_hmac (src, size, iv, key, &hmac);
1181 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1182 return decrypted_size;
1184 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1185 key = &t->kx_ctx->d_key_old2;
1186 decrypted_size = decrypt (key, dst, src, size, iv);
1187 t_hmac (src, size, iv, key, &hmac);
1188 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1189 return decrypted_size;
1191 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1192 "Failed checksum validation on tunnel %s with KX\n",
1194 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1199 * Decrypt and verify data with the appropriate tunnel key and verify that the
1200 * data has not been altered since it was sent by the remote peer.
1202 * @param t Tunnel whose key to use.
1203 * @param dst Destination for the plaintext.
1204 * @param src Source of the encrypted data. Can overlap with @c dst.
1205 * @param size Size of the encrypted data.
1206 * @param msg_hmac HMAC of the message, cannot be NULL.
1208 * @return Size of the decrypted data, -1 if an error was encountered.
1211 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1212 void *dst, const void *src, size_t size,
1213 const struct GNUNET_CADET_Hash *msg_hmac)
1215 struct CadetTunnelAxolotl *ax;
1232 * Create key material by doing ECDH on the local and remote ephemeral keys.
1234 * @param key_material Where to store the key material.
1235 * @param ephemeral_key Peer's public ephemeral key.
1238 derive_key_material (struct GNUNET_HashCode *key_material,
1239 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
1242 GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key,
1252 * Create a symmetic key from the identities of both ends and the key material
1255 * @param key Destination for the generated key.
1256 * @param sender ID of the peer that will encrypt with @c key.
1257 * @param receiver ID of the peer that will decrypt with @c key.
1258 * @param key_material Hash created with ECDH with the ephemeral keys.
1261 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1262 const struct GNUNET_PeerIdentity *sender,
1263 const struct GNUNET_PeerIdentity *receiver,
1264 const struct GNUNET_HashCode *key_material)
1266 const char salt[] = "CADET kx salt";
1268 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1269 salt, sizeof (salt),
1270 key_material, sizeof (struct GNUNET_HashCode),
1271 sender, sizeof (struct GNUNET_PeerIdentity),
1272 receiver, sizeof (struct GNUNET_PeerIdentity),
1278 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1280 * @param t Tunnel for which to create the keys.
1283 create_keys (struct CadetTunnel *t)
1285 struct GNUNET_HashCode km;
1287 derive_key_material (&km, &t->peers_ephemeral_key);
1288 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1289 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1290 #if DUMP_KEYS_TO_STDERR
1291 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1292 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
1293 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1294 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1295 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1296 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1297 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1298 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1299 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1305 * Create a new Key eXchange context for the tunnel.
1307 * If the old keys were verified, keep them for old traffic. Create a new KX
1308 * timestamp and a new nonce.
1310 * @param t Tunnel for which to create the KX ctx.
1313 create_kx_ctx (struct CadetTunnel *t)
1315 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1317 if (NULL != t->kx_ctx)
1319 if (NULL != t->kx_ctx->finish_task)
1321 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1322 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1323 t->kx_ctx->finish_task = NULL;
1328 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1329 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1333 if (CADET_TUNNEL_KEY_OK == t->estate)
1335 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1336 t->kx_ctx->d_key_old = t->d_key;
1337 t->kx_ctx->e_key_old = t->e_key;
1340 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1341 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1347 * @brief Finish the Key eXchange and destroy the old keys.
1349 * @param cls Closure (Tunnel for which to finish the KX).
1350 * @param tc Task context.
1353 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1355 struct CadetTunnel *t = cls;
1357 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1359 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1361 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1365 GNUNET_free (t->kx_ctx);
1371 * Destroy a Key eXchange context for the tunnel. This function only schedules
1372 * the destruction, the freeing of the memory (and clearing of old key material)
1373 * happens after a delay!
1375 * @param t Tunnel whose KX ctx to destroy.
1378 destroy_kx_ctx (struct CadetTunnel *t)
1380 struct GNUNET_TIME_Relative delay;
1382 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1385 if (is_key_null (&t->kx_ctx->e_key_old))
1387 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1391 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1392 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1394 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1400 * Pick a connection on which send the next data message.
1402 * @param t Tunnel on which to send the message.
1404 * @return The connection on which to send the next message.
1406 static struct CadetConnection *
1407 tunnel_get_connection (struct CadetTunnel *t)
1409 struct CadetTConnection *iter;
1410 struct CadetConnection *best;
1412 unsigned int lowest_q;
1414 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1416 lowest_q = UINT_MAX;
1417 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1419 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1420 GCC_2s (iter->c), GCC_get_state (iter->c));
1421 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1423 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1424 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1432 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1438 * Callback called when a queued message is sent.
1440 * Calculates the average time and connection packet tracking.
1442 * @param cls Closure (TunnelQueue handle).
1443 * @param c Connection this message was on.
1444 * @param q Connection queue handle (unused).
1445 * @param type Type of message sent.
1446 * @param fwd Was this a FWD going message?
1447 * @param size Size of the message.
1450 tun_message_sent (void *cls,
1451 struct CadetConnection *c,
1452 struct CadetConnectionQueue *q,
1453 uint16_t type, int fwd, size_t size)
1455 struct CadetTunnelQueue *qt = cls;
1456 struct CadetTunnel *t;
1458 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1460 GNUNET_assert (NULL != qt->cont);
1461 t = NULL == c ? NULL : GCC_get_tunnel (c);
1462 qt->cont (qt->cont_cls, t, qt, type, size);
1468 count_queued_data (const struct CadetTunnel *t)
1470 struct CadetTunnelDelayed *iter;
1473 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1480 * Delete a queued message: either was sent or the channel was destroyed
1481 * before the tunnel's key exchange had a chance to finish.
1483 * @param tqd Delayed queue handle.
1486 unqueue_data (struct CadetTunnelDelayed *tqd)
1488 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1494 * Cache a message to be sent once tunnel is online.
1496 * @param t Tunnel to hold the message.
1497 * @param msg Message itself (copy will be made).
1499 static struct CadetTunnelDelayed *
1500 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1502 struct CadetTunnelDelayed *tqd;
1503 uint16_t size = ntohs (msg->size);
1505 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1507 if (GNUNET_YES == is_ready (t))
1513 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1516 memcpy (&tqd[1], msg, size);
1517 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1523 * Sends an already built message on a tunnel, encrypting it and
1524 * choosing the best connection.
1526 * @param message Message to send. Function modifies it.
1527 * @param t Tunnel on which this message is transmitted.
1528 * @param c Connection to use (autoselect if NULL).
1529 * @param force Force the tunnel to take the message (buffer overfill).
1530 * @param cont Continuation to call once message is really sent.
1531 * @param cont_cls Closure for @c cont.
1532 * @param existing_q In case this a transmission of previously queued data,
1533 * this should be TunnelQueue given to the client.
1536 * @return Handle to cancel message.
1537 * NULL if @c cont is NULL or an error happens and message is dropped.
1539 static struct CadetTunnelQueue *
1540 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1541 struct CadetTunnel *t, struct CadetConnection *c,
1542 int force, GCT_sent cont, void *cont_cls,
1543 struct CadetTunnelQueue *existing_q)
1545 struct GNUNET_MessageHeader *msg;
1546 struct GNUNET_CADET_Encrypted *otr_msg;
1547 struct GNUNET_CADET_AX *ax_msg;
1548 struct CadetTunnelQueue *tq;
1549 size_t size = ntohs (message->size);
1550 const uint16_t max_overhead = sizeof (struct GNUNET_CADET_Encrypted)
1551 + sizeof (struct GNUNET_CADET_AX);
1552 char cbuf[max_overhead + size];
1559 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1561 if (GNUNET_NO == is_ready (t))
1563 struct CadetTunnelDelayed *tqd;
1564 /* A non null existing_q indicates sending of queued data.
1565 * Should only happen after tunnel becomes ready.
1567 GNUNET_assert (NULL == existing_q);
1568 tqd = queue_data (t, message);
1571 tq = GNUNET_new (struct CadetTunnelQueue);
1575 tq->cont_cls = cont_cls;
1579 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1581 if (CADET_Axolotl == t->enc_type)
1583 ax_msg = (struct GNUNET_CADET_AX *) cbuf;
1584 msg = &ax_msg->header;
1585 msg->size = htons (sizeof (struct GNUNET_CADET_AX) + size);
1586 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_AX);
1587 esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1588 ax_msg->Ns = htonl (t->ax->Ns++);
1589 ax_msg->PNs = htonl (t->ax->PNs);
1590 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1591 t_h_encrypt (t, ax_msg);
1592 t_hmac (&ax_msg->Ns, AX_HEADER_SIZE, 0, &t->ax->HKs, &ax_msg->hmac);
1596 otr_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1597 msg = &otr_msg->header;
1598 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1600 esize = t_encrypt (t, &otr_msg[1], message, size, iv, GNUNET_NO);
1601 t_hmac (&otr_msg[1], size, iv, select_key (t), &otr_msg->hmac);
1602 msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1603 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1605 GNUNET_assert (esize == size);
1608 c = tunnel_get_connection (t);
1611 /* Why is tunnel 'ready'? Should have been queued! */
1612 if (NULL != t->destroy_task)
1615 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1617 return NULL; /* Drop... */
1621 type = ntohs (message->type);
1624 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1625 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1626 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1627 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1629 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1631 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1632 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1633 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1634 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1635 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1639 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1641 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1643 fwd = GCC_is_origin (c, GNUNET_YES);
1647 GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type,
1648 mid, c, fwd, force, NULL, NULL));
1651 if (NULL == existing_q)
1653 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1660 tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1661 &tun_message_sent, tq);
1662 GNUNET_assert (NULL != tq->cq);
1664 tq->cont_cls = cont_cls;
1671 * Send all cached messages that we can, tunnel is online.
1673 * @param t Tunnel that holds the messages. Cannot be loopback.
1676 send_queued_data (struct CadetTunnel *t)
1678 struct CadetTunnelDelayed *tqd;
1679 struct CadetTunnelDelayed *next;
1682 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1684 if (GCT_is_loopback (t))
1690 if (GNUNET_NO == is_ready (t))
1692 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1693 estate2s (t->estate), cstate2s (t->cstate));
1697 room = GCT_get_connections_buffer (t);
1698 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1699 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1700 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1702 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1705 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1706 tqd->t, NULL, GNUNET_YES,
1707 NULL != tqd->tq ? tqd->tq->cont : NULL,
1708 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1712 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1717 * Callback called when a queued message is sent.
1719 * @param cls Closure.
1720 * @param c Connection this message was on.
1721 * @param type Type of message sent.
1722 * @param fwd Was this a FWD going message?
1723 * @param size Size of the message.
1726 ephm_sent (void *cls,
1727 struct CadetConnection *c,
1728 struct CadetConnectionQueue *q,
1729 uint16_t type, int fwd, size_t size)
1731 struct CadetTunnel *t = cls;
1732 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
1737 * Callback called when a queued message is sent.
1739 * @param cls Closure.
1740 * @param c Connection this message was on.
1741 * @param type Type of message sent.
1742 * @param fwd Was this a FWD going message?
1743 * @param size Size of the message.
1746 pong_sent (void *cls,
1747 struct CadetConnection *c,
1748 struct CadetConnectionQueue *q,
1749 uint16_t type, int fwd, size_t size)
1751 struct CadetTunnel *t = cls;
1752 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
1758 * Sends key exchange message on a tunnel, choosing the best connection.
1759 * Should not be called on loopback tunnels.
1761 * @param t Tunnel on which this message is transmitted.
1762 * @param message Message to send. Function modifies it.
1764 * @return Handle to the message in the connection queue.
1766 static struct CadetConnectionQueue *
1767 send_kx (struct CadetTunnel *t,
1768 const struct GNUNET_MessageHeader *message)
1770 struct CadetConnection *c;
1771 struct GNUNET_CADET_KX *msg;
1772 size_t size = ntohs (message->size);
1773 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1778 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1780 /* Avoid loopback. */
1781 if (GCT_is_loopback (t))
1786 type = ntohs (message->type);
1788 /* Even if tunnel is "being destroyed", send anyway.
1789 * Could be a response to a rekey initiated by remote peer,
1790 * who is trying to create a new channel!
1793 /* Must have a connection, or be looking for one. */
1794 if (NULL == t->connection_head)
1796 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
1797 if (CADET_TUNNEL_SEARCHING != t->cstate)
1800 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1801 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
1806 msg = (struct GNUNET_CADET_KX *) cbuf;
1807 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1808 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1809 c = tunnel_get_connection (t);
1812 if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
1815 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1821 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1822 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
1823 GNUNET_assert (NULL == t->ephm_h);
1826 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1827 GNUNET_assert (NULL == t->pong_h);
1832 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
1835 memcpy (&msg[1], message, size);
1837 fwd = GCC_is_origin (c, GNUNET_YES);
1839 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
1846 * Send the ephemeral key on a tunnel.
1848 * @param t Tunnel on which to send the key.
1851 send_ephemeral (struct CadetTunnel *t)
1853 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1854 if (NULL != t->ephm_h)
1856 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1860 otr_kx_msg.sender_status = htonl (t->estate);
1861 otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1862 otr_kx_msg.nonce = t->kx_ctx->challenge;
1863 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", otr_kx_msg.nonce);
1864 t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
1865 ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
1866 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", otr_kx_msg.nonce);
1867 t->ephm_h = send_kx (t, &otr_kx_msg.header);
1872 * Send a pong message on a tunnel.
1874 * @param t Tunnel on which to send the pong.
1875 * @param challenge Value sent in the ping that we have to send back.
1878 send_pong (struct CadetTunnel *t, uint32_t challenge)
1880 struct GNUNET_CADET_KX_Pong msg;
1882 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1883 if (NULL != t->pong_h)
1885 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1888 msg.header.size = htons (sizeof (msg));
1889 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1890 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1891 msg.nonce = challenge;
1892 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1893 t_encrypt (t, &msg.nonce, &msg.nonce,
1894 sizeof (msg.nonce), msg.iv, GNUNET_YES);
1895 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1897 t->pong_h = send_kx (t, &msg.header);
1902 * Initiate a rekey with the remote peer.
1904 * @param cls Closure (tunnel).
1905 * @param tc TaskContext.
1908 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1910 struct CadetTunnel *t = cls;
1912 t->rekey_task = NULL;
1914 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1915 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1918 GNUNET_assert (NULL != t->kx_ctx);
1919 struct GNUNET_TIME_Relative duration;
1921 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1922 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1923 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1925 // FIXME make duration of old keys configurable
1926 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1928 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
1929 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1930 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1937 case CADET_TUNNEL_KEY_UNINITIALIZED:
1938 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
1941 case CADET_TUNNEL_KEY_SENT:
1944 case CADET_TUNNEL_KEY_OK:
1946 * - state should have changed during rekey_iterator
1947 * - task should have been canceled at pong_handle
1950 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1953 case CADET_TUNNEL_KEY_PING:
1954 case CADET_TUNNEL_KEY_REKEY:
1958 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1961 // FIXME exponential backoff
1962 struct GNUNET_TIME_Relative delay;
1964 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1965 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1966 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1967 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1968 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1973 * Our ephemeral key has changed, create new session key on all tunnels.
1975 * Each tunnel will start the Key Exchange with a random delay between
1976 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1977 * per second, on average.
1979 * @param cls Closure (size of the hashmap).
1980 * @param key Current public key.
1981 * @param value Value in the hash map (tunnel).
1983 * @return #GNUNET_YES, so we should continue to iterate,
1986 rekey_iterator (void *cls,
1987 const struct GNUNET_PeerIdentity *key,
1990 struct CadetTunnel *t = value;
1991 struct GNUNET_TIME_Relative delay;
1992 long n = (long) cls;
1995 if (NULL != t->rekey_task)
1998 if (GNUNET_YES == GCT_is_loopback (t))
2001 if (CADET_OTR != t->enc_type)
2004 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2005 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2006 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2008 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2015 * Create a new ephemeral key and key message, schedule next rekeying.
2017 * @param cls Closure (unused).
2018 * @param tc TaskContext.
2021 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2023 struct GNUNET_TIME_Absolute time;
2028 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2031 GNUNET_free_non_null (otr_ephemeral_key);
2032 otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2034 time = GNUNET_TIME_absolute_get ();
2035 otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2036 time = GNUNET_TIME_absolute_add (time, rekey_period);
2037 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2038 otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2039 GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2040 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2041 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
2043 GNUNET_assert (GNUNET_OK ==
2044 GNUNET_CRYPTO_eddsa_sign (id_key,
2045 &otr_kx_msg.purpose,
2046 &otr_kx_msg.signature));
2048 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2049 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2051 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2052 &global_otr_rekey, NULL);
2057 * Called only on shutdown, destroy every tunnel.
2059 * @param cls Closure (unused).
2060 * @param key Current public key.
2061 * @param value Value in the hash map (tunnel).
2063 * @return #GNUNET_YES, so we should continue to iterate,
2066 destroy_iterator (void *cls,
2067 const struct GNUNET_PeerIdentity *key,
2070 struct CadetTunnel *t = value;
2072 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2079 * Notify remote peer that we don't know a channel he is talking about,
2080 * probably CHANNEL_DESTROY was missed.
2082 * @param t Tunnel on which to notify.
2083 * @param gid ID of the channel.
2086 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2088 struct GNUNET_CADET_ChannelManage msg;
2090 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2091 msg.header.size = htons (sizeof (msg));
2092 msg.chid = htonl (gid);
2094 LOG (GNUNET_ERROR_TYPE_DEBUG,
2095 "WARNING destroying unknown channel %u on tunnel %s\n",
2097 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2102 * Demultiplex data per channel and call appropriate channel handler.
2104 * @param t Tunnel on which the data came.
2105 * @param msg Data message.
2106 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2107 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2108 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2109 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2112 handle_data (struct CadetTunnel *t,
2113 const struct GNUNET_CADET_Data *msg,
2116 struct CadetChannel *ch;
2120 size = ntohs (msg->header.size);
2122 sizeof (struct GNUNET_CADET_Data) +
2123 sizeof (struct GNUNET_MessageHeader))
2128 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2129 GC_m2s (ntohs (msg[1].header.type)));
2132 ch = GCT_get_channel (t, ntohl (msg->chid));
2135 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2137 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2139 send_channel_destroy (t, ntohl (msg->chid));
2143 GCCH_handle_data (ch, msg, fwd);
2148 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2150 * @param t Tunnel on which the DATA ACK came.
2151 * @param msg DATA ACK message.
2152 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2153 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2154 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2155 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2158 handle_data_ack (struct CadetTunnel *t,
2159 const struct GNUNET_CADET_DataACK *msg,
2162 struct CadetChannel *ch;
2166 size = ntohs (msg->header.size);
2167 if (size != sizeof (struct GNUNET_CADET_DataACK))
2174 ch = GCT_get_channel (t, ntohl (msg->chid));
2177 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2179 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2184 GCCH_handle_data_ack (ch, msg, fwd);
2189 * Handle channel create.
2191 * @param t Tunnel on which the data came.
2192 * @param msg Data message.
2195 handle_ch_create (struct CadetTunnel *t,
2196 const struct GNUNET_CADET_ChannelCreate *msg)
2198 struct CadetChannel *ch;
2202 size = ntohs (msg->header.size);
2203 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2210 ch = GCT_get_channel (t, ntohl (msg->chid));
2211 if (NULL != ch && ! GCT_is_loopback (t))
2213 /* Probably a retransmission, safe to ignore */
2214 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2216 ch = GCCH_handle_create (t, msg);
2218 GCT_add_channel (t, ch);
2224 * Handle channel NACK: check correctness and call channel handler for NACKs.
2226 * @param t Tunnel on which the NACK came.
2227 * @param msg NACK message.
2230 handle_ch_nack (struct CadetTunnel *t,
2231 const struct GNUNET_CADET_ChannelManage *msg)
2233 struct CadetChannel *ch;
2237 size = ntohs (msg->header.size);
2238 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2245 ch = GCT_get_channel (t, ntohl (msg->chid));
2248 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2250 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2255 GCCH_handle_nack (ch);
2260 * Handle a CHANNEL ACK (SYNACK/ACK).
2262 * @param t Tunnel on which the CHANNEL ACK came.
2263 * @param msg CHANNEL ACK message.
2264 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2265 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2266 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2267 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2270 handle_ch_ack (struct CadetTunnel *t,
2271 const struct GNUNET_CADET_ChannelManage *msg,
2274 struct CadetChannel *ch;
2278 size = ntohs (msg->header.size);
2279 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2286 ch = GCT_get_channel (t, ntohl (msg->chid));
2289 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2291 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2296 GCCH_handle_ack (ch, msg, fwd);
2301 * Handle a channel destruction message.
2303 * @param t Tunnel on which the message came.
2304 * @param msg Channel destroy message.
2305 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2306 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2307 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2308 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2311 handle_ch_destroy (struct CadetTunnel *t,
2312 const struct GNUNET_CADET_ChannelManage *msg,
2315 struct CadetChannel *ch;
2319 size = ntohs (msg->header.size);
2320 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2327 ch = GCT_get_channel (t, ntohl (msg->chid));
2330 /* Probably a retransmission, safe to ignore */
2334 GCCH_handle_destroy (ch, msg, fwd);
2339 * Create a new Axolotl ephemeral (ratchet) key.
2344 new_ephemeral (struct CadetTunnel *t)
2346 GNUNET_free_non_null (t->ax->DHRs);
2347 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2352 * Free Axolotl data.
2357 destroy_ax (struct CadetTunnel *t)
2362 GNUNET_free_non_null (t->ax->DHRs);
2363 GNUNET_free_non_null (t->ax->kx_0);
2365 GNUNET_free (t->ax);
2372 * The peer's ephemeral key has changed: update the symmetrical keys.
2374 * @param t Tunnel this message came on.
2375 * @param msg Key eXchange message.
2378 handle_ephemeral (struct CadetTunnel *t,
2379 const struct GNUNET_CADET_KX_Ephemeral *msg)
2381 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2383 if (GNUNET_OK != check_ephemeral (t, msg))
2385 GNUNET_break_op (0);
2389 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2393 t->enc_type = CADET_OTR;
2394 if (NULL != t->rekey_task)
2395 GNUNET_SCHEDULER_cancel (t->rekey_task);
2397 rekey_tunnel (t, NULL);
2401 * If the key is different from what we know, derive the new E/D keys.
2402 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2404 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2405 sizeof (msg->ephemeral_key)))
2407 #if DUMP_KEYS_TO_STDERR
2408 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2409 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2410 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2411 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2413 t->peers_ephemeral_key = msg->ephemeral_key;
2417 if (CADET_TUNNEL_KEY_OK == t->estate)
2419 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2421 if (NULL != t->rekey_task)
2422 GNUNET_SCHEDULER_cancel (t->rekey_task);
2423 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2425 if (CADET_TUNNEL_KEY_SENT == t->estate)
2427 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2429 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2432 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2436 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2437 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2438 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2439 send_pong (t, nonce);
2445 * Peer has answer to our challenge.
2446 * If answer is successful, consider the key exchange finished and clean
2447 * up all related state.
2449 * @param t Tunnel this message came on.
2450 * @param msg Key eXchange Pong message.
2453 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2457 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2458 if (NULL == t->rekey_task)
2460 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2463 if (NULL == t->kx_ctx)
2465 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2469 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2470 if (challenge != t->kx_ctx->challenge)
2472 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2473 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2474 challenge, msg->nonce, t->kx_ctx->challenge);
2478 GNUNET_SCHEDULER_cancel (t->rekey_task);
2479 t->rekey_task = NULL;
2481 /* Don't free the old keys right away, but after a delay.
2482 * Rationale: the KX could have happened over a very fast connection,
2483 * with payload traffic still signed with the old key stuck in a slower
2485 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2489 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2494 * Handle Axolotl handshake.
2496 * @param t Tunnel this message came on.
2497 * @param msg Key eXchange Pong message.
2500 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2502 struct CadetTunnelAxolotl *ax;
2503 struct GNUNET_HashCode key_material[3];
2504 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2505 const struct GNUNET_CRYPTO_EcdhePublicKey *pub;
2506 const struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
2507 const char salt[] = "CADET Axolotl salt";
2508 const struct GNUNET_PeerIdentity *pid;
2511 LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2515 /* Something is wrong if ax is NULL. Whose fault it is? */
2516 GNUNET_break_op (CADET_OTR == t->enc_type);
2517 GNUNET_break (CADET_Axolotl == t->enc_type);
2521 if (GNUNET_OK != GCP_check_key (t->peer, &msg->permanent_key,
2522 &msg->purpose, &msg->signature))
2524 GNUNET_break_op (0);
2528 pid = GCT_get_destination (t);
2529 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2530 am_I_alice = GNUNET_YES;
2531 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2532 am_I_alice = GNUNET_NO;
2535 GNUNET_break_op (0);
2539 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2542 ax->DHRr = msg->ratchet_key;
2543 ax->DHIr = msg->permanent_key;
2546 if (GNUNET_YES == am_I_alice)
2548 priv = ax_key; /* A */
2549 pub = &msg->ephemeral_key; /* B0 */
2553 priv = ax->kx_0; /* B0 */
2554 pub = &ax->DHIr; /* A */
2556 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[0]);
2559 if (GNUNET_YES == am_I_alice)
2561 priv = ax->kx_0; /* A0 */
2562 pub = &ax->DHIr; /* B */
2566 priv = ax_key; /* B */
2567 pub = &msg->ephemeral_key; /* A0 */
2569 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[1]);
2572 priv = ax->kx_0; /* A0 or B0 */
2573 pub = &msg->ephemeral_key; /* B0 or A0 */
2574 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[2]);
2576 #if DUMP_KEYS_TO_STDERR
2579 for (i = 0; i < 3; i++)
2580 LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2581 i, GNUNET_h2s (&key_material[i]));
2586 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2587 salt, sizeof (salt),
2588 &key_material, sizeof (key_material), NULL);
2591 if (GNUNET_YES == am_I_alice)
2597 ax->ratchet_flag = GNUNET_YES;
2605 ax->ratchet_flag = GNUNET_NO;
2607 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2612 * Demultiplex by message type and call appropriate handler for a message
2613 * towards a channel of a local tunnel.
2615 * @param t Tunnel this message came on.
2616 * @param msgh Message header.
2617 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2618 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2619 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2620 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2623 handle_decrypted (struct CadetTunnel *t,
2624 const struct GNUNET_MessageHeader *msgh,
2629 type = ntohs (msgh->type);
2630 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2634 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2635 /* Do nothing, connection aleady got updated. */
2636 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2639 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2640 /* Don't send hop ACK, wait for client to ACK */
2641 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2644 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2645 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2648 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2649 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2652 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2653 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
2656 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2657 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2660 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2661 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2665 GNUNET_break_op (0);
2666 LOG (GNUNET_ERROR_TYPE_WARNING,
2667 "end-to-end message not known (%u)\n",
2668 ntohs (msgh->type));
2669 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2673 /******************************************************************************/
2674 /******************************** API ***********************************/
2675 /******************************************************************************/
2677 * Decrypt old format and demultiplex by message type. Call appropriate handler
2678 * for a message towards a channel of a local tunnel.
2680 * @param t Tunnel this message came on.
2681 * @param msg Message header.
2684 GCT_handle_encrypted (struct CadetTunnel *t,
2685 const struct GNUNET_MessageHeader *msg)
2687 uint16_t size = ntohs (msg->size);
2689 size_t payload_size;
2692 struct GNUNET_MessageHeader *msgh;
2695 type = ntohs (msg->type);
2696 if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
2698 const struct GNUNET_CADET_Encrypted *emsg;
2700 emsg = (struct GNUNET_CADET_Encrypted *) msg;
2701 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2702 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
2703 emsg->iv, &emsg->hmac);
2705 else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
2707 const struct GNUNET_CADET_AX *emsg;
2709 emsg = (struct GNUNET_CADET_AX *) msg;
2710 payload_size = size - sizeof (struct GNUNET_CADET_AX);
2711 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, &emsg[1],
2712 payload_size, &emsg->hmac);
2715 if (-1 == decrypted_size)
2717 GNUNET_break_op (0);
2722 while (off < decrypted_size)
2726 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2727 msize = ntohs (msgh->size);
2728 if (msize < sizeof (struct GNUNET_MessageHeader))
2730 GNUNET_break_op (0);
2733 handle_decrypted (t, msgh, GNUNET_SYSERR);
2740 * Demultiplex an encapsulated KX message by message type.
2742 * @param t Tunnel on which the message came.
2743 * @param message Payload of KX message.
2746 GCT_handle_kx (struct CadetTunnel *t,
2747 const struct GNUNET_MessageHeader *message)
2751 type = ntohs (message->type);
2752 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
2755 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2756 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
2759 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2760 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
2763 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2764 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
2768 GNUNET_break_op (0);
2769 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
2774 * Initialize the tunnel subsystem.
2776 * @param c Configuration handle.
2777 * @param key ECC private key, to derive all other keys and do crypto.
2780 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2781 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2783 int expected_overhead;
2785 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2787 expected_overhead = 0;
2788 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
2789 expected_overhead += sizeof (struct GNUNET_CADET_Data);
2790 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
2791 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2794 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2797 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2798 "CADET", "DEFAULT_TTL", "USING DEFAULT");
2802 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2805 rekey_period = GNUNET_TIME_UNIT_DAYS;
2810 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
2811 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2812 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2813 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2814 otr_kx_msg.origin_identity = my_full_id;
2815 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
2817 ax_key = GNUNET_CRYPTO_ecdhe_key_create ();
2818 GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &ax_identity.permanent_key);
2819 ax_identity.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_AXKX);
2820 ax_identity.purpose.size = htonl (ax_purpose_size ());
2821 GNUNET_assert (GNUNET_OK ==
2822 GNUNET_CRYPTO_eddsa_sign (id_key,
2823 &ax_identity.purpose,
2824 &ax_identity.signature));
2826 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2831 * Shut down the tunnel subsystem.
2836 if (NULL != rekey_task)
2838 GNUNET_SCHEDULER_cancel (rekey_task);
2841 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2842 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2843 GNUNET_free (ax_key);
2850 * @param destination Peer this tunnel is towards.
2852 struct CadetTunnel *
2853 GCT_new (struct CadetPeer *destination)
2855 struct CadetTunnel *t;
2857 t = GNUNET_new (struct CadetTunnel);
2859 t->peer = destination;
2862 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2863 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2869 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
2871 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2877 * Change the tunnel's connection state.
2879 * @param t Tunnel whose connection state to change.
2880 * @param cstate New connection state.
2883 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2887 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2888 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2889 if (myid != GCP_get_short_id (t->peer) &&
2890 CADET_TUNNEL_READY != t->cstate &&
2891 CADET_TUNNEL_READY == cstate)
2894 if (CADET_TUNNEL_KEY_OK == t->estate)
2896 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2897 send_queued_data (t);
2899 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2901 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
2906 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
2911 if (CADET_TUNNEL_READY == cstate
2912 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2914 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2915 GCP_stop_search (t->peer);
2921 * Change the tunnel encryption state.
2923 * @param t Tunnel whose encryption state to change, or NULL.
2924 * @param state New encryption state.
2927 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2929 enum CadetTunnelEState old;
2936 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2937 GCP_2s (t->peer), estate2s (old));
2938 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2939 GCP_2s (t->peer), estate2s (t->estate));
2941 /* Send queued data if enc state changes to OK */
2942 if (myid != GCP_get_short_id (t->peer) &&
2943 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
2945 send_queued_data (t);
2951 * @brief Check if tunnel has too many connections, and remove one if necessary.
2953 * Currently this means the newest connection, unless it is a direct one.
2954 * Implemented as a task to avoid freeing a connection that is in the middle
2955 * of being created/processed.
2957 * @param cls Closure (Tunnel to check).
2958 * @param tc Task context.
2961 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2963 struct CadetTunnel *t = cls;
2965 t->trim_connections_task = NULL;
2967 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2970 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2972 struct CadetTConnection *iter;
2973 struct CadetTConnection *c;
2975 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2977 if ((iter->created.abs_value_us > c->created.abs_value_us)
2978 && GNUNET_NO == GCC_is_direct (iter->c))
2985 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2987 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3000 * Add a connection to a tunnel.
3003 * @param c Connection.
3006 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3008 struct CadetTConnection *aux;
3010 GNUNET_assert (NULL != c);
3012 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3013 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3014 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3018 aux = GNUNET_new (struct CadetTConnection);
3020 aux->created = GNUNET_TIME_absolute_get ();
3022 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3024 if (CADET_TUNNEL_SEARCHING == t->cstate)
3025 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3027 if (NULL != t->trim_connections_task)
3028 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3033 * Remove a connection from a tunnel.
3036 * @param c Connection.
3039 GCT_remove_connection (struct CadetTunnel *t,
3040 struct CadetConnection *c)
3042 struct CadetTConnection *aux;
3043 struct CadetTConnection *next;
3046 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3047 GCC_2s (c), GCT_2s (t));
3048 for (aux = t->connection_head; aux != NULL; aux = next)
3053 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3058 conns = GCT_count_connections (t);
3060 && NULL == t->destroy_task
3061 && CADET_TUNNEL_SHUTDOWN != t->cstate
3062 && GNUNET_NO == shutting_down)
3064 if (0 == GCT_count_any_connections (t))
3065 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3067 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3070 /* Start new connections if needed */
3071 if (CONNECTIONS_PER_TUNNEL > conns
3072 && NULL == t->destroy_task
3073 && CADET_TUNNEL_SHUTDOWN != t->cstate
3074 && GNUNET_NO == shutting_down)
3076 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
3077 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3081 /* If not marked as ready, no change is needed */
3082 if (CADET_TUNNEL_READY != t->cstate)
3085 /* Check if any connection is ready to maintain cstate */
3086 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3087 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3093 * Add a channel to a tunnel.
3096 * @param ch Channel.
3099 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3101 struct CadetTChannel *aux;
3103 GNUNET_assert (NULL != ch);
3105 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3107 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3109 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
3114 aux = GNUNET_new (struct CadetTChannel);
3116 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3117 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3119 if (NULL != t->destroy_task)
3121 GNUNET_SCHEDULER_cancel (t->destroy_task);
3122 t->destroy_task = NULL;
3123 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3129 * Remove a channel from a tunnel.
3132 * @param ch Channel.
3135 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3137 struct CadetTChannel *aux;
3139 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3140 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3144 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3145 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3154 * Search for a channel by global ID.
3156 * @param t Tunnel containing the channel.
3157 * @param chid Public channel number.
3159 * @return channel handler, NULL if doesn't exist
3161 struct CadetChannel *
3162 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3164 struct CadetTChannel *iter;
3169 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3171 if (GCCH_get_id (iter->ch) == chid)
3175 return NULL == iter ? NULL : iter->ch;
3180 * @brief Destroy a tunnel and free all resources.
3182 * Should only be called a while after the tunnel has been marked as destroyed,
3183 * in case there is a new channel added to the same peer shortly after marking
3184 * the tunnel. This way we avoid a new public key handshake.
3186 * @param cls Closure (tunnel to destroy).
3187 * @param tc Task context.
3190 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3192 struct CadetTunnel *t = cls;
3193 struct CadetTConnection *iter;
3195 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3196 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3198 LOG (GNUNET_ERROR_TYPE_WARNING,
3199 "Not destroying tunnel, due to shutdown. "
3200 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3203 t->destroy_task = NULL;
3204 t->cstate = CADET_TUNNEL_SHUTDOWN;
3206 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3208 GCC_send_destroy (iter->c);
3215 * Tunnel is empty: destroy it.
3217 * Notifies all connections about the destruction.
3219 * @param t Tunnel to destroy.
3222 GCT_destroy_empty (struct CadetTunnel *t)
3224 if (GNUNET_YES == shutting_down)
3225 return; /* Will be destroyed immediately anyway */
3227 if (NULL != t->destroy_task)
3229 LOG (GNUNET_ERROR_TYPE_WARNING,
3230 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3232 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3234 /* should never happen, tunnel can only become empty once, and the
3235 * task identifier should be NO_TASK (cleaned when the tunnel was created
3236 * or became un-empty)
3241 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3244 // FIXME make delay a config option
3245 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3246 &delayed_destroy, t);
3247 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3248 t, t->destroy_task);
3253 * Destroy tunnel if empty (no more channels).
3255 * @param t Tunnel to destroy if empty.
3258 GCT_destroy_if_empty (struct CadetTunnel *t)
3260 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3261 if (0 < GCT_count_channels (t))
3264 GCT_destroy_empty (t);
3269 * Destroy the tunnel.
3271 * This function does not generate any warning traffic to clients or peers.
3274 * Cancel messages belonging to this tunnel queued to neighbors.
3275 * Free any allocated resources linked to the tunnel.
3277 * @param t The tunnel to destroy.
3280 GCT_destroy (struct CadetTunnel *t)
3282 struct CadetTConnection *iter_c;
3283 struct CadetTConnection *next_c;
3284 struct CadetTChannel *iter_ch;
3285 struct CadetTChannel *next_ch;
3290 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3292 GNUNET_break (GNUNET_YES ==
3293 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3294 GCP_get_id (t->peer), t));
3296 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3298 next_c = iter_c->next;
3299 GCC_destroy (iter_c->c);
3301 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3303 next_ch = iter_ch->next;
3304 GCCH_destroy (iter_ch->ch);
3305 /* Should only happen on shutdown, but it's ok. */
3308 if (NULL != t->destroy_task)
3310 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3311 GNUNET_SCHEDULER_cancel (t->destroy_task);
3312 t->destroy_task = NULL;
3315 if (NULL != t->trim_connections_task)
3317 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3318 t->trim_connections_task);
3319 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3320 t->trim_connections_task = NULL;
3323 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3324 GCP_set_tunnel (t->peer, NULL);
3326 if (NULL != t->rekey_task)
3328 GNUNET_SCHEDULER_cancel (t->rekey_task);
3329 t->rekey_task = NULL;
3331 if (NULL != t->kx_ctx)
3333 if (NULL != t->kx_ctx->finish_task)
3334 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3335 GNUNET_free (t->kx_ctx);
3346 * @brief Use the given path for the tunnel.
3347 * Update the next and prev hops (and RCs).
3348 * (Re)start the path refresh in case the tunnel is locally owned.
3350 * @param t Tunnel to update.
3351 * @param p Path to use.
3353 * @return Connection created.
3355 struct CadetConnection *
3356 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3358 struct CadetConnection *c;
3359 struct GNUNET_CADET_Hash cid;
3360 unsigned int own_pos;
3362 if (NULL == t || NULL == p)
3368 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3374 for (own_pos = 0; own_pos < p->length; own_pos++)
3376 if (p->peers[own_pos] == myid)
3379 if (own_pos >= p->length)
3381 GNUNET_break_op (0);
3385 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3386 c = GCC_new (&cid, t, p, own_pos);
3389 /* Path was flawed */
3392 GCT_add_connection (t, c);
3398 * Count all created connections of a tunnel. Not necessarily ready connections!
3400 * @param t Tunnel on which to count.
3402 * @return Number of connections created, either being established or ready.
3405 GCT_count_any_connections (struct CadetTunnel *t)
3407 struct CadetTConnection *iter;
3413 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3421 * Count established (ready) connections of a tunnel.
3423 * @param t Tunnel on which to count.
3425 * @return Number of connections.
3428 GCT_count_connections (struct CadetTunnel *t)
3430 struct CadetTConnection *iter;
3436 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3437 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3445 * Count channels of a tunnel.
3447 * @param t Tunnel on which to count.
3449 * @return Number of channels.
3452 GCT_count_channels (struct CadetTunnel *t)
3454 struct CadetTChannel *iter;
3457 for (count = 0, iter = t->channel_head;
3459 iter = iter->next, count++) /* skip */;
3466 * Get the connectivity state of a tunnel.
3470 * @return Tunnel's connectivity state.
3472 enum CadetTunnelCState
3473 GCT_get_cstate (struct CadetTunnel *t)
3478 return (enum CadetTunnelCState) -1;
3485 * Get the encryption state of a tunnel.
3489 * @return Tunnel's encryption state.
3491 enum CadetTunnelEState
3492 GCT_get_estate (struct CadetTunnel *t)
3497 return (enum CadetTunnelEState) -1;
3503 * Get the maximum buffer space for a tunnel towards a local client.
3507 * @return Biggest buffer space offered by any channel in the tunnel.
3510 GCT_get_channels_buffer (struct CadetTunnel *t)
3512 struct CadetTChannel *iter;
3513 unsigned int buffer;
3514 unsigned int ch_buf;
3516 if (NULL == t->channel_head)
3518 /* Probably getting buffer for a channel create/handshake. */
3519 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3524 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3526 ch_buf = get_channel_buffer (iter);
3527 if (ch_buf > buffer)
3535 * Get the total buffer space for a tunnel for P2P traffic.
3539 * @return Buffer space offered by all connections in the tunnel.
3542 GCT_get_connections_buffer (struct CadetTunnel *t)
3544 struct CadetTConnection *iter;
3545 unsigned int buffer;
3547 if (GNUNET_NO == is_ready (t))
3549 if (count_queued_data (t) > 3)
3556 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3558 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3562 buffer += get_connection_buffer (iter);
3570 * Get the tunnel's destination.
3574 * @return ID of the destination peer.
3576 const struct GNUNET_PeerIdentity *
3577 GCT_get_destination (struct CadetTunnel *t)
3579 return GCP_get_id (t->peer);
3584 * Get the tunnel's next free global channel ID.
3588 * @return GID of a channel free to use.
3591 GCT_get_next_chid (struct CadetTunnel *t)
3593 CADET_ChannelNumber chid;
3594 CADET_ChannelNumber mask;
3597 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3598 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3599 * If peer's ID is bigger, start at 0x4... bit 30 = 1
3601 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3606 t->next_chid |= mask;
3608 while (NULL != GCT_get_channel (t, t->next_chid))
3610 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3611 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3612 t->next_chid |= mask;
3614 chid = t->next_chid;
3615 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3616 t->next_chid |= mask;
3623 * Send ACK on one or more channels due to buffer in connections.
3625 * @param t Channel which has some free buffer space.
3628 GCT_unchoke_channels (struct CadetTunnel *t)
3630 struct CadetTChannel *iter;
3631 unsigned int buffer;
3632 unsigned int channels = GCT_count_channels (t);
3633 unsigned int choked_n;
3634 struct CadetChannel *choked[channels];
3636 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3637 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3638 if (NULL != t->channel_head)
3639 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3641 /* Get buffer space */
3642 buffer = GCT_get_connections_buffer (t);
3648 /* Count and remember choked channels */
3650 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3652 if (GNUNET_NO == get_channel_allowed (iter))
3654 choked[choked_n++] = iter->ch;
3658 /* Unchoke random channels */
3659 while (0 < buffer && 0 < choked_n)
3661 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3663 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3666 choked[r] = choked[choked_n];
3672 * Send ACK on one or more connections due to buffer space to the client.
3674 * Iterates all connections of the tunnel and sends ACKs appropriately.
3679 GCT_send_connection_acks (struct CadetTunnel *t)
3681 struct CadetTConnection *iter;
3684 uint32_t allow_per_connection;
3686 unsigned int buffer;
3688 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3697 if (CADET_TUNNEL_READY != t->cstate)
3700 buffer = GCT_get_channels_buffer (t);
3701 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
3703 /* Count connections, how many messages are already allowed */
3704 cs = GCT_count_connections (t);
3705 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3707 allowed += get_connection_allowed (iter);
3709 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
3711 /* Make sure there is no overflow */
3712 if (allowed > buffer)
3715 /* Authorize connections to send more data */
3716 to_allow = buffer - allowed;
3718 for (iter = t->connection_head;
3719 NULL != iter && to_allow > 0;
3722 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3723 || get_connection_allowed (iter) > 64 / 3)
3727 allow_per_connection = to_allow/cs;
3728 to_allow -= allow_per_connection;
3730 GCC_allow (iter->c, allow_per_connection,
3731 GCC_is_origin (iter->c, GNUNET_NO));
3736 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
3737 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
3743 * Cancel a previously sent message while it's in the queue.
3745 * ONLY can be called before the continuation given to the send function
3746 * is called. Once the continuation is called, the message is no longer in the
3749 * @param q Handle to the queue.
3752 GCT_cancel (struct CadetTunnelQueue *q)
3757 /* tun_message_sent() will be called and free q */
3759 else if (NULL != q->tqd)
3761 unqueue_data (q->tqd);
3763 if (NULL != q->cont)
3764 q->cont (q->cont_cls, NULL, q, 0, 0);
3775 * Sends an already built message on a tunnel, encrypting it and
3776 * choosing the best connection if not provided.
3778 * @param message Message to send. Function modifies it.
3779 * @param t Tunnel on which this message is transmitted.
3780 * @param c Connection to use (autoselect if NULL).
3781 * @param force Force the tunnel to take the message (buffer overfill).
3782 * @param cont Continuation to call once message is really sent.
3783 * @param cont_cls Closure for @c cont.
3785 * @return Handle to cancel message. NULL if @c cont is NULL.
3787 struct CadetTunnelQueue *
3788 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3789 struct CadetTunnel *t, struct CadetConnection *c,
3790 int force, GCT_sent cont, void *cont_cls)
3792 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3797 * Send an Axolotl KX message.
3799 * @param t Tunnel on which to send it.
3802 GCT_send_ax_kx (struct CadetTunnel *t)
3804 struct GNUNET_CADET_AX_KX msg;
3806 LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
3808 msg.header.size = htons (sizeof (msg));
3809 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
3810 msg.permanent_key = ax_identity.permanent_key;
3811 msg.purpose = ax_identity.purpose;
3812 msg.signature = ax_identity.signature;
3813 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
3814 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
3816 t->ephm_h = send_kx (t, &msg.header);
3817 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
3822 * Sends an already built and encrypted message on a tunnel, choosing the best
3823 * connection. Useful for re-queueing messages queued on a destroyed connection.
3825 * @param message Message to send. Function modifies it.
3826 * @param t Tunnel on which this message is transmitted.
3829 GCT_resend_message (const struct GNUNET_MessageHeader *message,
3830 struct CadetTunnel *t)
3832 struct CadetConnection *c;
3835 c = tunnel_get_connection (t);
3838 /* TODO queue in tunnel, marked as encrypted */
3839 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
3842 fwd = GCC_is_origin (c, GNUNET_YES);
3843 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
3844 GNUNET_YES, NULL, NULL));
3849 * Is the tunnel directed towards the local peer?
3853 * @return #GNUNET_YES if it is loopback.
3856 GCT_is_loopback (const struct CadetTunnel *t)
3858 return (myid == GCP_get_short_id (t->peer));
3863 * Is the tunnel this path already?
3868 * @return #GNUNET_YES a connection uses this path.
3871 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3873 struct CadetTConnection *iter;
3875 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3876 if (path_equivalent (GCC_get_path (iter->c), p))
3884 * Get a cost of a path for a tunnel considering existing connections.
3887 * @param path Candidate path.
3889 * @return Cost of the path (path length + number of overlapping nodes)
3892 GCT_get_path_cost (const struct CadetTunnel *t,
3893 const struct CadetPeerPath *path)
3895 struct CadetTConnection *iter;
3896 const struct CadetPeerPath *aux;
3897 unsigned int overlap;
3905 GNUNET_assert (NULL != t);
3907 for (i = 0; i < path->length; i++)
3909 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3911 aux = GCC_get_path (iter->c);
3915 for (j = 0; j < aux->length; j++)
3917 if (path->peers[i] == aux->peers[j])
3925 return path->length + overlap;
3930 * Get the static string for the peer this tunnel is directed.
3934 * @return Static string the destination peer's ID.
3937 GCT_2s (const struct CadetTunnel *t)
3942 return GCP_2s (t->peer);
3946 /******************************************************************************/
3947 /***************************** INFO/DEBUG *******************************/
3948 /******************************************************************************/
3951 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
3953 struct GNUNET_CRYPTO_EcdhePublicKey pub;
3954 struct CadetTunnelSkippedKey *iter;
3957 LOG2 (level, "TTT RK\t %s\n",
3958 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->RK));
3960 LOG2 (level, "TTT HKs\t %s\n",
3961 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
3962 LOG2 (level, "TTT HKr\t %s\n",
3963 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
3964 LOG2 (level, "TTT NHKs\t %s\n",
3965 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKs));
3966 LOG2 (level, "TTT NHKr\t %s\n",
3967 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKr));
3969 LOG2 (level, "TTT CKs\t %s\n",
3970 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
3971 LOG2 (level, "TTT CKr\t %s\n",
3972 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
3974 GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &pub);
3975 LOG2 (level, "TTT DHIs\t %s\n",
3976 GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
3977 LOG2 (level, "TTT DHIr\t %s\n",
3978 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHIr));
3979 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
3980 LOG2 (level, "TTT DHRs\t %s\n",
3981 GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
3982 LOG2 (level, "TTT DHRr\t %s\n",
3983 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHRr));
3985 LOG2 (level, "TTT Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
3986 LOG2 (level, "TTT PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
3987 LOG2 (level, "TTT Ratchet\t%u\n", ax->ratchet_flag);
3989 for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
3991 LOG2 (level, "TTT HK\t %s\n",
3992 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->HK));
3993 LOG2 (level, "TTT MK\t %s\n",
3994 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->MK));
3999 * Log all possible info about the tunnel state.
4001 * @param t Tunnel to debug.
4002 * @param level Debug level to use.
4005 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4007 struct CadetTChannel *iterch;
4008 struct CadetTConnection *iterc;
4011 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4013 __FILE__, __FUNCTION__, __LINE__);
4017 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4018 LOG2 (level, "TTT cstate %s, estate %s\n",
4019 cstate2s (t->cstate), estate2s (t->estate));
4020 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
4021 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4022 #if DUMP_KEYS_TO_STDERR
4023 if (CADET_Axolotl == t->enc_type)
4025 ax_debug (t->ax, level);
4029 LOG2 (level, "TTT my EPHM\t %s\n",
4030 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
4031 LOG2 (level, "TTT peers EPHM:\t %s\n",
4032 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
4033 LOG2 (level, "TTT ENC key:\t %s\n",
4034 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
4035 LOG2 (level, "TTT DEC key:\t %s\n",
4036 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
4039 LOG2 (level, "TTT OLD ENC key:\t %s\n",
4040 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
4041 LOG2 (level, "TTT OLD DEC key:\t %s\n",
4042 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
4046 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4047 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
4049 LOG2 (level, "TTT channels:\n");
4050 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4052 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
4055 LOG2 (level, "TTT connections:\n");
4056 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4058 GCC_debug (iterc->c, level);
4061 LOG2 (level, "TTT DEBUG TUNNEL END\n");
4066 * Iterate all tunnels.
4068 * @param iter Iterator.
4069 * @param cls Closure for @c iter.
4072 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4074 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4079 * Count all tunnels.
4081 * @return Number of tunnels to remote peers kept by this peer.
4084 GCT_count_all (void)
4086 return GNUNET_CONTAINER_multipeermap_size (tunnels);
4091 * Iterate all connections of a tunnel.
4093 * @param t Tunnel whose connections to iterate.
4094 * @param iter Iterator.
4095 * @param cls Closure for @c iter.
4098 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4100 struct CadetTConnection *ct;
4102 for (ct = t->connection_head; NULL != ct; ct = ct->next)
4108 * Iterate all channels of a tunnel.
4110 * @param t Tunnel whose channels to iterate.
4111 * @param iter Iterator.
4112 * @param cls Closure for @c iter.
4115 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4117 struct CadetTChannel *cht;
4119 for (cht = t->channel_head; NULL != cht; cht = cht->next)
4120 iter (cls, cht->ch);