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_Encrypted) + 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 size_t size = ntohs (msg->size);
2688 size_t payload_size;
2691 uint16_t type = ntohs (msg->type);
2692 struct GNUNET_MessageHeader *msgh;
2695 if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
2697 const struct GNUNET_CADET_Encrypted *emsg;
2699 emsg = (struct GNUNET_CADET_Encrypted *) msg;
2700 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2701 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
2702 emsg->iv, &emsg->hmac);
2704 else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
2706 const struct GNUNET_CADET_AX *emsg;
2708 emsg = (struct GNUNET_CADET_AX *) msg;
2709 payload_size = size - sizeof (struct GNUNET_CADET_AX);
2710 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, &emsg[1],
2711 payload_size, &emsg->hmac);
2714 if (-1 == decrypted_size)
2716 GNUNET_break_op (0);
2721 while (off < decrypted_size)
2725 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2726 msize = ntohs (msgh->size);
2727 if (msize < sizeof (struct GNUNET_MessageHeader))
2729 GNUNET_break_op (0);
2732 handle_decrypted (t, msgh, GNUNET_SYSERR);
2739 * Demultiplex an encapsulated KX message by message type.
2741 * @param t Tunnel on which the message came.
2742 * @param message Payload of KX message.
2745 GCT_handle_kx (struct CadetTunnel *t,
2746 const struct GNUNET_MessageHeader *message)
2750 type = ntohs (message->type);
2751 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
2754 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2755 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
2758 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2759 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
2762 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2763 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
2767 GNUNET_break_op (0);
2768 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
2773 * Initialize the tunnel subsystem.
2775 * @param c Configuration handle.
2776 * @param key ECC private key, to derive all other keys and do crypto.
2779 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2780 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2782 int expected_overhead;
2784 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2786 expected_overhead = 0;
2787 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
2788 expected_overhead += sizeof (struct GNUNET_CADET_Data);
2789 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
2790 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2793 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2796 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2797 "CADET", "DEFAULT_TTL", "USING DEFAULT");
2801 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2804 rekey_period = GNUNET_TIME_UNIT_DAYS;
2809 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
2810 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2811 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2812 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2813 otr_kx_msg.origin_identity = my_full_id;
2814 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
2816 ax_key = GNUNET_CRYPTO_ecdhe_key_create ();
2817 GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &ax_identity.permanent_key);
2818 ax_identity.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_AXKX);
2819 ax_identity.purpose.size = htonl (ax_purpose_size ());
2820 GNUNET_assert (GNUNET_OK ==
2821 GNUNET_CRYPTO_eddsa_sign (id_key,
2822 &ax_identity.purpose,
2823 &ax_identity.signature));
2825 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2830 * Shut down the tunnel subsystem.
2835 if (NULL != rekey_task)
2837 GNUNET_SCHEDULER_cancel (rekey_task);
2840 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2841 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2842 GNUNET_free (ax_key);
2849 * @param destination Peer this tunnel is towards.
2851 struct CadetTunnel *
2852 GCT_new (struct CadetPeer *destination)
2854 struct CadetTunnel *t;
2856 t = GNUNET_new (struct CadetTunnel);
2858 t->peer = destination;
2861 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2862 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2868 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
2870 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2876 * Change the tunnel's connection state.
2878 * @param t Tunnel whose connection state to change.
2879 * @param cstate New connection state.
2882 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2886 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2887 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2888 if (myid != GCP_get_short_id (t->peer) &&
2889 CADET_TUNNEL_READY != t->cstate &&
2890 CADET_TUNNEL_READY == cstate)
2893 if (CADET_TUNNEL_KEY_OK == t->estate)
2895 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2896 send_queued_data (t);
2898 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2900 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
2905 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
2910 if (CADET_TUNNEL_READY == cstate
2911 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2913 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2914 GCP_stop_search (t->peer);
2920 * Change the tunnel encryption state.
2922 * @param t Tunnel whose encryption state to change, or NULL.
2923 * @param state New encryption state.
2926 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2928 enum CadetTunnelEState old;
2935 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2936 GCP_2s (t->peer), estate2s (old));
2937 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2938 GCP_2s (t->peer), estate2s (t->estate));
2940 /* Send queued data if enc state changes to OK */
2941 if (myid != GCP_get_short_id (t->peer) &&
2942 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
2944 send_queued_data (t);
2950 * @brief Check if tunnel has too many connections, and remove one if necessary.
2952 * Currently this means the newest connection, unless it is a direct one.
2953 * Implemented as a task to avoid freeing a connection that is in the middle
2954 * of being created/processed.
2956 * @param cls Closure (Tunnel to check).
2957 * @param tc Task context.
2960 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2962 struct CadetTunnel *t = cls;
2964 t->trim_connections_task = NULL;
2966 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2969 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2971 struct CadetTConnection *iter;
2972 struct CadetTConnection *c;
2974 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2976 if ((iter->created.abs_value_us > c->created.abs_value_us)
2977 && GNUNET_NO == GCC_is_direct (iter->c))
2984 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2986 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2999 * Add a connection to a tunnel.
3002 * @param c Connection.
3005 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3007 struct CadetTConnection *aux;
3009 GNUNET_assert (NULL != c);
3011 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3012 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3013 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3017 aux = GNUNET_new (struct CadetTConnection);
3019 aux->created = GNUNET_TIME_absolute_get ();
3021 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3023 if (CADET_TUNNEL_SEARCHING == t->cstate)
3024 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3026 if (NULL != t->trim_connections_task)
3027 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3032 * Remove a connection from a tunnel.
3035 * @param c Connection.
3038 GCT_remove_connection (struct CadetTunnel *t,
3039 struct CadetConnection *c)
3041 struct CadetTConnection *aux;
3042 struct CadetTConnection *next;
3045 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3046 GCC_2s (c), GCT_2s (t));
3047 for (aux = t->connection_head; aux != NULL; aux = next)
3052 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3057 conns = GCT_count_connections (t);
3059 && NULL == t->destroy_task
3060 && CADET_TUNNEL_SHUTDOWN != t->cstate
3061 && GNUNET_NO == shutting_down)
3063 if (0 == GCT_count_any_connections (t))
3064 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3066 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3069 /* Start new connections if needed */
3070 if (CONNECTIONS_PER_TUNNEL > conns
3071 && NULL == t->destroy_task
3072 && CADET_TUNNEL_SHUTDOWN != t->cstate
3073 && GNUNET_NO == shutting_down)
3075 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
3076 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3080 /* If not marked as ready, no change is needed */
3081 if (CADET_TUNNEL_READY != t->cstate)
3084 /* Check if any connection is ready to maintain cstate */
3085 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3086 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3092 * Add a channel to a tunnel.
3095 * @param ch Channel.
3098 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3100 struct CadetTChannel *aux;
3102 GNUNET_assert (NULL != ch);
3104 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3106 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3108 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
3113 aux = GNUNET_new (struct CadetTChannel);
3115 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3116 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3118 if (NULL != t->destroy_task)
3120 GNUNET_SCHEDULER_cancel (t->destroy_task);
3121 t->destroy_task = NULL;
3122 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3128 * Remove a channel from a tunnel.
3131 * @param ch Channel.
3134 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3136 struct CadetTChannel *aux;
3138 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3139 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3143 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3144 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3153 * Search for a channel by global ID.
3155 * @param t Tunnel containing the channel.
3156 * @param chid Public channel number.
3158 * @return channel handler, NULL if doesn't exist
3160 struct CadetChannel *
3161 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3163 struct CadetTChannel *iter;
3168 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3170 if (GCCH_get_id (iter->ch) == chid)
3174 return NULL == iter ? NULL : iter->ch;
3179 * @brief Destroy a tunnel and free all resources.
3181 * Should only be called a while after the tunnel has been marked as destroyed,
3182 * in case there is a new channel added to the same peer shortly after marking
3183 * the tunnel. This way we avoid a new public key handshake.
3185 * @param cls Closure (tunnel to destroy).
3186 * @param tc Task context.
3189 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3191 struct CadetTunnel *t = cls;
3192 struct CadetTConnection *iter;
3194 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3195 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3197 LOG (GNUNET_ERROR_TYPE_WARNING,
3198 "Not destroying tunnel, due to shutdown. "
3199 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3202 t->destroy_task = NULL;
3203 t->cstate = CADET_TUNNEL_SHUTDOWN;
3205 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3207 GCC_send_destroy (iter->c);
3214 * Tunnel is empty: destroy it.
3216 * Notifies all connections about the destruction.
3218 * @param t Tunnel to destroy.
3221 GCT_destroy_empty (struct CadetTunnel *t)
3223 if (GNUNET_YES == shutting_down)
3224 return; /* Will be destroyed immediately anyway */
3226 if (NULL != t->destroy_task)
3228 LOG (GNUNET_ERROR_TYPE_WARNING,
3229 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3231 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3233 /* should never happen, tunnel can only become empty once, and the
3234 * task identifier should be NO_TASK (cleaned when the tunnel was created
3235 * or became un-empty)
3240 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3243 // FIXME make delay a config option
3244 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3245 &delayed_destroy, t);
3246 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3247 t, t->destroy_task);
3252 * Destroy tunnel if empty (no more channels).
3254 * @param t Tunnel to destroy if empty.
3257 GCT_destroy_if_empty (struct CadetTunnel *t)
3259 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3260 if (0 < GCT_count_channels (t))
3263 GCT_destroy_empty (t);
3268 * Destroy the tunnel.
3270 * This function does not generate any warning traffic to clients or peers.
3273 * Cancel messages belonging to this tunnel queued to neighbors.
3274 * Free any allocated resources linked to the tunnel.
3276 * @param t The tunnel to destroy.
3279 GCT_destroy (struct CadetTunnel *t)
3281 struct CadetTConnection *iter_c;
3282 struct CadetTConnection *next_c;
3283 struct CadetTChannel *iter_ch;
3284 struct CadetTChannel *next_ch;
3289 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3291 GNUNET_break (GNUNET_YES ==
3292 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3293 GCP_get_id (t->peer), t));
3295 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3297 next_c = iter_c->next;
3298 GCC_destroy (iter_c->c);
3300 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3302 next_ch = iter_ch->next;
3303 GCCH_destroy (iter_ch->ch);
3304 /* Should only happen on shutdown, but it's ok. */
3307 if (NULL != t->destroy_task)
3309 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3310 GNUNET_SCHEDULER_cancel (t->destroy_task);
3311 t->destroy_task = NULL;
3314 if (NULL != t->trim_connections_task)
3316 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3317 t->trim_connections_task);
3318 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3319 t->trim_connections_task = NULL;
3322 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3323 GCP_set_tunnel (t->peer, NULL);
3325 if (NULL != t->rekey_task)
3327 GNUNET_SCHEDULER_cancel (t->rekey_task);
3328 t->rekey_task = NULL;
3330 if (NULL != t->kx_ctx)
3332 if (NULL != t->kx_ctx->finish_task)
3333 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3334 GNUNET_free (t->kx_ctx);
3345 * @brief Use the given path for the tunnel.
3346 * Update the next and prev hops (and RCs).
3347 * (Re)start the path refresh in case the tunnel is locally owned.
3349 * @param t Tunnel to update.
3350 * @param p Path to use.
3352 * @return Connection created.
3354 struct CadetConnection *
3355 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3357 struct CadetConnection *c;
3358 struct GNUNET_CADET_Hash cid;
3359 unsigned int own_pos;
3361 if (NULL == t || NULL == p)
3367 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3373 for (own_pos = 0; own_pos < p->length; own_pos++)
3375 if (p->peers[own_pos] == myid)
3378 if (own_pos >= p->length)
3380 GNUNET_break_op (0);
3384 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3385 c = GCC_new (&cid, t, p, own_pos);
3388 /* Path was flawed */
3391 GCT_add_connection (t, c);
3397 * Count all created connections of a tunnel. Not necessarily ready connections!
3399 * @param t Tunnel on which to count.
3401 * @return Number of connections created, either being established or ready.
3404 GCT_count_any_connections (struct CadetTunnel *t)
3406 struct CadetTConnection *iter;
3412 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3420 * Count established (ready) connections of a tunnel.
3422 * @param t Tunnel on which to count.
3424 * @return Number of connections.
3427 GCT_count_connections (struct CadetTunnel *t)
3429 struct CadetTConnection *iter;
3435 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3436 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3444 * Count channels of a tunnel.
3446 * @param t Tunnel on which to count.
3448 * @return Number of channels.
3451 GCT_count_channels (struct CadetTunnel *t)
3453 struct CadetTChannel *iter;
3456 for (count = 0, iter = t->channel_head;
3458 iter = iter->next, count++) /* skip */;
3465 * Get the connectivity state of a tunnel.
3469 * @return Tunnel's connectivity state.
3471 enum CadetTunnelCState
3472 GCT_get_cstate (struct CadetTunnel *t)
3477 return (enum CadetTunnelCState) -1;
3484 * Get the encryption state of a tunnel.
3488 * @return Tunnel's encryption state.
3490 enum CadetTunnelEState
3491 GCT_get_estate (struct CadetTunnel *t)
3496 return (enum CadetTunnelEState) -1;
3502 * Get the maximum buffer space for a tunnel towards a local client.
3506 * @return Biggest buffer space offered by any channel in the tunnel.
3509 GCT_get_channels_buffer (struct CadetTunnel *t)
3511 struct CadetTChannel *iter;
3512 unsigned int buffer;
3513 unsigned int ch_buf;
3515 if (NULL == t->channel_head)
3517 /* Probably getting buffer for a channel create/handshake. */
3518 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3523 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3525 ch_buf = get_channel_buffer (iter);
3526 if (ch_buf > buffer)
3534 * Get the total buffer space for a tunnel for P2P traffic.
3538 * @return Buffer space offered by all connections in the tunnel.
3541 GCT_get_connections_buffer (struct CadetTunnel *t)
3543 struct CadetTConnection *iter;
3544 unsigned int buffer;
3546 if (GNUNET_NO == is_ready (t))
3548 if (count_queued_data (t) > 3)
3555 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3557 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3561 buffer += get_connection_buffer (iter);
3569 * Get the tunnel's destination.
3573 * @return ID of the destination peer.
3575 const struct GNUNET_PeerIdentity *
3576 GCT_get_destination (struct CadetTunnel *t)
3578 return GCP_get_id (t->peer);
3583 * Get the tunnel's next free global channel ID.
3587 * @return GID of a channel free to use.
3590 GCT_get_next_chid (struct CadetTunnel *t)
3592 CADET_ChannelNumber chid;
3593 CADET_ChannelNumber mask;
3596 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3597 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3598 * If peer's ID is bigger, start at 0x4... bit 30 = 1
3600 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3605 t->next_chid |= mask;
3607 while (NULL != GCT_get_channel (t, t->next_chid))
3609 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3610 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3611 t->next_chid |= mask;
3613 chid = t->next_chid;
3614 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3615 t->next_chid |= mask;
3622 * Send ACK on one or more channels due to buffer in connections.
3624 * @param t Channel which has some free buffer space.
3627 GCT_unchoke_channels (struct CadetTunnel *t)
3629 struct CadetTChannel *iter;
3630 unsigned int buffer;
3631 unsigned int channels = GCT_count_channels (t);
3632 unsigned int choked_n;
3633 struct CadetChannel *choked[channels];
3635 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3636 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3637 if (NULL != t->channel_head)
3638 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3640 /* Get buffer space */
3641 buffer = GCT_get_connections_buffer (t);
3647 /* Count and remember choked channels */
3649 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3651 if (GNUNET_NO == get_channel_allowed (iter))
3653 choked[choked_n++] = iter->ch;
3657 /* Unchoke random channels */
3658 while (0 < buffer && 0 < choked_n)
3660 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3662 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3665 choked[r] = choked[choked_n];
3671 * Send ACK on one or more connections due to buffer space to the client.
3673 * Iterates all connections of the tunnel and sends ACKs appropriately.
3678 GCT_send_connection_acks (struct CadetTunnel *t)
3680 struct CadetTConnection *iter;
3683 uint32_t allow_per_connection;
3685 unsigned int buffer;
3687 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3696 if (CADET_TUNNEL_READY != t->cstate)
3699 buffer = GCT_get_channels_buffer (t);
3700 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
3702 /* Count connections, how many messages are already allowed */
3703 cs = GCT_count_connections (t);
3704 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3706 allowed += get_connection_allowed (iter);
3708 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
3710 /* Make sure there is no overflow */
3711 if (allowed > buffer)
3714 /* Authorize connections to send more data */
3715 to_allow = buffer - allowed;
3717 for (iter = t->connection_head;
3718 NULL != iter && to_allow > 0;
3721 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3722 || get_connection_allowed (iter) > 64 / 3)
3726 allow_per_connection = to_allow/cs;
3727 to_allow -= allow_per_connection;
3729 GCC_allow (iter->c, allow_per_connection,
3730 GCC_is_origin (iter->c, GNUNET_NO));
3735 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
3736 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
3742 * Cancel a previously sent message while it's in the queue.
3744 * ONLY can be called before the continuation given to the send function
3745 * is called. Once the continuation is called, the message is no longer in the
3748 * @param q Handle to the queue.
3751 GCT_cancel (struct CadetTunnelQueue *q)
3756 /* tun_message_sent() will be called and free q */
3758 else if (NULL != q->tqd)
3760 unqueue_data (q->tqd);
3762 if (NULL != q->cont)
3763 q->cont (q->cont_cls, NULL, q, 0, 0);
3774 * Sends an already built message on a tunnel, encrypting it and
3775 * choosing the best connection if not provided.
3777 * @param message Message to send. Function modifies it.
3778 * @param t Tunnel on which this message is transmitted.
3779 * @param c Connection to use (autoselect if NULL).
3780 * @param force Force the tunnel to take the message (buffer overfill).
3781 * @param cont Continuation to call once message is really sent.
3782 * @param cont_cls Closure for @c cont.
3784 * @return Handle to cancel message. NULL if @c cont is NULL.
3786 struct CadetTunnelQueue *
3787 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3788 struct CadetTunnel *t, struct CadetConnection *c,
3789 int force, GCT_sent cont, void *cont_cls)
3791 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3796 * Send an Axolotl KX message.
3798 * @param t Tunnel on which to send it.
3801 GCT_send_ax_kx (struct CadetTunnel *t)
3803 struct GNUNET_CADET_AX_KX msg;
3805 LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
3807 msg.header.size = htons (sizeof (msg));
3808 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
3809 msg.permanent_key = ax_identity.permanent_key;
3810 msg.purpose = ax_identity.purpose;
3811 msg.signature = ax_identity.signature;
3812 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
3813 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
3815 t->ephm_h = send_kx (t, &msg.header);
3816 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
3821 * Sends an already built and encrypted message on a tunnel, choosing the best
3822 * connection. Useful for re-queueing messages queued on a destroyed connection.
3824 * @param message Message to send. Function modifies it.
3825 * @param t Tunnel on which this message is transmitted.
3828 GCT_resend_message (const struct GNUNET_MessageHeader *message,
3829 struct CadetTunnel *t)
3831 struct CadetConnection *c;
3834 c = tunnel_get_connection (t);
3837 /* TODO queue in tunnel, marked as encrypted */
3838 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
3841 fwd = GCC_is_origin (c, GNUNET_YES);
3842 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
3843 GNUNET_YES, NULL, NULL));
3848 * Is the tunnel directed towards the local peer?
3852 * @return #GNUNET_YES if it is loopback.
3855 GCT_is_loopback (const struct CadetTunnel *t)
3857 return (myid == GCP_get_short_id (t->peer));
3862 * Is the tunnel this path already?
3867 * @return #GNUNET_YES a connection uses this path.
3870 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3872 struct CadetTConnection *iter;
3874 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3875 if (path_equivalent (GCC_get_path (iter->c), p))
3883 * Get a cost of a path for a tunnel considering existing connections.
3886 * @param path Candidate path.
3888 * @return Cost of the path (path length + number of overlapping nodes)
3891 GCT_get_path_cost (const struct CadetTunnel *t,
3892 const struct CadetPeerPath *path)
3894 struct CadetTConnection *iter;
3895 const struct CadetPeerPath *aux;
3896 unsigned int overlap;
3904 GNUNET_assert (NULL != t);
3906 for (i = 0; i < path->length; i++)
3908 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3910 aux = GCC_get_path (iter->c);
3914 for (j = 0; j < aux->length; j++)
3916 if (path->peers[i] == aux->peers[j])
3924 return path->length + overlap;
3929 * Get the static string for the peer this tunnel is directed.
3933 * @return Static string the destination peer's ID.
3936 GCT_2s (const struct CadetTunnel *t)
3941 return GCP_2s (t->peer);
3945 /******************************************************************************/
3946 /***************************** INFO/DEBUG *******************************/
3947 /******************************************************************************/
3950 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
3952 struct GNUNET_CRYPTO_EcdhePublicKey pub;
3953 struct CadetTunnelSkippedKey *iter;
3956 LOG2 (level, "TTT RK\t %s\n",
3957 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->RK));
3959 LOG2 (level, "TTT HKs\t %s\n",
3960 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
3961 LOG2 (level, "TTT HKr\t %s\n",
3962 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
3963 LOG2 (level, "TTT NHKs\t %s\n",
3964 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKs));
3965 LOG2 (level, "TTT NHKr\t %s\n",
3966 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKr));
3968 LOG2 (level, "TTT CKs\t %s\n",
3969 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
3970 LOG2 (level, "TTT CKr\t %s\n",
3971 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
3973 GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &pub);
3974 LOG2 (level, "TTT DHIs\t %s\n",
3975 GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
3976 LOG2 (level, "TTT DHIr\t %s\n",
3977 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHIr));
3978 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
3979 LOG2 (level, "TTT DHRs\t %s\n",
3980 GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
3981 LOG2 (level, "TTT DHRr\t %s\n",
3982 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHRr));
3984 LOG2 (level, "TTT Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
3985 LOG2 (level, "TTT PNs\t%u\tSkipped\t%u\n", ax->PNs, ax->skipped);
3986 LOG2 (level, "TTT Ratchet\t%u\n", ax->ratchet_flag);
3988 for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
3990 LOG2 (level, "TTT HK\t %s\n",
3991 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->HK));
3992 LOG2 (level, "TTT MK\t %s\n",
3993 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->MK));
3998 * Log all possible info about the tunnel state.
4000 * @param t Tunnel to debug.
4001 * @param level Debug level to use.
4004 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4006 struct CadetTChannel *iterch;
4007 struct CadetTConnection *iterc;
4010 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4012 __FILE__, __FUNCTION__, __LINE__);
4016 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4017 LOG2 (level, "TTT cstate %s, estate %s\n",
4018 cstate2s (t->cstate), estate2s (t->estate));
4019 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
4020 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4021 #if DUMP_KEYS_TO_STDERR
4022 if (CADET_Axolotl == t->enc_type)
4024 ax_debug (t->ax, level);
4028 LOG2 (level, "TTT my EPHM\t %s\n",
4029 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
4030 LOG2 (level, "TTT peers EPHM:\t %s\n",
4031 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
4032 LOG2 (level, "TTT ENC key:\t %s\n",
4033 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
4034 LOG2 (level, "TTT DEC key:\t %s\n",
4035 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
4038 LOG2 (level, "TTT OLD ENC key:\t %s\n",
4039 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
4040 LOG2 (level, "TTT OLD DEC key:\t %s\n",
4041 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
4045 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4046 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
4048 LOG2 (level, "TTT channels:\n");
4049 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4051 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
4054 LOG2 (level, "TTT connections:\n");
4055 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4057 GCC_debug (iterc->c, level);
4060 LOG2 (level, "TTT DEBUG TUNNEL END\n");
4065 * Iterate all tunnels.
4067 * @param iter Iterator.
4068 * @param cls Closure for @c iter.
4071 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4073 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4078 * Count all tunnels.
4080 * @return Number of tunnels to remote peers kept by this peer.
4083 GCT_count_all (void)
4085 return GNUNET_CONTAINER_multipeermap_size (tunnels);
4090 * Iterate all connections of a tunnel.
4092 * @param t Tunnel whose connections to iterate.
4093 * @param iter Iterator.
4094 * @param cls Closure for @c iter.
4097 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4099 struct CadetTConnection *ct;
4101 for (ct = t->connection_head; NULL != ct; ct = ct->next)
4107 * Iterate all channels of a tunnel.
4109 * @param t Tunnel whose channels to iterate.
4110 * @param iter Iterator.
4111 * @param cls Closure for @c iter.
4114 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4116 struct CadetTChannel *cht;
4118 for (cht = t->channel_head; NULL != cht; cht = cht->next)
4119 iter (cls, cht->ch);