gnunet-service-cadet_tunnels.c 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711
  1. /*
  2. This file is part of GNUnet.
  3. Copyright (C) 2013, 2017, 2018 GNUnet e.V.
  4. GNUnet is free software: you can redistribute it and/or modify it
  5. under the terms of the GNU Affero General Public License as published
  6. by the Free Software Foundation, either version 3 of the License,
  7. or (at your option) any later version.
  8. GNUnet is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Affero General Public License for more details.
  12. You should have received a copy of the GNU Affero General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. SPDX-License-Identifier: AGPL3.0-or-later
  15. */
  16. /**
  17. * @file cadet/gnunet-service-cadet_tunnels.c
  18. * @brief Information we track per tunnel.
  19. * @author Bartlomiej Polot
  20. * @author Christian Grothoff
  21. *
  22. * FIXME:
  23. * - proper connection evaluation during connection management:
  24. * + consider quality (or quality spread?) of current connection set
  25. * when deciding how often to do maintenance
  26. * + interact with PEER to drive DHT GET/PUT operations based
  27. * on how much we like our connections
  28. */
  29. #include "platform.h"
  30. #include "gnunet_util_lib.h"
  31. #include "gnunet_statistics_service.h"
  32. #include "gnunet_signatures.h"
  33. #include "cadet_protocol.h"
  34. #include "gnunet-service-cadet_channel.h"
  35. #include "gnunet-service-cadet_connection.h"
  36. #include "gnunet-service-cadet_tunnels.h"
  37. #include "gnunet-service-cadet_peer.h"
  38. #include "gnunet-service-cadet_paths.h"
  39. #define LOG(level, ...) GNUNET_log_from (level, "cadet-tun", __VA_ARGS__)
  40. /**
  41. * How often do we try to decrypt payload with unverified key
  42. * material? Used to limit CPU increase upon receiving bogus
  43. * KX.
  44. */
  45. #define MAX_UNVERIFIED_ATTEMPTS 16
  46. /**
  47. * How long do we wait until tearing down an idle tunnel?
  48. */
  49. #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply ( \
  50. GNUNET_TIME_UNIT_SECONDS, 90)
  51. /**
  52. * How long do we wait initially before retransmitting the KX?
  53. * TODO: replace by 2 RTT if/once we have connection-level RTT data!
  54. */
  55. #define INITIAL_KX_RETRY_DELAY GNUNET_TIME_relative_multiply ( \
  56. GNUNET_TIME_UNIT_MILLISECONDS, 250)
  57. /**
  58. * Maximum number of skipped keys we keep in memory per tunnel.
  59. */
  60. #define MAX_SKIPPED_KEYS 64
  61. /**
  62. * Maximum number of keys (and thus ratchet steps) we are willing to
  63. * skip before we decide this is either a bogus packet or a DoS-attempt.
  64. */
  65. #define MAX_KEY_GAP 256
  66. /**
  67. * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
  68. */
  69. struct CadetTunnelSkippedKey
  70. {
  71. /**
  72. * DLL next.
  73. */
  74. struct CadetTunnelSkippedKey *next;
  75. /**
  76. * DLL prev.
  77. */
  78. struct CadetTunnelSkippedKey *prev;
  79. /**
  80. * When was this key stored (for timeout).
  81. */
  82. struct GNUNET_TIME_Absolute timestamp;
  83. /**
  84. * Header key.
  85. */
  86. struct GNUNET_CRYPTO_SymmetricSessionKey HK;
  87. /**
  88. * Message key.
  89. */
  90. struct GNUNET_CRYPTO_SymmetricSessionKey MK;
  91. /**
  92. * Key number for a given HK.
  93. */
  94. unsigned int Kn;
  95. };
  96. /**
  97. * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
  98. */
  99. struct CadetTunnelAxolotl
  100. {
  101. /**
  102. * A (double linked) list of stored message keys and associated header keys
  103. * for "skipped" messages, i.e. messages that have not been
  104. * received despite the reception of more recent messages, (head).
  105. */
  106. struct CadetTunnelSkippedKey *skipped_head;
  107. /**
  108. * Skipped messages' keys DLL, tail.
  109. */
  110. struct CadetTunnelSkippedKey *skipped_tail;
  111. /**
  112. * 32-byte root key which gets updated by DH ratchet.
  113. */
  114. struct GNUNET_CRYPTO_SymmetricSessionKey RK;
  115. /**
  116. * 32-byte header key (currently used for sending).
  117. */
  118. struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
  119. /**
  120. * 32-byte header key (currently used for receiving)
  121. */
  122. struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
  123. /**
  124. * 32-byte next header key (for sending), used once the
  125. * ratchet advances. We are sure that the sender has this
  126. * key as well only after @e ratchet_allowed is #GNUNET_YES.
  127. */
  128. struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
  129. /**
  130. * 32-byte next header key (for receiving). To be tried
  131. * when decrypting with @e HKr fails and thus the sender
  132. * may have advanced the ratchet.
  133. */
  134. struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
  135. /**
  136. * 32-byte chain keys (used for forward-secrecy) for
  137. * sending messages. Updated for every message.
  138. */
  139. struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
  140. /**
  141. * 32-byte chain keys (used for forward-secrecy) for
  142. * receiving messages. Updated for every message. If
  143. * messages are skipped, the respective derived MKs
  144. * (and the current @HKr) are kept in the @e skipped_head DLL.
  145. */
  146. struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
  147. /**
  148. * ECDH for key exchange (A0 / B0).
  149. */
  150. struct GNUNET_CRYPTO_EcdhePrivateKey kx_0;
  151. /**
  152. * ECDH Ratchet key (our private key in the current DH).
  153. */
  154. struct GNUNET_CRYPTO_EcdhePrivateKey DHRs;
  155. /**
  156. * ECDH Ratchet key (other peer's public key in the current DH).
  157. */
  158. struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
  159. /**
  160. * Last ephemeral public key received from the other peer,
  161. * for duplicate detection.
  162. */
  163. struct GNUNET_CRYPTO_EcdhePublicKey last_ephemeral;
  164. /**
  165. * Time when the current ratchet expires and a new one is triggered
  166. * (if @e ratchet_allowed is #GNUNET_YES).
  167. */
  168. struct GNUNET_TIME_Absolute ratchet_expiration;
  169. /**
  170. * Number of elements in @a skipped_head <-> @a skipped_tail.
  171. */
  172. unsigned int skipped;
  173. /**
  174. * Message number (reset to 0 with each new ratchet, next message to send).
  175. */
  176. uint32_t Ns;
  177. /**
  178. * Message number (reset to 0 with each new ratchet, next message to recv).
  179. */
  180. uint32_t Nr;
  181. /**
  182. * Previous message numbers (# of msgs sent under prev ratchet)
  183. */
  184. uint32_t PNs;
  185. /**
  186. * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
  187. */
  188. int ratchet_flag;
  189. /**
  190. * True (#GNUNET_YES) if we have received a message from the
  191. * other peer that uses the keys from our last ratchet step.
  192. * This implies that we are again allowed to advance the ratchet,
  193. * otherwise we have to wait until the other peer sees our current
  194. * ephemeral key and advances first.
  195. *
  196. * #GNUNET_NO if we have advanced the ratched but lack any evidence
  197. * that the other peer has noticed this.
  198. */
  199. int ratchet_allowed;
  200. /**
  201. * Number of messages recieved since our last ratchet advance.
  202. *
  203. * If this counter = 0, we cannot send a new ratchet key in the next
  204. * message.
  205. *
  206. * If this counter > 0, we could (but don't have to) send a new key.
  207. *
  208. * Once the @e ratchet_counter is larger than
  209. * #ratchet_messages (or @e ratchet_expiration time has past), and
  210. * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
  211. */
  212. unsigned int ratchet_counter;
  213. };
  214. /**
  215. * Struct used to save messages in a non-ready tunnel to send once connected.
  216. */
  217. struct CadetTunnelQueueEntry
  218. {
  219. /**
  220. * We are entries in a DLL
  221. */
  222. struct CadetTunnelQueueEntry *next;
  223. /**
  224. * We are entries in a DLL
  225. */
  226. struct CadetTunnelQueueEntry *prev;
  227. /**
  228. * Tunnel these messages belong in.
  229. */
  230. struct CadetTunnel *t;
  231. /**
  232. * Continuation to call once sent (on the channel layer).
  233. */
  234. GCT_SendContinuation cont;
  235. /**
  236. * Closure for @c cont.
  237. */
  238. void *cont_cls;
  239. /**
  240. * Envelope of message to send follows.
  241. */
  242. struct GNUNET_MQ_Envelope *env;
  243. /**
  244. * Where to put the connection identifier into the payload
  245. * of the message in @e env once we have it?
  246. */
  247. struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
  248. };
  249. /**
  250. * Struct containing all information regarding a tunnel to a peer.
  251. */
  252. struct CadetTunnel
  253. {
  254. /**
  255. * Destination of the tunnel.
  256. */
  257. struct CadetPeer *destination;
  258. /**
  259. * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
  260. * ephemeral key changes.
  261. */
  262. struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
  263. /**
  264. * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
  265. */
  266. struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
  267. /**
  268. * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
  269. */
  270. struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
  271. /**
  272. * Axolotl info.
  273. */
  274. struct CadetTunnelAxolotl ax;
  275. /**
  276. * Unverified Axolotl info, used only if we got a fresh KX (not a
  277. * KX_AUTH) while our end of the tunnel was still up. In this case,
  278. * we keep the fresh KX around but do not put it into action until
  279. * we got encrypted payload that assures us of the authenticity of
  280. * the KX.
  281. */
  282. struct CadetTunnelAxolotl *unverified_ax;
  283. /**
  284. * Task scheduled if there are no more channels using the tunnel.
  285. */
  286. struct GNUNET_SCHEDULER_Task *destroy_task;
  287. /**
  288. * Task to trim connections if too many are present.
  289. */
  290. struct GNUNET_SCHEDULER_Task *maintain_connections_task;
  291. /**
  292. * Task to send messages from queue (if possible).
  293. */
  294. struct GNUNET_SCHEDULER_Task *send_task;
  295. /**
  296. * Task to trigger KX.
  297. */
  298. struct GNUNET_SCHEDULER_Task *kx_task;
  299. /**
  300. * Tokenizer for decrypted messages.
  301. */
  302. struct GNUNET_MessageStreamTokenizer *mst;
  303. /**
  304. * Dispatcher for decrypted messages only (do NOT use for sending!).
  305. */
  306. struct GNUNET_MQ_Handle *mq;
  307. /**
  308. * DLL of ready connections that are actively used to reach the destination peer.
  309. */
  310. struct CadetTConnection *connection_ready_head;
  311. /**
  312. * DLL of ready connections that are actively used to reach the destination peer.
  313. */
  314. struct CadetTConnection *connection_ready_tail;
  315. /**
  316. * DLL of connections that we maintain that might be used to reach the destination peer.
  317. */
  318. struct CadetTConnection *connection_busy_head;
  319. /**
  320. * DLL of connections that we maintain that might be used to reach the destination peer.
  321. */
  322. struct CadetTConnection *connection_busy_tail;
  323. /**
  324. * Channels inside this tunnel. Maps
  325. * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
  326. */
  327. struct GNUNET_CONTAINER_MultiHashMap32 *channels;
  328. /**
  329. * Channel ID for the next created channel in this tunnel.
  330. */
  331. struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
  332. /**
  333. * Queued messages, to transmit once tunnel gets connected.
  334. */
  335. struct CadetTunnelQueueEntry *tq_head;
  336. /**
  337. * Queued messages, to transmit once tunnel gets connected.
  338. */
  339. struct CadetTunnelQueueEntry *tq_tail;
  340. /**
  341. * Identification of the connection from which we are currently processing
  342. * a message. Only valid (non-NULL) during #handle_decrypted() and the
  343. * handle-*()-functions called from our @e mq during that function.
  344. */
  345. struct CadetTConnection *current_ct;
  346. /**
  347. * How long do we wait until we retry the KX?
  348. */
  349. struct GNUNET_TIME_Relative kx_retry_delay;
  350. /**
  351. * When do we try the next KX?
  352. */
  353. struct GNUNET_TIME_Absolute next_kx_attempt;
  354. /**
  355. * Number of connections in the @e connection_ready_head DLL.
  356. */
  357. unsigned int num_ready_connections;
  358. /**
  359. * Number of connections in the @e connection_busy_head DLL.
  360. */
  361. unsigned int num_busy_connections;
  362. /**
  363. * How often have we tried and failed to decrypt a message using
  364. * the unverified KX material from @e unverified_ax? Used to
  365. * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
  366. */
  367. unsigned int unverified_attempts;
  368. /**
  369. * Number of entries in the @e tq_head DLL.
  370. */
  371. unsigned int tq_len;
  372. /**
  373. * State of the tunnel encryption.
  374. */
  375. enum CadetTunnelEState estate;
  376. /**
  377. * Force triggering KX_AUTH independent of @e estate.
  378. */
  379. int kx_auth_requested;
  380. };
  381. /**
  382. * Am I Alice or Betty (some call her Bob), or talking to myself?
  383. *
  384. * @param other the other peer
  385. * @return #GNUNET_YES for Alice, #GNUNET_NO for Betty, #GNUNET_SYSERR if talking to myself
  386. */
  387. static int
  388. alice_or_betty (const struct GNUNET_PeerIdentity *other)
  389. {
  390. if (0 > GNUNET_memcmp (&my_full_id,
  391. other))
  392. return GNUNET_YES;
  393. else if (0 < GNUNET_memcmp (&my_full_id,
  394. other))
  395. return GNUNET_NO;
  396. else
  397. {
  398. GNUNET_break_op (0);
  399. return GNUNET_SYSERR;
  400. }
  401. }
  402. /**
  403. * Connection @a ct is now unready, clear it's ready flag
  404. * and move it from the ready DLL to the busy DLL.
  405. *
  406. * @param ct connection to move to unready status
  407. */
  408. static void
  409. mark_connection_unready (struct CadetTConnection *ct)
  410. {
  411. struct CadetTunnel *t = ct->t;
  412. GNUNET_assert (GNUNET_YES == ct->is_ready);
  413. GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
  414. t->connection_ready_tail,
  415. ct);
  416. GNUNET_assert (0 < t->num_ready_connections);
  417. t->num_ready_connections--;
  418. ct->is_ready = GNUNET_NO;
  419. GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
  420. t->connection_busy_tail,
  421. ct);
  422. t->num_busy_connections++;
  423. }
  424. /**
  425. * Get the static string for the peer this tunnel is directed.
  426. *
  427. * @param t Tunnel.
  428. *
  429. * @return Static string the destination peer's ID.
  430. */
  431. const char *
  432. GCT_2s (const struct CadetTunnel *t)
  433. {
  434. static char buf[64];
  435. if (NULL == t)
  436. return "Tunnel(NULL)";
  437. GNUNET_snprintf (buf,
  438. sizeof(buf),
  439. "Tunnel %s",
  440. GNUNET_i2s (GCP_get_id (t->destination)));
  441. return buf;
  442. }
  443. /**
  444. * Get string description for tunnel encryption state.
  445. *
  446. * @param es Tunnel state.
  447. *
  448. * @return String representation.
  449. */
  450. static const char *
  451. estate2s (enum CadetTunnelEState es)
  452. {
  453. static char buf[32];
  454. switch (es)
  455. {
  456. case CADET_TUNNEL_KEY_UNINITIALIZED:
  457. return "CADET_TUNNEL_KEY_UNINITIALIZED";
  458. case CADET_TUNNEL_KEY_AX_RECV:
  459. return "CADET_TUNNEL_KEY_AX_RECV";
  460. case CADET_TUNNEL_KEY_AX_SENT:
  461. return "CADET_TUNNEL_KEY_AX_SENT";
  462. case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
  463. return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV";
  464. case CADET_TUNNEL_KEY_AX_AUTH_SENT:
  465. return "CADET_TUNNEL_KEY_AX_AUTH_SENT";
  466. case CADET_TUNNEL_KEY_OK:
  467. return "CADET_TUNNEL_KEY_OK";
  468. default:
  469. GNUNET_snprintf (buf,
  470. sizeof(buf),
  471. "%u (UNKNOWN STATE)",
  472. es);
  473. return buf;
  474. }
  475. }
  476. /**
  477. * Return the peer to which this tunnel goes.
  478. *
  479. * @param t a tunnel
  480. * @return the destination of the tunnel
  481. */
  482. struct CadetPeer *
  483. GCT_get_destination (struct CadetTunnel *t)
  484. {
  485. return t->destination;
  486. }
  487. /**
  488. * Count channels of a tunnel.
  489. *
  490. * @param t Tunnel on which to count.
  491. *
  492. * @return Number of channels.
  493. */
  494. unsigned int
  495. GCT_count_channels (struct CadetTunnel *t)
  496. {
  497. return GNUNET_CONTAINER_multihashmap32_size (t->channels);
  498. }
  499. /**
  500. * Lookup a channel by its @a ctn.
  501. *
  502. * @param t tunnel to look in
  503. * @param ctn number of channel to find
  504. * @return NULL if channel does not exist
  505. */
  506. struct CadetChannel *
  507. lookup_channel (struct CadetTunnel *t,
  508. struct GNUNET_CADET_ChannelTunnelNumber ctn)
  509. {
  510. return GNUNET_CONTAINER_multihashmap32_get (t->channels,
  511. ntohl (ctn.cn));
  512. }
  513. /**
  514. * Count all created connections of a tunnel. Not necessarily ready connections!
  515. *
  516. * @param t Tunnel on which to count.
  517. *
  518. * @return Number of connections created, either being established or ready.
  519. */
  520. unsigned int
  521. GCT_count_any_connections (const struct CadetTunnel *t)
  522. {
  523. return t->num_ready_connections + t->num_busy_connections;
  524. }
  525. /**
  526. * Find first connection that is ready in the list of
  527. * our connections. Picks ready connections round-robin.
  528. *
  529. * @param t tunnel to search
  530. * @return NULL if we have no connection that is ready
  531. */
  532. static struct CadetTConnection *
  533. get_ready_connection (struct CadetTunnel *t)
  534. {
  535. struct CadetTConnection *hd = t->connection_ready_head;
  536. GNUNET_assert ((NULL == hd) ||
  537. (GNUNET_YES == hd->is_ready));
  538. return hd;
  539. }
  540. /**
  541. * Get the encryption state of a tunnel.
  542. *
  543. * @param t Tunnel.
  544. *
  545. * @return Tunnel's encryption state.
  546. */
  547. enum CadetTunnelEState
  548. GCT_get_estate (struct CadetTunnel *t)
  549. {
  550. return t->estate;
  551. }
  552. /**
  553. * Called when either we have a new connection, or a new message in the
  554. * queue, or some existing connection has transmission capacity. Looks
  555. * at our message queue and if there is a message, picks a connection
  556. * to send it on.
  557. *
  558. * @param cls the `struct CadetTunnel` to process messages on
  559. */
  560. static void
  561. trigger_transmissions (void *cls);
  562. /* ************************************** start core crypto ***************************** */
  563. /**
  564. * Create a new Axolotl ephemeral (ratchet) key.
  565. *
  566. * @param ax key material to update
  567. */
  568. static void
  569. new_ephemeral (struct CadetTunnelAxolotl *ax)
  570. {
  571. LOG (GNUNET_ERROR_TYPE_DEBUG,
  572. "Creating new ephemeral ratchet key (DHRs)\n");
  573. GNUNET_assert (GNUNET_OK ==
  574. GNUNET_CRYPTO_ecdhe_key_create2 (&ax->DHRs));
  575. }
  576. /**
  577. * Calculate HMAC.
  578. *
  579. * @param plaintext Content to HMAC.
  580. * @param size Size of @c plaintext.
  581. * @param iv Initialization vector for the message.
  582. * @param key Key to use.
  583. * @param hmac[out] Destination to store the HMAC.
  584. */
  585. static void
  586. t_hmac (const void *plaintext,
  587. size_t size,
  588. uint32_t iv,
  589. const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
  590. struct GNUNET_ShortHashCode *hmac)
  591. {
  592. static const char ctx[] = "cadet authentication key";
  593. struct GNUNET_CRYPTO_AuthKey auth_key;
  594. struct GNUNET_HashCode hash;
  595. GNUNET_CRYPTO_hmac_derive_key (&auth_key,
  596. key,
  597. &iv, sizeof(iv),
  598. key, sizeof(*key),
  599. ctx, sizeof(ctx),
  600. NULL);
  601. /* Two step: GNUNET_ShortHash is only 256 bits,
  602. GNUNET_HashCode is 512, so we truncate. */
  603. GNUNET_CRYPTO_hmac (&auth_key,
  604. plaintext,
  605. size,
  606. &hash);
  607. GNUNET_memcpy (hmac,
  608. &hash,
  609. sizeof(*hmac));
  610. }
  611. /**
  612. * Perform a HMAC.
  613. *
  614. * @param key Key to use.
  615. * @param[out] hash Resulting HMAC.
  616. * @param source Source key material (data to HMAC).
  617. * @param len Length of @a source.
  618. */
  619. static void
  620. t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
  621. struct GNUNET_HashCode *hash,
  622. const void *source,
  623. unsigned int len)
  624. {
  625. static const char ctx[] = "axolotl HMAC-HASH";
  626. struct GNUNET_CRYPTO_AuthKey auth_key;
  627. GNUNET_CRYPTO_hmac_derive_key (&auth_key,
  628. key,
  629. ctx, sizeof(ctx),
  630. NULL);
  631. GNUNET_CRYPTO_hmac (&auth_key,
  632. source,
  633. len,
  634. hash);
  635. }
  636. /**
  637. * Derive a symmetric encryption key from an HMAC-HASH.
  638. *
  639. * @param key Key to use for the HMAC.
  640. * @param[out] out Key to generate.
  641. * @param source Source key material (data to HMAC).
  642. * @param len Length of @a source.
  643. */
  644. static void
  645. t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
  646. struct GNUNET_CRYPTO_SymmetricSessionKey *out,
  647. const void *source,
  648. unsigned int len)
  649. {
  650. static const char ctx[] = "axolotl derive key";
  651. struct GNUNET_HashCode h;
  652. t_ax_hmac_hash (key,
  653. &h,
  654. source,
  655. len);
  656. GNUNET_CRYPTO_kdf (out, sizeof(*out),
  657. ctx, sizeof(ctx),
  658. &h, sizeof(h),
  659. NULL);
  660. }
  661. /**
  662. * Encrypt data with the axolotl tunnel key.
  663. *
  664. * @param ax key material to use.
  665. * @param dst Destination with @a size bytes for the encrypted data.
  666. * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
  667. * @param size Size of the buffers at @a src and @a dst
  668. */
  669. static void
  670. t_ax_encrypt (struct CadetTunnelAxolotl *ax,
  671. void *dst,
  672. const void *src,
  673. size_t size)
  674. {
  675. struct GNUNET_CRYPTO_SymmetricSessionKey MK;
  676. struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
  677. size_t out_size;
  678. ax->ratchet_counter++;
  679. if ((GNUNET_YES == ax->ratchet_allowed) &&
  680. ((ratchet_messages <= ax->ratchet_counter) ||
  681. (0 == GNUNET_TIME_absolute_get_remaining (
  682. ax->ratchet_expiration).rel_value_us)))
  683. {
  684. ax->ratchet_flag = GNUNET_YES;
  685. }
  686. if (GNUNET_YES == ax->ratchet_flag)
  687. {
  688. /* Advance ratchet */
  689. struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
  690. struct GNUNET_HashCode dh;
  691. struct GNUNET_HashCode hmac;
  692. static const char ctx[] = "axolotl ratchet";
  693. new_ephemeral (ax);
  694. ax->HKs = ax->NHKs;
  695. /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
  696. GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
  697. &ax->DHRr,
  698. &dh);
  699. t_ax_hmac_hash (&ax->RK,
  700. &hmac,
  701. &dh,
  702. sizeof(dh));
  703. GNUNET_CRYPTO_kdf (keys, sizeof(keys),
  704. ctx, sizeof(ctx),
  705. &hmac, sizeof(hmac),
  706. NULL);
  707. ax->RK = keys[0];
  708. ax->NHKs = keys[1];
  709. ax->CKs = keys[2];
  710. ax->PNs = ax->Ns;
  711. ax->Ns = 0;
  712. ax->ratchet_flag = GNUNET_NO;
  713. ax->ratchet_allowed = GNUNET_NO;
  714. ax->ratchet_counter = 0;
  715. ax->ratchet_expiration
  716. = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
  717. ratchet_time);
  718. }
  719. t_hmac_derive_key (&ax->CKs,
  720. &MK,
  721. "0",
  722. 1);
  723. GNUNET_CRYPTO_symmetric_derive_iv (&iv,
  724. &MK,
  725. NULL, 0,
  726. NULL);
  727. out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
  728. size,
  729. &MK,
  730. &iv,
  731. dst);
  732. GNUNET_assert (size == out_size);
  733. t_hmac_derive_key (&ax->CKs,
  734. &ax->CKs,
  735. "1",
  736. 1);
  737. }
  738. /**
  739. * Decrypt data with the axolotl tunnel key.
  740. *
  741. * @param ax key material to use.
  742. * @param dst Destination for the decrypted data, must contain @a size bytes.
  743. * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
  744. * @param size Size of the @a src and @a dst buffers
  745. */
  746. static void
  747. t_ax_decrypt (struct CadetTunnelAxolotl *ax,
  748. void *dst,
  749. const void *src,
  750. size_t size)
  751. {
  752. struct GNUNET_CRYPTO_SymmetricSessionKey MK;
  753. struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
  754. size_t out_size;
  755. t_hmac_derive_key (&ax->CKr,
  756. &MK,
  757. "0",
  758. 1);
  759. GNUNET_CRYPTO_symmetric_derive_iv (&iv,
  760. &MK,
  761. NULL, 0,
  762. NULL);
  763. GNUNET_assert (size >= sizeof(struct GNUNET_MessageHeader));
  764. out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
  765. size,
  766. &MK,
  767. &iv,
  768. dst);
  769. GNUNET_assert (out_size == size);
  770. t_hmac_derive_key (&ax->CKr,
  771. &ax->CKr,
  772. "1",
  773. 1);
  774. }
  775. /**
  776. * Encrypt header with the axolotl header key.
  777. *
  778. * @param ax key material to use.
  779. * @param[in|out] msg Message whose header to encrypt.
  780. */
  781. static void
  782. t_h_encrypt (struct CadetTunnelAxolotl *ax,
  783. struct GNUNET_CADET_TunnelEncryptedMessage *msg)
  784. {
  785. struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
  786. size_t out_size;
  787. GNUNET_CRYPTO_symmetric_derive_iv (&iv,
  788. &ax->HKs,
  789. NULL, 0,
  790. NULL);
  791. out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
  792. sizeof(struct
  793. GNUNET_CADET_AxHeader),
  794. &ax->HKs,
  795. &iv,
  796. &msg->ax_header);
  797. GNUNET_assert (sizeof(struct GNUNET_CADET_AxHeader) == out_size);
  798. }
  799. /**
  800. * Decrypt header with the current axolotl header key.
  801. *
  802. * @param ax key material to use.
  803. * @param src Message whose header to decrypt.
  804. * @param dst Where to decrypt header to.
  805. */
  806. static void
  807. t_h_decrypt (struct CadetTunnelAxolotl *ax,
  808. const struct GNUNET_CADET_TunnelEncryptedMessage *src,
  809. struct GNUNET_CADET_TunnelEncryptedMessage *dst)
  810. {
  811. struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
  812. size_t out_size;
  813. GNUNET_CRYPTO_symmetric_derive_iv (&iv,
  814. &ax->HKr,
  815. NULL, 0,
  816. NULL);
  817. out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
  818. sizeof(struct
  819. GNUNET_CADET_AxHeader),
  820. &ax->HKr,
  821. &iv,
  822. &dst->ax_header.Ns);
  823. GNUNET_assert (sizeof(struct GNUNET_CADET_AxHeader) == out_size);
  824. }
  825. /**
  826. * Delete a key from the list of skipped keys.
  827. *
  828. * @param ax key material to delete @a key from.
  829. * @param key Key to delete.
  830. */
  831. static void
  832. delete_skipped_key (struct CadetTunnelAxolotl *ax,
  833. struct CadetTunnelSkippedKey *key)
  834. {
  835. GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
  836. ax->skipped_tail,
  837. key);
  838. GNUNET_free (key);
  839. ax->skipped--;
  840. }
  841. /**
  842. * Decrypt and verify data with the appropriate tunnel key and verify that the
  843. * data has not been altered since it was sent by the remote peer.
  844. *
  845. * @param ax key material to use.
  846. * @param dst Destination for the plaintext.
  847. * @param src Source of the message. Can overlap with @c dst.
  848. * @param size Size of the message.
  849. * @return Size of the decrypted data, -1 if an error was encountered.
  850. */
  851. static ssize_t
  852. try_old_ax_keys (struct CadetTunnelAxolotl *ax,
  853. void *dst,
  854. const struct GNUNET_CADET_TunnelEncryptedMessage *src,
  855. size_t size)
  856. {
  857. struct CadetTunnelSkippedKey *key;
  858. struct GNUNET_ShortHashCode *hmac;
  859. struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
  860. struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
  861. struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
  862. size_t esize;
  863. size_t res;
  864. size_t len;
  865. unsigned int N;
  866. LOG (GNUNET_ERROR_TYPE_DEBUG,
  867. "Trying skipped keys\n");
  868. hmac = &plaintext_header.hmac;
  869. esize = size - sizeof(struct GNUNET_CADET_TunnelEncryptedMessage);
  870. /* Find a correct Header Key */
  871. valid_HK = NULL;
  872. for (key = ax->skipped_head; NULL != key; key = key->next)
  873. {
  874. t_hmac (&src->ax_header,
  875. sizeof(struct GNUNET_CADET_AxHeader) + esize,
  876. 0,
  877. &key->HK,
  878. hmac);
  879. if (0 == GNUNET_memcmp (hmac,
  880. &src->hmac))
  881. {
  882. valid_HK = &key->HK;
  883. break;
  884. }
  885. }
  886. if (NULL == key)
  887. return -1;
  888. /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
  889. GNUNET_assert (size > sizeof(struct GNUNET_CADET_TunnelEncryptedMessage));
  890. len = size - sizeof(struct GNUNET_CADET_TunnelEncryptedMessage);
  891. GNUNET_assert (len >= sizeof(struct GNUNET_MessageHeader));
  892. /* Decrypt header */
  893. GNUNET_CRYPTO_symmetric_derive_iv (&iv,
  894. &key->HK,
  895. NULL, 0,
  896. NULL);
  897. res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
  898. sizeof(struct GNUNET_CADET_AxHeader),
  899. &key->HK,
  900. &iv,
  901. &plaintext_header.ax_header.Ns);
  902. GNUNET_assert (sizeof(struct GNUNET_CADET_AxHeader) == res);
  903. /* Find the correct message key */
  904. N = ntohl (plaintext_header.ax_header.Ns);
  905. while ((NULL != key) &&
  906. (N != key->Kn))
  907. key = key->next;
  908. if ((NULL == key) ||
  909. (0 != GNUNET_memcmp (&key->HK,
  910. valid_HK)))
  911. return -1;
  912. /* Decrypt payload */
  913. GNUNET_CRYPTO_symmetric_derive_iv (&iv,
  914. &key->MK,
  915. NULL,
  916. 0,
  917. NULL);
  918. res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
  919. len,
  920. &key->MK,
  921. &iv,
  922. dst);
  923. delete_skipped_key (ax,
  924. key);
  925. return res;
  926. }
  927. /**
  928. * Delete a key from the list of skipped keys.
  929. *
  930. * @param ax key material to delete from.
  931. * @param HKr Header Key to use.
  932. */
  933. static void
  934. store_skipped_key (struct CadetTunnelAxolotl *ax,
  935. const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
  936. {
  937. struct CadetTunnelSkippedKey *key;
  938. key = GNUNET_new (struct CadetTunnelSkippedKey);
  939. key->timestamp = GNUNET_TIME_absolute_get ();
  940. key->Kn = ax->Nr;
  941. key->HK = ax->HKr;
  942. t_hmac_derive_key (&ax->CKr,
  943. &key->MK,
  944. "0",
  945. 1);
  946. t_hmac_derive_key (&ax->CKr,
  947. &ax->CKr,
  948. "1",
  949. 1);
  950. GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
  951. ax->skipped_tail,
  952. key);
  953. ax->skipped++;
  954. ax->Nr++;
  955. }
  956. /**
  957. * Stage skipped AX keys and calculate the message key.
  958. * Stores each HK and MK for skipped messages.
  959. *
  960. * @param ax key material to use
  961. * @param HKr Header key.
  962. * @param Np Received meesage number.
  963. * @return #GNUNET_OK if keys were stored.
  964. * #GNUNET_SYSERR if an error ocurred (@a Np not expected).
  965. */
  966. static int
  967. store_ax_keys (struct CadetTunnelAxolotl *ax,
  968. const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
  969. uint32_t Np)
  970. {
  971. int gap;
  972. gap = Np - ax->Nr;
  973. LOG (GNUNET_ERROR_TYPE_DEBUG,
  974. "Storing skipped keys [%u, %u)\n",
  975. ax->Nr,
  976. Np);
  977. if (MAX_KEY_GAP < gap)
  978. {
  979. /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
  980. /* TODO: start new key exchange on return */
  981. GNUNET_break_op (0);
  982. LOG (GNUNET_ERROR_TYPE_WARNING,
  983. "Got message %u, expected %u+\n",
  984. Np,
  985. ax->Nr);
  986. return GNUNET_SYSERR;
  987. }
  988. if (0 > gap)
  989. {
  990. /* Delayed message: don't store keys, flag to try old keys. */
  991. return GNUNET_SYSERR;
  992. }
  993. while (ax->Nr < Np)
  994. store_skipped_key (ax,
  995. HKr);
  996. while (ax->skipped > MAX_SKIPPED_KEYS)
  997. delete_skipped_key (ax,
  998. ax->skipped_tail);
  999. return GNUNET_OK;
  1000. }
  1001. /**
  1002. * Decrypt and verify data with the appropriate tunnel key and verify that the
  1003. * data has not been altered since it was sent by the remote peer.
  1004. *
  1005. * @param ax key material to use
  1006. * @param dst Destination for the plaintext.
  1007. * @param src Source of the message. Can overlap with @c dst.
  1008. * @param size Size of the message.
  1009. * @return Size of the decrypted data, -1 if an error was encountered.
  1010. */
  1011. static ssize_t
  1012. t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
  1013. void *dst,
  1014. const struct
  1015. GNUNET_CADET_TunnelEncryptedMessage *src,
  1016. size_t size)
  1017. {
  1018. struct GNUNET_ShortHashCode msg_hmac;
  1019. struct GNUNET_HashCode hmac;
  1020. struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
  1021. uint32_t Np;
  1022. uint32_t PNp;
  1023. size_t esize; /* Size of encryped payload */
  1024. esize = size - sizeof(struct GNUNET_CADET_TunnelEncryptedMessage);
  1025. /* Try current HK */
  1026. t_hmac (&src->ax_header,
  1027. sizeof(struct GNUNET_CADET_AxHeader) + esize,
  1028. 0, &ax->HKr,
  1029. &msg_hmac);
  1030. if (0 != GNUNET_memcmp (&msg_hmac,
  1031. &src->hmac))
  1032. {
  1033. static const char ctx[] = "axolotl ratchet";
  1034. struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
  1035. struct GNUNET_CRYPTO_SymmetricSessionKey HK;
  1036. struct GNUNET_HashCode dh;
  1037. struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
  1038. /* Try Next HK */
  1039. t_hmac (&src->ax_header,
  1040. sizeof(struct GNUNET_CADET_AxHeader) + esize,
  1041. 0,
  1042. &ax->NHKr,
  1043. &msg_hmac);
  1044. if (0 != GNUNET_memcmp (&msg_hmac,
  1045. &src->hmac))
  1046. {
  1047. /* Try the skipped keys, if that fails, we're out of luck. */
  1048. return try_old_ax_keys (ax,
  1049. dst,
  1050. src,
  1051. size);
  1052. }
  1053. HK = ax->HKr;
  1054. ax->HKr = ax->NHKr;
  1055. t_h_decrypt (ax,
  1056. src,
  1057. &plaintext_header);
  1058. Np = ntohl (plaintext_header.ax_header.Ns);
  1059. PNp = ntohl (plaintext_header.ax_header.PNs);
  1060. DHRp = &plaintext_header.ax_header.DHRs;
  1061. store_ax_keys (ax,
  1062. &HK,
  1063. PNp);
  1064. /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
  1065. GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
  1066. DHRp,
  1067. &dh);
  1068. t_ax_hmac_hash (&ax->RK,
  1069. &hmac,
  1070. &dh, sizeof(dh));
  1071. GNUNET_CRYPTO_kdf (keys, sizeof(keys),
  1072. ctx, sizeof(ctx),
  1073. &hmac, sizeof(hmac),
  1074. NULL);
  1075. /* Commit "purported" keys */
  1076. ax->RK = keys[0];
  1077. ax->NHKr = keys[1];
  1078. ax->CKr = keys[2];
  1079. ax->DHRr = *DHRp;
  1080. ax->Nr = 0;
  1081. ax->ratchet_allowed = GNUNET_YES;
  1082. }
  1083. else
  1084. {
  1085. t_h_decrypt (ax,
  1086. src,
  1087. &plaintext_header);
  1088. Np = ntohl (plaintext_header.ax_header.Ns);
  1089. PNp = ntohl (plaintext_header.ax_header.PNs);
  1090. }
  1091. if ((Np != ax->Nr) &&
  1092. (GNUNET_OK != store_ax_keys (ax,
  1093. &ax->HKr,
  1094. Np)))
  1095. {
  1096. /* Try the skipped keys, if that fails, we're out of luck. */
  1097. return try_old_ax_keys (ax,
  1098. dst,
  1099. src,
  1100. size);
  1101. }
  1102. t_ax_decrypt (ax,
  1103. dst,
  1104. &src[1],
  1105. esize);
  1106. ax->Nr = Np + 1;
  1107. return esize;
  1108. }
  1109. /**
  1110. * Our tunnel became ready for the first time, notify channels
  1111. * that have been waiting.
  1112. *
  1113. * @param cls our tunnel, not used
  1114. * @param key unique ID of the channel, not used
  1115. * @param value the `struct CadetChannel` to notify
  1116. * @return #GNUNET_OK (continue to iterate)
  1117. */
  1118. static int
  1119. notify_tunnel_up_cb (void *cls,
  1120. uint32_t key,
  1121. void *value)
  1122. {
  1123. struct CadetChannel *ch = value;
  1124. GCCH_tunnel_up (ch);
  1125. return GNUNET_OK;
  1126. }
  1127. /**
  1128. * Change the tunnel encryption state.
  1129. * If the encryption state changes to OK, stop the rekey task.
  1130. *
  1131. * @param t Tunnel whose encryption state to change, or NULL.
  1132. * @param state New encryption state.
  1133. */
  1134. void
  1135. GCT_change_estate (struct CadetTunnel *t,
  1136. enum CadetTunnelEState state)
  1137. {
  1138. enum CadetTunnelEState old = t->estate;
  1139. t->estate = state;
  1140. LOG (GNUNET_ERROR_TYPE_DEBUG,
  1141. "%s estate changed from %s to %s\n",
  1142. GCT_2s (t),
  1143. estate2s (old),
  1144. estate2s (state));
  1145. if ((CADET_TUNNEL_KEY_OK != old) &&
  1146. (CADET_TUNNEL_KEY_OK == t->estate))
  1147. {
  1148. if (NULL != t->kx_task)
  1149. {
  1150. GNUNET_SCHEDULER_cancel (t->kx_task);
  1151. t->kx_task = NULL;
  1152. }
  1153. /* notify all channels that have been waiting */
  1154. GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
  1155. &notify_tunnel_up_cb,
  1156. t);
  1157. if (NULL != t->send_task)
  1158. GNUNET_SCHEDULER_cancel (t->send_task);
  1159. t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
  1160. t);
  1161. }
  1162. }
  1163. /**
  1164. * Send a KX message.
  1165. *
  1166. * @param t tunnel on which to send the KX_AUTH
  1167. * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
  1168. * we are to find one that is ready.
  1169. * @param ax axolotl key context to use
  1170. */
  1171. static void
  1172. send_kx (struct CadetTunnel *t,
  1173. struct CadetTConnection *ct,
  1174. struct CadetTunnelAxolotl *ax)
  1175. {
  1176. struct CadetConnection *cc;
  1177. struct GNUNET_MQ_Envelope *env;
  1178. struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
  1179. enum GNUNET_CADET_KX_Flags flags;
  1180. if (GNUNET_YES != alice_or_betty (GCP_get_id (t->destination)))
  1181. return; /* only Alice may send KX */
  1182. if ((NULL == ct) ||
  1183. (GNUNET_NO == ct->is_ready))
  1184. ct = get_ready_connection (t);
  1185. if (NULL == ct)
  1186. {
  1187. LOG (GNUNET_ERROR_TYPE_DEBUG,
  1188. "Wanted to send %s in state %s, but no connection is ready, deferring\n",
  1189. GCT_2s (t),
  1190. estate2s (t->estate));
  1191. t->next_kx_attempt = GNUNET_TIME_absolute_get ();
  1192. return;
  1193. }
  1194. cc = ct->cc;
  1195. env = GNUNET_MQ_msg (msg,
  1196. GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
  1197. flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */
  1198. msg->flags = htonl (flags);
  1199. msg->cid = *GCC_get_id (cc);
  1200. GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
  1201. &msg->ephemeral_key);
  1202. #if DEBUG_KX
  1203. msg->ephemeral_key_XXX = ax->kx_0;
  1204. msg->private_key_XXX = *my_private_key;
  1205. #endif
  1206. LOG (GNUNET_ERROR_TYPE_DEBUG,
  1207. "Sending KX message to %s with ephemeral %s on CID %s\n",
  1208. GCT_2s (t),
  1209. GNUNET_e2s (&msg->ephemeral_key),
  1210. GNUNET_sh2s (&msg->cid.connection_of_tunnel));
  1211. GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
  1212. &msg->ratchet_key);
  1213. mark_connection_unready (ct);
  1214. t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
  1215. t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
  1216. if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
  1217. GCT_change_estate (t,
  1218. CADET_TUNNEL_KEY_AX_SENT);
  1219. else if (CADET_TUNNEL_KEY_AX_RECV == t->estate)
  1220. GCT_change_estate (t,
  1221. CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
  1222. GCC_transmit (cc,
  1223. env);
  1224. GNUNET_STATISTICS_update (stats,
  1225. "# KX transmitted",
  1226. 1,
  1227. GNUNET_NO);
  1228. }
  1229. /**
  1230. * Send a KX_AUTH message.
  1231. *
  1232. * @param t tunnel on which to send the KX_AUTH
  1233. * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
  1234. * we are to find one that is ready.
  1235. * @param ax axolotl key context to use
  1236. * @param force_reply Force the other peer to reply with a KX_AUTH message
  1237. * (set if we would like to transmit right now, but cannot)
  1238. */
  1239. static void
  1240. send_kx_auth (struct CadetTunnel *t,
  1241. struct CadetTConnection *ct,
  1242. struct CadetTunnelAxolotl *ax,
  1243. int force_reply)
  1244. {
  1245. struct CadetConnection *cc;
  1246. struct GNUNET_MQ_Envelope *env;
  1247. struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg;
  1248. enum GNUNET_CADET_KX_Flags flags;
  1249. if ((NULL == ct) ||
  1250. (GNUNET_NO == ct->is_ready))
  1251. ct = get_ready_connection (t);
  1252. if (NULL == ct)
  1253. {
  1254. LOG (GNUNET_ERROR_TYPE_DEBUG,
  1255. "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n",
  1256. GCT_2s (t));
  1257. t->next_kx_attempt = GNUNET_TIME_absolute_get ();
  1258. t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */
  1259. return;
  1260. }
  1261. t->kx_auth_requested = GNUNET_NO; /* clear flag */
  1262. cc = ct->cc;
  1263. env = GNUNET_MQ_msg (msg,
  1264. GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH);
  1265. flags = GNUNET_CADET_KX_FLAG_NONE;
  1266. if (GNUNET_YES == force_reply)
  1267. flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
  1268. msg->kx.flags = htonl (flags);
  1269. msg->kx.cid = *GCC_get_id (cc);
  1270. GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
  1271. &msg->kx.ephemeral_key);
  1272. GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
  1273. &msg->kx.ratchet_key);
  1274. #if DEBUG_KX
  1275. msg->kx.ephemeral_key_XXX = ax->kx_0;
  1276. msg->kx.private_key_XXX = *my_private_key;
  1277. msg->r_ephemeral_key_XXX = ax->last_ephemeral;
  1278. #endif
  1279. LOG (GNUNET_ERROR_TYPE_DEBUG,
  1280. "Sending KX_AUTH message to %s with ephemeral %s on CID %s\n",
  1281. GCT_2s (t),
  1282. GNUNET_e2s (&msg->kx.ephemeral_key),
  1283. GNUNET_sh2s (&msg->kx.cid.connection_of_tunnel));
  1284. /* Compute authenticator (this is the main difference to #send_kx()) */
  1285. GNUNET_CRYPTO_hash (&ax->RK,
  1286. sizeof(ax->RK),
  1287. &msg->auth);
  1288. /* Compute when to be triggered again; actual job will
  1289. be scheduled via #connection_ready_cb() */
  1290. t->kx_retry_delay
  1291. = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
  1292. t->next_kx_attempt
  1293. = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
  1294. /* Send via cc, mark it as unready */
  1295. mark_connection_unready (ct);
  1296. /* Update state machine, unless we are already OK */
  1297. if (CADET_TUNNEL_KEY_OK != t->estate)
  1298. GCT_change_estate (t,
  1299. CADET_TUNNEL_KEY_AX_AUTH_SENT);
  1300. GCC_transmit (cc,
  1301. env);
  1302. GNUNET_STATISTICS_update (stats,
  1303. "# KX_AUTH transmitted",
  1304. 1,
  1305. GNUNET_NO);
  1306. }
  1307. /**
  1308. * Cleanup state used by @a ax.
  1309. *
  1310. * @param ax state to free, but not memory of @a ax itself
  1311. */
  1312. static void
  1313. cleanup_ax (struct CadetTunnelAxolotl *ax)
  1314. {
  1315. while (NULL != ax->skipped_head)
  1316. delete_skipped_key (ax,
  1317. ax->skipped_head);
  1318. GNUNET_assert (0 == ax->skipped);
  1319. GNUNET_CRYPTO_ecdhe_key_clear (&ax->kx_0);
  1320. GNUNET_CRYPTO_ecdhe_key_clear (&ax->DHRs);
  1321. }
  1322. /**
  1323. * Update our Axolotl key state based on the KX data we received.
  1324. * Computes the new chain keys, and root keys, etc, and also checks
  1325. * whether this is a replay of the current chain.
  1326. *
  1327. * @param[in|out] axolotl chain key state to recompute
  1328. * @param pid peer identity of the other peer
  1329. * @param ephemeral_key ephemeral public key of the other peer
  1330. * @param ratchet_key senders next ephemeral public key
  1331. * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
  1332. * root key is already in @a ax and thus the KX is useless;
  1333. * #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
  1334. */
  1335. static int
  1336. update_ax_by_kx (struct CadetTunnelAxolotl *ax,
  1337. const struct GNUNET_PeerIdentity *pid,
  1338. const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
  1339. const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
  1340. {
  1341. struct GNUNET_HashCode key_material[3];
  1342. struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
  1343. const char salt[] = "CADET Axolotl salt";
  1344. int am_I_alice;
  1345. if (GNUNET_SYSERR == (am_I_alice = alice_or_betty (pid)))
  1346. {
  1347. GNUNET_break_op (0);
  1348. return GNUNET_SYSERR;
  1349. }
  1350. if (0 == GNUNET_memcmp (&ax->DHRr,
  1351. ratchet_key))
  1352. {
  1353. GNUNET_STATISTICS_update (stats,
  1354. "# Ratchet key already known",
  1355. 1,
  1356. GNUNET_NO);
  1357. LOG (GNUNET_ERROR_TYPE_DEBUG,
  1358. "Ratchet key already known. Ignoring KX.\n");
  1359. return GNUNET_NO;
  1360. }
  1361. ax->DHRr = *ratchet_key;
  1362. ax->last_ephemeral = *ephemeral_key;
  1363. /* ECDH A B0 */
  1364. if (GNUNET_YES == am_I_alice)
  1365. {
  1366. GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* a */
  1367. ephemeral_key, /* B0 */
  1368. &key_material[0]);
  1369. }
  1370. else
  1371. {
  1372. GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0, /* b0 */
  1373. &pid->public_key, /* A */
  1374. &key_material[0]);
  1375. }
  1376. /* ECDH A0 B */
  1377. if (GNUNET_YES == am_I_alice)
  1378. {
  1379. GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0, /* a0 */
  1380. &pid->public_key, /* B */
  1381. &key_material[1]);
  1382. }
  1383. else
  1384. {
  1385. GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* b */
  1386. ephemeral_key, /* A0 */
  1387. &key_material[1]);
  1388. }
  1389. /* ECDH A0 B0 */
  1390. GNUNET_CRYPTO_ecc_ecdh (&ax->kx_0, /* a0 or b0 */
  1391. ephemeral_key, /* B0 or A0 */
  1392. &key_material[2]);
  1393. /* KDF */
  1394. GNUNET_CRYPTO_kdf (keys, sizeof(keys),
  1395. salt, sizeof(salt),
  1396. &key_material, sizeof(key_material),
  1397. NULL);
  1398. if (0 == memcmp (&ax->RK,
  1399. &keys[0],
  1400. sizeof(ax->RK)))
  1401. {
  1402. LOG (GNUNET_ERROR_TYPE_DEBUG,
  1403. "Root key already known. Ignoring KX.\n");
  1404. GNUNET_STATISTICS_update (stats,
  1405. "# Root key already known",
  1406. 1,
  1407. GNUNET_NO);
  1408. return GNUNET_NO;
  1409. }
  1410. ax->RK = keys[0];
  1411. if (GNUNET_YES == am_I_alice)
  1412. {
  1413. ax->HKr = keys[1];
  1414. ax->NHKs = keys[2];
  1415. ax->NHKr = keys[3];
  1416. ax->CKr = keys[4];
  1417. ax->ratchet_flag = GNUNET_YES;
  1418. }
  1419. else
  1420. {
  1421. ax->HKs = keys[1];
  1422. ax->NHKr = keys[2];
  1423. ax->NHKs = keys[3];
  1424. ax->CKs = keys[4];
  1425. ax->ratchet_flag = GNUNET_NO;
  1426. ax->ratchet_expiration
  1427. = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
  1428. ratchet_time);
  1429. }
  1430. return GNUNET_OK;
  1431. }
  1432. /**
  1433. * Try to redo the KX or KX_AUTH handshake, if we can.
  1434. *
  1435. * @param cls the `struct CadetTunnel` to do KX for.
  1436. */
  1437. static void
  1438. retry_kx (void *cls)
  1439. {
  1440. struct CadetTunnel *t = cls;
  1441. struct CadetTunnelAxolotl *ax;
  1442. t->kx_task = NULL;
  1443. LOG (GNUNET_ERROR_TYPE_DEBUG,
  1444. "Trying to make KX progress on %s in state %s\n",
  1445. GCT_2s (t),
  1446. estate2s (t->estate));
  1447. switch (t->estate)
  1448. {
  1449. case CADET_TUNNEL_KEY_UNINITIALIZED: /* first attempt */
  1450. case CADET_TUNNEL_KEY_AX_SENT: /* trying again */
  1451. send_kx (t,
  1452. NULL,
  1453. &t->ax);
  1454. break;
  1455. case CADET_TUNNEL_KEY_AX_RECV:
  1456. case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
  1457. /* We are responding, so only require reply
  1458. if WE have a channel waiting. */
  1459. if (NULL != t->unverified_ax)
  1460. {
  1461. /* Send AX_AUTH so we might get this one verified */
  1462. ax = t->unverified_ax;
  1463. }
  1464. else
  1465. {
  1466. /* How can this be? */
  1467. GNUNET_break (0);
  1468. ax = &t->ax;
  1469. }
  1470. send_kx_auth (t,
  1471. NULL,
  1472. ax,
  1473. (0 == GCT_count_channels (t))
  1474. ? GNUNET_NO
  1475. : GNUNET_YES);
  1476. break;
  1477. case CADET_TUNNEL_KEY_AX_AUTH_SENT:
  1478. /* We are responding, so only require reply
  1479. if WE have a channel waiting. */
  1480. if (NULL != t->unverified_ax)
  1481. {
  1482. /* Send AX_AUTH so we might get this one verified */
  1483. ax = t->unverified_ax;
  1484. }
  1485. else
  1486. {
  1487. /* How can this be? */
  1488. GNUNET_break (0);
  1489. ax = &t->ax;
  1490. }
  1491. send_kx_auth (t,
  1492. NULL,
  1493. ax,
  1494. (0 == GCT_count_channels (t))
  1495. ? GNUNET_NO
  1496. : GNUNET_YES);
  1497. break;
  1498. case CADET_TUNNEL_KEY_OK:
  1499. /* Must have been the *other* peer asking us to
  1500. respond with a KX_AUTH. */
  1501. if (NULL != t->unverified_ax)
  1502. {
  1503. /* Sending AX_AUTH in response to AX so we might get this one verified */
  1504. ax = t->unverified_ax;
  1505. }
  1506. else
  1507. {
  1508. /* Sending AX_AUTH in response to AX_AUTH */
  1509. ax = &t->ax;
  1510. }
  1511. send_kx_auth (t,
  1512. NULL,
  1513. ax,
  1514. GNUNET_NO);
  1515. break;
  1516. }
  1517. }
  1518. /**
  1519. * Handle KX message that lacks authentication (and which will thus
  1520. * only be considered authenticated after we respond with our own
  1521. * KX_AUTH and finally successfully decrypt payload).
  1522. *
  1523. * @param ct connection/tunnel combo that received encrypted message
  1524. * @param msg the key exchange message
  1525. */
  1526. void
  1527. GCT_handle_kx (struct CadetTConnection *ct,
  1528. const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
  1529. {
  1530. struct CadetTunnel *t = ct->t;
  1531. int ret;
  1532. GNUNET_STATISTICS_update (stats,
  1533. "# KX received",
  1534. 1,
  1535. GNUNET_NO);
  1536. if (GNUNET_YES ==
  1537. alice_or_betty (GCP_get_id (t->destination)))
  1538. {
  1539. /* Betty/Bob is not allowed to send KX! */
  1540. GNUNET_break_op (0);
  1541. return;
  1542. }
  1543. LOG (GNUNET_ERROR_TYPE_DEBUG,
  1544. "Received KX message from %s with ephemeral %s from %s on connection %s\n",
  1545. GCT_2s (t),
  1546. GNUNET_e2s (&msg->ephemeral_key),
  1547. GNUNET_i2s (GCP_get_id (t->destination)),
  1548. GCC_2s (ct->cc));
  1549. #if 1
  1550. if ((0 ==
  1551. memcmp (&t->ax.DHRr,
  1552. &msg->ratchet_key,
  1553. sizeof(msg->ratchet_key))) &&
  1554. (0 ==
  1555. memcmp (&t->ax.last_ephemeral,
  1556. &msg->ephemeral_key,
  1557. sizeof(msg->ephemeral_key))))
  1558. {
  1559. GNUNET_STATISTICS_update (stats,
  1560. "# Duplicate KX received",
  1561. 1,
  1562. GNUNET_NO);
  1563. send_kx_auth (t,
  1564. ct,
  1565. &t->ax,
  1566. GNUNET_NO);
  1567. return;
  1568. }
  1569. #endif
  1570. /* We only keep ONE unverified KX around, so if there is an existing one,
  1571. clean it up. */
  1572. if (NULL != t->unverified_ax)
  1573. {
  1574. if ((0 ==
  1575. memcmp (&t->unverified_ax->DHRr,
  1576. &msg->ratchet_key,
  1577. sizeof(msg->ratchet_key))) &&
  1578. (0 ==
  1579. memcmp (&t->unverified_ax->last_ephemeral,
  1580. &msg->ephemeral_key,
  1581. sizeof(msg->ephemeral_key))))
  1582. {
  1583. GNUNET_STATISTICS_update (stats,
  1584. "# Duplicate unverified KX received",
  1585. 1,
  1586. GNUNET_NO);
  1587. #if 1
  1588. send_kx_auth (t,
  1589. ct,
  1590. t->unverified_ax,
  1591. GNUNET_NO);
  1592. return;
  1593. #endif
  1594. }
  1595. LOG (GNUNET_ERROR_TYPE_DEBUG,
  1596. "Dropping old unverified KX state.\n");
  1597. GNUNET_STATISTICS_update (stats,
  1598. "# Unverified KX dropped for fresh KX",
  1599. 1,
  1600. GNUNET_NO);
  1601. GNUNET_break (NULL == t->unverified_ax->skipped_head);
  1602. memset (t->unverified_ax,
  1603. 0,
  1604. sizeof(struct CadetTunnelAxolotl));
  1605. }
  1606. else
  1607. {
  1608. LOG (GNUNET_ERROR_TYPE_DEBUG,
  1609. "Creating fresh unverified KX for %s\n",
  1610. GCT_2s (t));
  1611. GNUNET_STATISTICS_update (stats,
  1612. "# Fresh KX setup",
  1613. 1,
  1614. GNUNET_NO);
  1615. t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
  1616. }
  1617. /* Set as the 'current' RK/DHRr the one we are currently using,
  1618. so that the duplicate-detection logic of
  1619. #update_ax_by_kx can work. */
  1620. t->unverified_ax->RK = t->ax.RK;
  1621. t->unverified_ax->DHRr = t->ax.DHRr;
  1622. t->unverified_ax->DHRs = t->ax.DHRs;
  1623. t->unverified_ax->kx_0 = t->ax.kx_0;
  1624. t->unverified_attempts = 0;
  1625. /* Update 'ax' by the new key material */
  1626. ret = update_ax_by_kx (t->unverified_ax,
  1627. GCP_get_id (t->destination),
  1628. &msg->ephemeral_key,
  1629. &msg->ratchet_key);
  1630. GNUNET_break (GNUNET_SYSERR != ret);
  1631. if (GNUNET_OK != ret)
  1632. {
  1633. GNUNET_STATISTICS_update (stats,
  1634. "# Useless KX",
  1635. 1,
  1636. GNUNET_NO);
  1637. return; /* duplicate KX, nothing to do */
  1638. }
  1639. /* move ahead in our state machine */
  1640. if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
  1641. GCT_change_estate (t,
  1642. CADET_TUNNEL_KEY_AX_RECV);
  1643. else if (CADET_TUNNEL_KEY_AX_SENT == t->estate)
  1644. GCT_change_estate (t,
  1645. CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
  1646. /* KX is still not done, try again our end. */
  1647. if (CADET_TUNNEL_KEY_OK != t->estate)
  1648. {
  1649. if (NULL != t->kx_task)
  1650. GNUNET_SCHEDULER_cancel (t->kx_task);
  1651. t->kx_task
  1652. = GNUNET_SCHEDULER_add_now (&retry_kx,
  1653. t);
  1654. }
  1655. }
  1656. #if DEBUG_KX
  1657. static void
  1658. check_ee (const struct GNUNET_CRYPTO_EcdhePrivateKey *e1,
  1659. const struct GNUNET_CRYPTO_EcdhePrivateKey *e2)
  1660. {
  1661. struct GNUNET_CRYPTO_EcdhePublicKey p1;
  1662. struct GNUNET_CRYPTO_EcdhePublicKey p2;
  1663. struct GNUNET_HashCode hc1;
  1664. struct GNUNET_HashCode hc2;
  1665. GNUNET_CRYPTO_ecdhe_key_get_public (e1,
  1666. &p1);
  1667. GNUNET_CRYPTO_ecdhe_key_get_public (e2,
  1668. &p2);
  1669. GNUNET_assert (GNUNET_OK ==
  1670. GNUNET_CRYPTO_ecc_ecdh (e1,
  1671. &p2,
  1672. &hc1));
  1673. GNUNET_assert (GNUNET_OK ==
  1674. GNUNET_CRYPTO_ecc_ecdh (e2,
  1675. &p1,
  1676. &hc2));
  1677. GNUNET_break (0 == GNUNET_memcmp (&hc1,
  1678. &hc2));
  1679. }
  1680. static void
  1681. check_ed (const struct GNUNET_CRYPTO_EcdhePrivateKey *e1,
  1682. const struct GNUNET_CRYPTO_EddsaPrivateKey *e2)
  1683. {
  1684. struct GNUNET_CRYPTO_EcdhePublicKey p1;
  1685. struct GNUNET_CRYPTO_EddsaPublicKey p2;
  1686. struct GNUNET_HashCode hc1;
  1687. struct GNUNET_HashCode hc2;
  1688. GNUNET_CRYPTO_ecdhe_key_get_public (e1,
  1689. &p1);
  1690. GNUNET_CRYPTO_eddsa_key_get_public (e2,
  1691. &p2);
  1692. GNUNET_assert (GNUNET_OK ==
  1693. GNUNET_CRYPTO_ecdh_eddsa (e1,
  1694. &p2,
  1695. &hc1));
  1696. GNUNET_assert (GNUNET_OK ==
  1697. GNUNET_CRYPTO_eddsa_ecdh (e2,
  1698. &p1,
  1699. &hc2));
  1700. GNUNET_break (0 == GNUNET_memcmp (&hc1,
  1701. &hc2));
  1702. }
  1703. static void
  1704. test_crypto_bug (const struct GNUNET_CRYPTO_EcdhePrivateKey *e1,
  1705. const struct GNUNET_CRYPTO_EcdhePrivateKey *e2,
  1706. const struct GNUNET_CRYPTO_EddsaPrivateKey *d1,
  1707. const struct GNUNET_CRYPTO_EddsaPrivateKey *d2)
  1708. {
  1709. check_ee (e1, e2);
  1710. check_ed (e1, d2);
  1711. check_ed (e2, d1);
  1712. }
  1713. #endif
  1714. /**
  1715. * Handle KX_AUTH message.
  1716. *
  1717. * @param ct connection/tunnel combo that received encrypted message
  1718. * @param msg the key exchange message
  1719. */
  1720. void
  1721. GCT_handle_kx_auth (struct CadetTConnection *ct,
  1722. const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
  1723. {
  1724. struct CadetTunnel *t = ct->t;
  1725. struct CadetTunnelAxolotl ax_tmp;
  1726. struct GNUNET_HashCode kx_auth;
  1727. int ret;
  1728. GNUNET_STATISTICS_update (stats,
  1729. "# KX_AUTH received",
  1730. 1,
  1731. GNUNET_NO);
  1732. if ((CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
  1733. (CADET_TUNNEL_KEY_AX_RECV == t->estate))
  1734. {
  1735. /* Confusing, we got a KX_AUTH before we even send our own
  1736. KX. This should not happen. We'll send our own KX ASAP anyway,
  1737. so let's ignore this here. */
  1738. GNUNET_break_op (0);
  1739. return;
  1740. }
  1741. LOG (GNUNET_ERROR_TYPE_DEBUG,
  1742. "Handling KX_AUTH message from %s with ephemeral %s\n",
  1743. GCT_2s (t),
  1744. GNUNET_e2s (&msg->kx.ephemeral_key));
  1745. /* We do everything in ax_tmp until we've checked the authentication
  1746. so we don't clobber anything we care about by accident. */
  1747. ax_tmp = t->ax;
  1748. /* Update 'ax' by the new key material */
  1749. ret = update_ax_by_kx (&ax_tmp,
  1750. GCP_get_id (t->destination),
  1751. &msg->kx.ephemeral_key,
  1752. &msg->kx.ratchet_key);
  1753. if (GNUNET_OK != ret)
  1754. {
  1755. if (GNUNET_NO == ret)
  1756. GNUNET_STATISTICS_update (stats,
  1757. "# redundant KX_AUTH received",
  1758. 1,
  1759. GNUNET_NO);
  1760. else
  1761. GNUNET_break (0); /* connect to self!? */
  1762. return;
  1763. }
  1764. GNUNET_CRYPTO_hash (&ax_tmp.RK,
  1765. sizeof(ax_tmp.RK),
  1766. &kx_auth);
  1767. if (0 != GNUNET_memcmp (&kx_auth,
  1768. &msg->auth))
  1769. {
  1770. /* This KX_AUTH is not using the latest KX/KX_AUTH data
  1771. we transmitted to the sender, refuse it, try KX again. */
  1772. GNUNET_STATISTICS_update (stats,
  1773. "# KX_AUTH not using our last KX received (auth failure)",
  1774. 1,
  1775. GNUNET_NO);
  1776. LOG (GNUNET_ERROR_TYPE_WARNING,
  1777. "KX AUTH mismatch!\n");
  1778. #if DEBUG_KX
  1779. {
  1780. struct GNUNET_CRYPTO_EcdhePublicKey ephemeral_key;
  1781. GNUNET_CRYPTO_ecdhe_key_get_public (&ax_tmp.kx_0,
  1782. &ephemeral_key);
  1783. if (0 != GNUNET_memcmp (&ephemeral_key,
  1784. &msg->r_ephemeral_key_XXX))
  1785. {
  1786. LOG (GNUNET_ERROR_TYPE_WARNING,
  1787. "My ephemeral is %s!\n",
  1788. GNUNET_e2s (&ephemeral_key));
  1789. LOG (GNUNET_ERROR_TYPE_WARNING,
  1790. "Response is for ephemeral %s!\n",
  1791. GNUNET_e2s (&msg->r_ephemeral_key_XXX));
  1792. }
  1793. else
  1794. {
  1795. test_crypto_bug (&ax_tmp.kx_0,
  1796. &msg->kx.ephemeral_key_XXX,
  1797. my_private_key,
  1798. &msg->kx.private_key_XXX);
  1799. }
  1800. }
  1801. #endif
  1802. if (NULL == t->kx_task)
  1803. t->kx_task
  1804. = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
  1805. &retry_kx,
  1806. t);
  1807. return;
  1808. }
  1809. /* Yep, we're good. */
  1810. t->ax = ax_tmp;
  1811. if (NULL != t->unverified_ax)
  1812. {
  1813. /* We got some "stale" KX before, drop that. */
  1814. cleanup_ax (t->unverified_ax);
  1815. GNUNET_free (t->unverified_ax);
  1816. t->unverified_ax = NULL;
  1817. }
  1818. /* move ahead in our state machine */
  1819. switch (t->estate)
  1820. {
  1821. case CADET_TUNNEL_KEY_UNINITIALIZED:
  1822. case CADET_TUNNEL_KEY_AX_RECV:
  1823. /* Checked above, this is impossible. */
  1824. GNUNET_assert (0);
  1825. break;
  1826. case CADET_TUNNEL_KEY_AX_SENT: /* This is the normal case */
  1827. case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */
  1828. case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */
  1829. GCT_change_estate (t,
  1830. CADET_TUNNEL_KEY_OK);
  1831. break;
  1832. case CADET_TUNNEL_KEY_OK:
  1833. /* Did not expect another KX_AUTH, but so what, still acceptable.
  1834. Nothing to do here. */
  1835. break;
  1836. }
  1837. if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->kx.flags)))
  1838. {
  1839. send_kx_auth (t,
  1840. NULL,
  1841. &t->ax,
  1842. GNUNET_NO);
  1843. }
  1844. }
  1845. /* ************************************** end core crypto ***************************** */
  1846. /**
  1847. * Compute the next free channel tunnel number for this tunnel.
  1848. *
  1849. * @param t the tunnel
  1850. * @return unused number that can uniquely identify a channel in the tunnel
  1851. */
  1852. static struct GNUNET_CADET_ChannelTunnelNumber
  1853. get_next_free_ctn (struct CadetTunnel *t)
  1854. {
  1855. #define HIGH_BIT 0x8000000
  1856. struct GNUNET_CADET_ChannelTunnelNumber ret;
  1857. uint32_t ctn;
  1858. int cmp;
  1859. uint32_t highbit;
  1860. cmp = GNUNET_memcmp (&my_full_id,
  1861. GCP_get_id (GCT_get_destination (t)));
  1862. if (0 < cmp)
  1863. highbit = HIGH_BIT;
  1864. else if (0 > cmp)
  1865. highbit = 0;
  1866. else
  1867. GNUNET_assert (0); // loopback must never go here!
  1868. ctn = ntohl (t->next_ctn.cn);
  1869. while (NULL !=
  1870. GNUNET_CONTAINER_multihashmap32_get (t->channels,
  1871. ctn | highbit))
  1872. {
  1873. ctn = ((ctn + 1) & (~HIGH_BIT));
  1874. }
  1875. t->next_ctn.cn = htonl ((ctn + 1) & (~HIGH_BIT));
  1876. ret.cn = htonl (ctn | highbit);
  1877. return ret;
  1878. }
  1879. /**
  1880. * Add a channel to a tunnel, and notify channel that we are ready
  1881. * for transmission if we are already up. Otherwise that notification
  1882. * will be done later in #notify_tunnel_up_cb().
  1883. *
  1884. * @param t Tunnel.
  1885. * @param ch Channel
  1886. * @return unique number identifying @a ch within @a t
  1887. */
  1888. struct GNUNET_CADET_ChannelTunnelNumber
  1889. GCT_add_channel (struct CadetTunnel *t,
  1890. struct CadetChannel *ch)
  1891. {
  1892. struct GNUNET_CADET_ChannelTunnelNumber ctn;
  1893. ctn = get_next_free_ctn (t);
  1894. if (NULL != t->destroy_task)
  1895. {
  1896. GNUNET_SCHEDULER_cancel (t->destroy_task);
  1897. t->destroy_task = NULL;
  1898. }
  1899. GNUNET_assert (GNUNET_YES ==
  1900. GNUNET_CONTAINER_multihashmap32_put (t->channels,
  1901. ntohl (ctn.cn),
  1902. ch,
  1903. GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  1904. LOG (GNUNET_ERROR_TYPE_DEBUG,
  1905. "Adding %s to %s\n",
  1906. GCCH_2s (ch),
  1907. GCT_2s (t));
  1908. switch (t->estate)
  1909. {
  1910. case CADET_TUNNEL_KEY_UNINITIALIZED:
  1911. /* waiting for connection to start KX */
  1912. break;
  1913. case CADET_TUNNEL_KEY_AX_RECV:
  1914. case CADET_TUNNEL_KEY_AX_SENT:
  1915. case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
  1916. /* we're currently waiting for KX to complete */
  1917. break;
  1918. case CADET_TUNNEL_KEY_AX_AUTH_SENT:
  1919. /* waiting for OTHER peer to send us data,
  1920. we might need to prompt more aggressively! */
  1921. if (NULL == t->kx_task)
  1922. t->kx_task
  1923. = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
  1924. &retry_kx,
  1925. t);
  1926. break;
  1927. case CADET_TUNNEL_KEY_OK:
  1928. /* We are ready. Tell the new channel that we are up. */
  1929. GCCH_tunnel_up (ch);
  1930. break;
  1931. }
  1932. return ctn;
  1933. }
  1934. /**
  1935. * We lost a connection, remove it from our list and clean up
  1936. * the connection object itself.
  1937. *
  1938. * @param ct binding of connection to tunnel of the connection that was lost.
  1939. */
  1940. void
  1941. GCT_connection_lost (struct CadetTConnection *ct)
  1942. {
  1943. struct CadetTunnel *t = ct->t;
  1944. if (GNUNET_YES == ct->is_ready)
  1945. {
  1946. GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
  1947. t->connection_ready_tail,
  1948. ct);
  1949. t->num_ready_connections--;
  1950. }
  1951. else
  1952. {
  1953. GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
  1954. t->connection_busy_tail,
  1955. ct);
  1956. t->num_busy_connections--;
  1957. }
  1958. GNUNET_free (ct);
  1959. }
  1960. /**
  1961. * Clean up connection @a ct of a tunnel.
  1962. *
  1963. * @param cls the `struct CadetTunnel`
  1964. * @param ct connection to clean up
  1965. */
  1966. static void
  1967. destroy_t_connection (void *cls,
  1968. struct CadetTConnection *ct)
  1969. {
  1970. struct CadetTunnel *t = cls;
  1971. struct CadetConnection *cc = ct->cc;
  1972. GNUNET_assert (ct->t == t);
  1973. GCT_connection_lost (ct);
  1974. GCC_destroy_without_tunnel (cc);
  1975. }
  1976. /**
  1977. * This tunnel is no longer used, destroy it.
  1978. *
  1979. * @param cls the idle tunnel
  1980. */
  1981. static void
  1982. destroy_tunnel (void *cls)
  1983. {
  1984. struct CadetTunnel *t = cls;
  1985. struct CadetTunnelQueueEntry *tq;
  1986. t->destroy_task = NULL;
  1987. LOG (GNUNET_ERROR_TYPE_DEBUG,
  1988. "Destroying idle %s\n",
  1989. GCT_2s (t));
  1990. GNUNET_assert (0 == GCT_count_channels (t));
  1991. GCT_iterate_connections (t,
  1992. &destroy_t_connection,
  1993. t);
  1994. GNUNET_assert (NULL == t->connection_ready_head);
  1995. GNUNET_assert (NULL == t->connection_busy_head);
  1996. while (NULL != (tq = t->tq_head))
  1997. {
  1998. if (NULL != tq->cont)
  1999. tq->cont (tq->cont_cls,
  2000. NULL);
  2001. GCT_send_cancel (tq);
  2002. }
  2003. GCP_drop_tunnel (t->destination,
  2004. t);
  2005. GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
  2006. if (NULL != t->maintain_connections_task)
  2007. {
  2008. GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
  2009. t->maintain_connections_task = NULL;
  2010. }
  2011. if (NULL != t->send_task)
  2012. {
  2013. GNUNET_SCHEDULER_cancel (t->send_task);
  2014. t->send_task = NULL;
  2015. }
  2016. if (NULL != t->kx_task)
  2017. {
  2018. GNUNET_SCHEDULER_cancel (t->kx_task);
  2019. t->kx_task = NULL;
  2020. }
  2021. GNUNET_MST_destroy (t->mst);
  2022. GNUNET_MQ_destroy (t->mq);
  2023. if (NULL != t->unverified_ax)
  2024. {
  2025. cleanup_ax (t->unverified_ax);
  2026. GNUNET_free (t->unverified_ax);
  2027. }
  2028. cleanup_ax (&t->ax);
  2029. GNUNET_assert (NULL == t->destroy_task);
  2030. GNUNET_free (t);
  2031. }
  2032. /**
  2033. * Remove a channel from a tunnel.
  2034. *
  2035. * @param t Tunnel.
  2036. * @param ch Channel
  2037. * @param ctn unique number identifying @a ch within @a t
  2038. */
  2039. void
  2040. GCT_remove_channel (struct CadetTunnel *t,
  2041. struct CadetChannel *ch,
  2042. struct GNUNET_CADET_ChannelTunnelNumber ctn)
  2043. {
  2044. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2045. "Removing %s from %s\n",
  2046. GCCH_2s (ch),
  2047. GCT_2s (t));
  2048. GNUNET_assert (GNUNET_YES ==
  2049. GNUNET_CONTAINER_multihashmap32_remove (t->channels,
  2050. ntohl (ctn.cn),
  2051. ch));
  2052. if ((0 ==
  2053. GCT_count_channels (t)) &&
  2054. (NULL == t->destroy_task))
  2055. {
  2056. t->destroy_task
  2057. = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
  2058. &destroy_tunnel,
  2059. t);
  2060. }
  2061. }
  2062. /**
  2063. * Destroy remaining channels during shutdown.
  2064. *
  2065. * @param cls the `struct CadetTunnel` of the channel
  2066. * @param key key of the channel
  2067. * @param value the `struct CadetChannel`
  2068. * @return #GNUNET_OK (continue to iterate)
  2069. */
  2070. static int
  2071. destroy_remaining_channels (void *cls,
  2072. uint32_t key,
  2073. void *value)
  2074. {
  2075. struct CadetChannel *ch = value;
  2076. GCCH_handle_remote_destroy (ch,
  2077. NULL);
  2078. return GNUNET_OK;
  2079. }
  2080. /**
  2081. * Destroys the tunnel @a t now, without delay. Used during shutdown.
  2082. *
  2083. * @param t tunnel to destroy
  2084. */
  2085. void
  2086. GCT_destroy_tunnel_now (struct CadetTunnel *t)
  2087. {
  2088. GNUNET_assert (GNUNET_YES == shutting_down);
  2089. GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
  2090. &destroy_remaining_channels,
  2091. t);
  2092. GNUNET_assert (0 ==
  2093. GCT_count_channels (t));
  2094. if (NULL != t->destroy_task)
  2095. {
  2096. GNUNET_SCHEDULER_cancel (t->destroy_task);
  2097. t->destroy_task = NULL;
  2098. }
  2099. destroy_tunnel (t);
  2100. }
  2101. /**
  2102. * Send normal payload from queue in @a t via connection @a ct.
  2103. * Does nothing if our payload queue is empty.
  2104. *
  2105. * @param t tunnel to send data from
  2106. * @param ct connection to use for transmission (is ready)
  2107. */
  2108. static void
  2109. try_send_normal_payload (struct CadetTunnel *t,
  2110. struct CadetTConnection *ct)
  2111. {
  2112. struct CadetTunnelQueueEntry *tq;
  2113. GNUNET_assert (GNUNET_YES == ct->is_ready);
  2114. tq = t->tq_head;
  2115. if (NULL == tq)
  2116. {
  2117. /* no messages pending right now */
  2118. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2119. "Not sending payload of %s on ready %s (nothing pending)\n",
  2120. GCT_2s (t),
  2121. GCC_2s (ct->cc));
  2122. return;
  2123. }
  2124. /* ready to send message 'tq' on tunnel 'ct' */
  2125. GNUNET_assert (t == tq->t);
  2126. GNUNET_CONTAINER_DLL_remove (t->tq_head,
  2127. t->tq_tail,
  2128. tq);
  2129. if (NULL != tq->cid)
  2130. *tq->cid = *GCC_get_id (ct->cc);
  2131. mark_connection_unready (ct);
  2132. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2133. "Sending payload of %s on %s\n",
  2134. GCT_2s (t),
  2135. GCC_2s (ct->cc));
  2136. GCC_transmit (ct->cc,
  2137. tq->env);
  2138. if (NULL != tq->cont)
  2139. tq->cont (tq->cont_cls,
  2140. GCC_get_id (ct->cc));
  2141. GNUNET_free (tq);
  2142. }
  2143. /**
  2144. * A connection is @a is_ready for transmission. Looks at our message
  2145. * queue and if there is a message, sends it out via the connection.
  2146. *
  2147. * @param cls the `struct CadetTConnection` that is @a is_ready
  2148. * @param is_ready #GNUNET_YES if connection are now ready,
  2149. * #GNUNET_NO if connection are no longer ready
  2150. */
  2151. static void
  2152. connection_ready_cb (void *cls,
  2153. int is_ready)
  2154. {
  2155. struct CadetTConnection *ct = cls;
  2156. struct CadetTunnel *t = ct->t;
  2157. if (GNUNET_NO == is_ready)
  2158. {
  2159. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2160. "%s no longer ready for %s\n",
  2161. GCC_2s (ct->cc),
  2162. GCT_2s (t));
  2163. mark_connection_unready (ct);
  2164. return;
  2165. }
  2166. GNUNET_assert (GNUNET_NO == ct->is_ready);
  2167. GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
  2168. t->connection_busy_tail,
  2169. ct);
  2170. GNUNET_assert (0 < t->num_busy_connections);
  2171. t->num_busy_connections--;
  2172. ct->is_ready = GNUNET_YES;
  2173. GNUNET_CONTAINER_DLL_insert_tail (t->connection_ready_head,
  2174. t->connection_ready_tail,
  2175. ct);
  2176. t->num_ready_connections++;
  2177. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2178. "%s now ready for %s in state %s\n",
  2179. GCC_2s (ct->cc),
  2180. GCT_2s (t),
  2181. estate2s (t->estate));
  2182. switch (t->estate)
  2183. {
  2184. case CADET_TUNNEL_KEY_UNINITIALIZED:
  2185. /* Do not begin KX if WE have no channels waiting! */
  2186. if (0 != GNUNET_TIME_absolute_get_remaining (
  2187. t->next_kx_attempt).rel_value_us)
  2188. return; /* wait for timeout before retrying */
  2189. /* We are uninitialized, just transmit immediately,
  2190. without undue delay. */
  2191. if (NULL != t->kx_task)
  2192. {
  2193. GNUNET_SCHEDULER_cancel (t->kx_task);
  2194. t->kx_task = NULL;
  2195. }
  2196. send_kx (t,
  2197. ct,
  2198. &t->ax);
  2199. if ((0 ==
  2200. GCT_count_channels (t)) &&
  2201. (NULL == t->destroy_task))
  2202. {
  2203. t->destroy_task
  2204. = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
  2205. &destroy_tunnel,
  2206. t);
  2207. }
  2208. break;
  2209. case CADET_TUNNEL_KEY_AX_RECV:
  2210. case CADET_TUNNEL_KEY_AX_SENT:
  2211. case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
  2212. case CADET_TUNNEL_KEY_AX_AUTH_SENT:
  2213. /* we're currently waiting for KX to complete, schedule job */
  2214. if (NULL == t->kx_task)
  2215. t->kx_task
  2216. = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
  2217. &retry_kx,
  2218. t);
  2219. break;
  2220. case CADET_TUNNEL_KEY_OK:
  2221. if (GNUNET_YES == t->kx_auth_requested)
  2222. {
  2223. if (0 != GNUNET_TIME_absolute_get_remaining (
  2224. t->next_kx_attempt).rel_value_us)
  2225. return; /* wait for timeout */
  2226. if (NULL != t->kx_task)
  2227. {
  2228. GNUNET_SCHEDULER_cancel (t->kx_task);
  2229. t->kx_task = NULL;
  2230. }
  2231. send_kx_auth (t,
  2232. ct,
  2233. &t->ax,
  2234. GNUNET_NO);
  2235. return;
  2236. }
  2237. try_send_normal_payload (t,
  2238. ct);
  2239. break;
  2240. }
  2241. }
  2242. /**
  2243. * Called when either we have a new connection, or a new message in the
  2244. * queue, or some existing connection has transmission capacity. Looks
  2245. * at our message queue and if there is a message, picks a connection
  2246. * to send it on.
  2247. *
  2248. * @param cls the `struct CadetTunnel` to process messages on
  2249. */
  2250. static void
  2251. trigger_transmissions (void *cls)
  2252. {
  2253. struct CadetTunnel *t = cls;
  2254. struct CadetTConnection *ct;
  2255. t->send_task = NULL;
  2256. if (NULL == t->tq_head)
  2257. return; /* no messages pending right now */
  2258. ct = get_ready_connection (t);
  2259. if (NULL == ct)
  2260. return; /* no connections ready */
  2261. try_send_normal_payload (t,
  2262. ct);
  2263. }
  2264. /**
  2265. * Closure for #evaluate_connection. Used to assemble summary information
  2266. * about the existing connections so we can evaluate a new path.
  2267. */
  2268. struct EvaluationSummary
  2269. {
  2270. /**
  2271. * Minimum length of any of our connections, `UINT_MAX` if we have none.
  2272. */
  2273. unsigned int min_length;
  2274. /**
  2275. * Maximum length of any of our connections, 0 if we have none.
  2276. */
  2277. unsigned int max_length;
  2278. /**
  2279. * Minimum desirability of any of our connections, UINT64_MAX if we have none.
  2280. */
  2281. GNUNET_CONTAINER_HeapCostType min_desire;
  2282. /**
  2283. * Maximum desirability of any of our connections, 0 if we have none.
  2284. */
  2285. GNUNET_CONTAINER_HeapCostType max_desire;
  2286. /**
  2287. * Path we are comparing against for #evaluate_connection, can be NULL.
  2288. */
  2289. struct CadetPeerPath *path;
  2290. /**
  2291. * Connection deemed the "worst" so far encountered by #evaluate_connection,
  2292. * NULL if we did not yet encounter any connections.
  2293. */
  2294. struct CadetTConnection *worst;
  2295. /**
  2296. * Numeric score of @e worst, only set if @e worst is non-NULL.
  2297. */
  2298. double worst_score;
  2299. /**
  2300. * Set to #GNUNET_YES if we have a connection over @e path already.
  2301. */
  2302. int duplicate;
  2303. };
  2304. /**
  2305. * Evaluate a connection, updating our summary information in @a cls about
  2306. * what kinds of connections we have.
  2307. *
  2308. * @param cls the `struct EvaluationSummary *` to update
  2309. * @param ct a connection to include in the summary
  2310. */
  2311. static void
  2312. evaluate_connection (void *cls,
  2313. struct CadetTConnection *ct)
  2314. {
  2315. struct EvaluationSummary *es = cls;
  2316. struct CadetConnection *cc = ct->cc;
  2317. unsigned int ct_length;
  2318. struct CadetPeerPath *ps;
  2319. const struct CadetConnectionMetrics *metrics;
  2320. GNUNET_CONTAINER_HeapCostType ct_desirability;
  2321. struct GNUNET_TIME_Relative uptime;
  2322. struct GNUNET_TIME_Relative last_use;
  2323. double score;
  2324. double success_rate;
  2325. ps = GCC_get_path (cc,
  2326. &ct_length);
  2327. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2328. "Evaluating path %s of existing %s\n",
  2329. GCPP_2s (ps),
  2330. GCC_2s (cc));
  2331. if (ps == es->path)
  2332. {
  2333. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2334. "Ignoring duplicate path %s.\n",
  2335. GCPP_2s (es->path));
  2336. es->duplicate = GNUNET_YES;
  2337. return;
  2338. }
  2339. if (NULL != es->path)
  2340. {
  2341. int duplicate = GNUNET_YES;
  2342. for (unsigned int i = 0; i < ct_length; i++)
  2343. {
  2344. GNUNET_assert (GCPP_get_length (es->path) > i);
  2345. if (GCPP_get_peer_at_offset (es->path,
  2346. i) !=
  2347. GCPP_get_peer_at_offset (ps,
  2348. i))
  2349. {
  2350. duplicate = GNUNET_NO;
  2351. break;
  2352. }
  2353. }
  2354. if (GNUNET_YES == duplicate)
  2355. {
  2356. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2357. "Ignoring overlapping path %s.\n",
  2358. GCPP_2s (es->path));
  2359. es->duplicate = GNUNET_YES;
  2360. return;
  2361. }
  2362. else
  2363. {
  2364. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2365. "Known path %s differs from proposed path\n",
  2366. GCPP_2s (ps));
  2367. }
  2368. }
  2369. ct_desirability = GCPP_get_desirability (ps);
  2370. metrics = GCC_get_metrics (cc);
  2371. uptime = GNUNET_TIME_absolute_get_duration (metrics->age);
  2372. last_use = GNUNET_TIME_absolute_get_duration (metrics->last_use);
  2373. /* We add 1.0 here to avoid division by zero. */
  2374. success_rate = (metrics->num_acked_transmissions + 1.0)
  2375. / (metrics->num_successes + 1.0);
  2376. score
  2377. = ct_desirability
  2378. + 100.0 / (1.0 + ct_length) /* longer paths = better */
  2379. + sqrt (uptime.rel_value_us / 60000000LL) /* larger uptime = better */
  2380. - last_use.rel_value_us / 1000L; /* longer idle = worse */
  2381. score *= success_rate; /* weigh overall by success rate */
  2382. if ((NULL == es->worst) ||
  2383. (score < es->worst_score))
  2384. {
  2385. es->worst = ct;
  2386. es->worst_score = score;
  2387. }
  2388. es->min_length = GNUNET_MIN (es->min_length,
  2389. ct_length);
  2390. es->max_length = GNUNET_MAX (es->max_length,
  2391. ct_length);
  2392. es->min_desire = GNUNET_MIN (es->min_desire,
  2393. ct_desirability);
  2394. es->max_desire = GNUNET_MAX (es->max_desire,
  2395. ct_desirability);
  2396. }
  2397. /**
  2398. * Consider using the path @a p for the tunnel @a t.
  2399. * The tunnel destination is at offset @a off in path @a p.
  2400. *
  2401. * @param cls our tunnel
  2402. * @param path a path to our destination
  2403. * @param off offset of the destination on path @a path
  2404. * @return #GNUNET_YES (should keep iterating)
  2405. */
  2406. static int
  2407. consider_path_cb (void *cls,
  2408. struct CadetPeerPath *path,
  2409. unsigned int off)
  2410. {
  2411. struct CadetTunnel *t = cls;
  2412. struct EvaluationSummary es;
  2413. struct CadetTConnection *ct;
  2414. GNUNET_assert (off < GCPP_get_length (path));
  2415. GNUNET_assert (GCPP_get_peer_at_offset (path,
  2416. off) == t->destination);
  2417. es.min_length = UINT_MAX;
  2418. es.max_length = 0;
  2419. es.max_desire = 0;
  2420. es.min_desire = UINT64_MAX;
  2421. es.path = path;
  2422. es.duplicate = GNUNET_NO;
  2423. es.worst = NULL;
  2424. /* Compute evaluation summary over existing connections. */
  2425. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2426. "Evaluating proposed path %s for target %s\n",
  2427. GCPP_2s (path),
  2428. GCT_2s (t));
  2429. /* FIXME: suspect this does not ACTUALLY iterate
  2430. over all existing paths, otherwise dup detection
  2431. should work!!! */
  2432. GCT_iterate_connections (t,
  2433. &evaluate_connection,
  2434. &es);
  2435. if (GNUNET_YES == es.duplicate)
  2436. return GNUNET_YES;
  2437. /* FIXME: not sure we should really just count
  2438. 'num_connections' here, as they may all have
  2439. consistently failed to connect. */
  2440. /* We iterate by increasing path length; if we have enough paths and
  2441. this one is more than twice as long than what we are currently
  2442. using, then ignore all of these super-long ones! */
  2443. if ((GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) &&
  2444. (es.min_length * 2 < off) &&
  2445. (es.max_length < off))
  2446. {
  2447. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2448. "Ignoring paths of length %u, they are way too long.\n",
  2449. es.min_length * 2);
  2450. return GNUNET_NO;
  2451. }
  2452. /* If we have enough paths and this one looks no better, ignore it. */
  2453. if ((GCT_count_any_connections (t) >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
  2454. (es.min_length < GCPP_get_length (path)) &&
  2455. (es.min_desire > GCPP_get_desirability (path)) &&
  2456. (es.max_length < off))
  2457. {
  2458. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2459. "Ignoring path (%u/%llu) to %s, got something better already.\n",
  2460. GCPP_get_length (path),
  2461. (unsigned long long) GCPP_get_desirability (path),
  2462. GCP_2s (t->destination));
  2463. return GNUNET_YES;
  2464. }
  2465. /* Path is interesting (better by some metric, or we don't have
  2466. enough paths yet). */
  2467. ct = GNUNET_new (struct CadetTConnection);
  2468. ct->created = GNUNET_TIME_absolute_get ();
  2469. ct->t = t;
  2470. ct->cc = GCC_create (t->destination,
  2471. path,
  2472. off,
  2473. ct,
  2474. &connection_ready_cb,
  2475. ct);
  2476. /* FIXME: schedule job to kill connection (and path?) if it takes
  2477. too long to get ready! (And track performance data on how long
  2478. other connections took with the tunnel!)
  2479. => Note: to be done within 'connection'-logic! */
  2480. GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
  2481. t->connection_busy_tail,
  2482. ct);
  2483. t->num_busy_connections++;
  2484. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2485. "Found interesting path %s for %s, created %s\n",
  2486. GCPP_2s (path),
  2487. GCT_2s (t),
  2488. GCC_2s (ct->cc));
  2489. return GNUNET_YES;
  2490. }
  2491. /**
  2492. * Function called to maintain the connections underlying our tunnel.
  2493. * Tries to maintain (incl. tear down) connections for the tunnel, and
  2494. * if there is a significant change, may trigger transmissions.
  2495. *
  2496. * Basically, needs to check if there are connections that perform
  2497. * badly, and if so eventually kill them and trigger a replacement.
  2498. * The strategy is to open one more connection than
  2499. * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
  2500. * least-performing one, and then inquire for new ones.
  2501. *
  2502. * @param cls the `struct CadetTunnel`
  2503. */
  2504. static void
  2505. maintain_connections_cb (void *cls)
  2506. {
  2507. struct CadetTunnel *t = cls;
  2508. struct GNUNET_TIME_Relative delay;
  2509. struct EvaluationSummary es;
  2510. t->maintain_connections_task = NULL;
  2511. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2512. "Performing connection maintenance for %s.\n",
  2513. GCT_2s (t));
  2514. es.min_length = UINT_MAX;
  2515. es.max_length = 0;
  2516. es.max_desire = 0;
  2517. es.min_desire = UINT64_MAX;
  2518. es.path = NULL;
  2519. es.worst = NULL;
  2520. es.duplicate = GNUNET_NO;
  2521. GCT_iterate_connections (t,
  2522. &evaluate_connection,
  2523. &es);
  2524. if ((NULL != es.worst) &&
  2525. (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL))
  2526. {
  2527. /* Clear out worst-performing connection 'es.worst'. */
  2528. destroy_t_connection (t,
  2529. es.worst);
  2530. }
  2531. /* Consider additional paths */
  2532. (void) GCP_iterate_paths (t->destination,
  2533. &consider_path_cb,
  2534. t);
  2535. /* FIXME: calculate when to try again based on how well we are doing;
  2536. in particular, if we have to few connections, we might be able
  2537. to do without this (as PATHS should tell us whenever a new path
  2538. is available instantly; however, need to make sure this job is
  2539. restarted after that happens).
  2540. Furthermore, if the paths we do know are in a reasonably narrow
  2541. quality band and are plentyful, we might also consider us stabilized
  2542. and then reduce the frequency accordingly. */delay = GNUNET_TIME_UNIT_MINUTES;
  2543. t->maintain_connections_task
  2544. = GNUNET_SCHEDULER_add_delayed (delay,
  2545. &maintain_connections_cb,
  2546. t);
  2547. }
  2548. /**
  2549. * Consider using the path @a p for the tunnel @a t.
  2550. * The tunnel destination is at offset @a off in path @a p.
  2551. *
  2552. * @param cls our tunnel
  2553. * @param path a path to our destination
  2554. * @param off offset of the destination on path @a path
  2555. */
  2556. void
  2557. GCT_consider_path (struct CadetTunnel *t,
  2558. struct CadetPeerPath *p,
  2559. unsigned int off)
  2560. {
  2561. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2562. "Considering %s for %s (offset %u)\n",
  2563. GCPP_2s (p),
  2564. GCT_2s (t),
  2565. off);
  2566. (void) consider_path_cb (t,
  2567. p,
  2568. off);
  2569. }
  2570. /**
  2571. * We got a keepalive. Track in statistics.
  2572. *
  2573. * @param cls the `struct CadetTunnel` for which we decrypted the message
  2574. * @param msg the message we received on the tunnel
  2575. */
  2576. static void
  2577. handle_plaintext_keepalive (void *cls,
  2578. const struct GNUNET_MessageHeader *msg)
  2579. {
  2580. struct CadetTunnel *t = cls;
  2581. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2582. "Received KEEPALIVE on %s\n",
  2583. GCT_2s (t));
  2584. GNUNET_STATISTICS_update (stats,
  2585. "# keepalives received",
  2586. 1,
  2587. GNUNET_NO);
  2588. }
  2589. /**
  2590. * Check that @a msg is well-formed.
  2591. *
  2592. * @param cls the `struct CadetTunnel` for which we decrypted the message
  2593. * @param msg the message we received on the tunnel
  2594. * @return #GNUNET_OK (any variable-size payload goes)
  2595. */
  2596. static int
  2597. check_plaintext_data (void *cls,
  2598. const struct GNUNET_CADET_ChannelAppDataMessage *msg)
  2599. {
  2600. return GNUNET_OK;
  2601. }
  2602. /**
  2603. * We received payload data for a channel. Locate the channel
  2604. * and process the data, or return an error if the channel is unknown.
  2605. *
  2606. * @param cls the `struct CadetTunnel` for which we decrypted the message
  2607. * @param msg the message we received on the tunnel
  2608. */
  2609. static void
  2610. handle_plaintext_data (void *cls,
  2611. const struct GNUNET_CADET_ChannelAppDataMessage *msg)
  2612. {
  2613. struct CadetTunnel *t = cls;
  2614. struct CadetChannel *ch;
  2615. ch = lookup_channel (t,
  2616. msg->ctn);
  2617. if (NULL == ch)
  2618. {
  2619. /* We don't know about such a channel, might have been destroyed on our
  2620. end in the meantime, or never existed. Send back a DESTROY. */
  2621. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2622. "Received %u bytes of application data for unknown channel %u, sending DESTROY\n",
  2623. (unsigned int) (ntohs (msg->header.size) - sizeof(*msg)),
  2624. ntohl (msg->ctn.cn));
  2625. GCT_send_channel_destroy (t,
  2626. msg->ctn);
  2627. return;
  2628. }
  2629. GCCH_handle_channel_plaintext_data (ch,
  2630. GCC_get_id (t->current_ct->cc),
  2631. msg);
  2632. }
  2633. /**
  2634. * We received an acknowledgement for data we sent on a channel.
  2635. * Locate the channel and process it, or return an error if the
  2636. * channel is unknown.
  2637. *
  2638. * @param cls the `struct CadetTunnel` for which we decrypted the message
  2639. * @param ack the message we received on the tunnel
  2640. */
  2641. static void
  2642. handle_plaintext_data_ack (void *cls,
  2643. const struct GNUNET_CADET_ChannelDataAckMessage *ack)
  2644. {
  2645. struct CadetTunnel *t = cls;
  2646. struct CadetChannel *ch;
  2647. ch = lookup_channel (t,
  2648. ack->ctn);
  2649. if (NULL == ch)
  2650. {
  2651. /* We don't know about such a channel, might have been destroyed on our
  2652. end in the meantime, or never existed. Send back a DESTROY. */
  2653. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2654. "Received DATA_ACK for unknown channel %u, sending DESTROY\n",
  2655. ntohl (ack->ctn.cn));
  2656. GCT_send_channel_destroy (t,
  2657. ack->ctn);
  2658. return;
  2659. }
  2660. GCCH_handle_channel_plaintext_data_ack (ch,
  2661. GCC_get_id (t->current_ct->cc),
  2662. ack);
  2663. }
  2664. /**
  2665. * We have received a request to open a channel to a port from
  2666. * another peer. Creates the incoming channel.
  2667. *
  2668. * @param cls the `struct CadetTunnel` for which we decrypted the message
  2669. * @param copen the message we received on the tunnel
  2670. */
  2671. static void
  2672. handle_plaintext_channel_open (void *cls,
  2673. const struct
  2674. GNUNET_CADET_ChannelOpenMessage *copen)
  2675. {
  2676. struct CadetTunnel *t = cls;
  2677. struct CadetChannel *ch;
  2678. ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
  2679. ntohl (copen->ctn.cn));
  2680. if (NULL != ch)
  2681. {
  2682. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2683. "Received duplicate channel CHANNEL_OPEN on h_port %s from %s (%s), resending ACK\n",
  2684. GNUNET_h2s (&copen->h_port),
  2685. GCT_2s (t),
  2686. GCCH_2s (ch));
  2687. GCCH_handle_duplicate_open (ch,
  2688. GCC_get_id (t->current_ct->cc));
  2689. return;
  2690. }
  2691. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2692. "Received CHANNEL_OPEN on h_port %s from %s\n",
  2693. GNUNET_h2s (&copen->h_port),
  2694. GCT_2s (t));
  2695. ch = GCCH_channel_incoming_new (t,
  2696. copen->ctn,
  2697. &copen->h_port,
  2698. ntohl (copen->opt));
  2699. if (NULL != t->destroy_task)
  2700. {
  2701. GNUNET_SCHEDULER_cancel (t->destroy_task);
  2702. t->destroy_task = NULL;
  2703. }
  2704. GNUNET_assert (GNUNET_OK ==
  2705. GNUNET_CONTAINER_multihashmap32_put (t->channels,
  2706. ntohl (copen->ctn.cn),
  2707. ch,
  2708. GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  2709. }
  2710. /**
  2711. * Send a DESTROY message via the tunnel.
  2712. *
  2713. * @param t the tunnel to transmit over
  2714. * @param ctn ID of the channel to destroy
  2715. */
  2716. void
  2717. GCT_send_channel_destroy (struct CadetTunnel *t,
  2718. struct GNUNET_CADET_ChannelTunnelNumber ctn)
  2719. {
  2720. struct GNUNET_CADET_ChannelDestroyMessage msg;
  2721. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2722. "Sending DESTORY message for channel ID %u\n",
  2723. ntohl (ctn.cn));
  2724. msg.header.size = htons (sizeof(msg));
  2725. msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
  2726. msg.reserved = htonl (0);
  2727. msg.ctn = ctn;
  2728. GCT_send (t,
  2729. &msg.header,
  2730. NULL,
  2731. NULL);
  2732. }
  2733. /**
  2734. * We have received confirmation from the target peer that the
  2735. * given channel could be established (the port is open).
  2736. * Tell the client.
  2737. *
  2738. * @param cls the `struct CadetTunnel` for which we decrypted the message
  2739. * @param cm the message we received on the tunnel
  2740. */
  2741. static void
  2742. handle_plaintext_channel_open_ack (void *cls,
  2743. const struct
  2744. GNUNET_CADET_ChannelOpenAckMessage *cm)
  2745. {
  2746. struct CadetTunnel *t = cls;
  2747. struct CadetChannel *ch;
  2748. ch = lookup_channel (t,
  2749. cm->ctn);
  2750. if (NULL == ch)
  2751. {
  2752. /* We don't know about such a channel, might have been destroyed on our
  2753. end in the meantime, or never existed. Send back a DESTROY. */
  2754. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2755. "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
  2756. ntohl (cm->ctn.cn));
  2757. GCT_send_channel_destroy (t,
  2758. cm->ctn);
  2759. return;
  2760. }
  2761. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2762. "Received channel OPEN_ACK on channel %s from %s\n",
  2763. GCCH_2s (ch),
  2764. GCT_2s (t));
  2765. GCCH_handle_channel_open_ack (ch,
  2766. GCC_get_id (t->current_ct->cc),
  2767. &cm->port);
  2768. }
  2769. /**
  2770. * We received a message saying that a channel should be destroyed.
  2771. * Pass it on to the correct channel.
  2772. *
  2773. * @param cls the `struct CadetTunnel` for which we decrypted the message
  2774. * @param cm the message we received on the tunnel
  2775. */
  2776. static void
  2777. handle_plaintext_channel_destroy (void *cls,
  2778. const struct
  2779. GNUNET_CADET_ChannelDestroyMessage *cm)
  2780. {
  2781. struct CadetTunnel *t = cls;
  2782. struct CadetChannel *ch;
  2783. ch = lookup_channel (t,
  2784. cm->ctn);
  2785. if (NULL == ch)
  2786. {
  2787. /* We don't know about such a channel, might have been destroyed on our
  2788. end in the meantime, or never existed. */
  2789. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2790. "Received channel DESTORY for unknown channel %u. Ignoring.\n",
  2791. ntohl (cm->ctn.cn));
  2792. return;
  2793. }
  2794. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2795. "Received channel DESTROY on %s from %s\n",
  2796. GCCH_2s (ch),
  2797. GCT_2s (t));
  2798. GCCH_handle_remote_destroy (ch,
  2799. GCC_get_id (t->current_ct->cc));
  2800. }
  2801. /**
  2802. * Handles a message we decrypted, by injecting it into
  2803. * our message queue (which will do the dispatching).
  2804. *
  2805. * @param cls the `struct CadetTunnel` that got the message
  2806. * @param msg the message
  2807. * @return #GNUNET_OK on success (always)
  2808. * #GNUNET_NO to stop further processing (no error)
  2809. * #GNUNET_SYSERR to stop further processing with error
  2810. */
  2811. static int
  2812. handle_decrypted (void *cls,
  2813. const struct GNUNET_MessageHeader *msg)
  2814. {
  2815. struct CadetTunnel *t = cls;
  2816. GNUNET_assert (NULL != t->current_ct);
  2817. GNUNET_MQ_inject_message (t->mq,
  2818. msg);
  2819. return GNUNET_OK;
  2820. }
  2821. /**
  2822. * Function called if we had an error processing
  2823. * an incoming decrypted message.
  2824. *
  2825. * @param cls the `struct CadetTunnel`
  2826. * @param error error code
  2827. */
  2828. static void
  2829. decrypted_error_cb (void *cls,
  2830. enum GNUNET_MQ_Error error)
  2831. {
  2832. GNUNET_break_op (0);
  2833. }
  2834. /**
  2835. * Create a tunnel to @a destionation. Must only be called
  2836. * from within #GCP_get_tunnel().
  2837. *
  2838. * @param destination where to create the tunnel to
  2839. * @return new tunnel to @a destination
  2840. */
  2841. struct CadetTunnel *
  2842. GCT_create_tunnel (struct CadetPeer *destination)
  2843. {
  2844. struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
  2845. struct GNUNET_MQ_MessageHandler handlers[] = {
  2846. GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
  2847. GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
  2848. struct GNUNET_MessageHeader,
  2849. t),
  2850. GNUNET_MQ_hd_var_size (plaintext_data,
  2851. GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
  2852. struct GNUNET_CADET_ChannelAppDataMessage,
  2853. t),
  2854. GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
  2855. GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
  2856. struct GNUNET_CADET_ChannelDataAckMessage,
  2857. t),
  2858. GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
  2859. GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
  2860. struct GNUNET_CADET_ChannelOpenMessage,
  2861. t),
  2862. GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
  2863. GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
  2864. struct GNUNET_CADET_ChannelOpenAckMessage,
  2865. t),
  2866. GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
  2867. GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
  2868. struct GNUNET_CADET_ChannelDestroyMessage,
  2869. t),
  2870. GNUNET_MQ_handler_end ()
  2871. };
  2872. t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
  2873. new_ephemeral (&t->ax);
  2874. GNUNET_assert (GNUNET_OK ==
  2875. GNUNET_CRYPTO_ecdhe_key_create2 (&t->ax.kx_0));
  2876. t->destination = destination;
  2877. t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
  2878. t->maintain_connections_task
  2879. = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
  2880. t);
  2881. t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
  2882. NULL,
  2883. NULL,
  2884. NULL,
  2885. handlers,
  2886. &decrypted_error_cb,
  2887. t);
  2888. t->mst = GNUNET_MST_create (&handle_decrypted,
  2889. t);
  2890. return t;
  2891. }
  2892. /**
  2893. * Add a @a connection to the @a tunnel.
  2894. *
  2895. * @param t a tunnel
  2896. * @param cid connection identifer to use for the connection
  2897. * @param options options for the connection
  2898. * @param path path to use for the connection
  2899. * @return #GNUNET_OK on success,
  2900. * #GNUNET_SYSERR on failure (duplicate connection)
  2901. */
  2902. int
  2903. GCT_add_inbound_connection (struct CadetTunnel *t,
  2904. const struct
  2905. GNUNET_CADET_ConnectionTunnelIdentifier *cid,
  2906. struct CadetPeerPath *path)
  2907. {
  2908. struct CadetTConnection *ct;
  2909. ct = GNUNET_new (struct CadetTConnection);
  2910. ct->created = GNUNET_TIME_absolute_get ();
  2911. ct->t = t;
  2912. ct->cc = GCC_create_inbound (t->destination,
  2913. path,
  2914. ct,
  2915. cid,
  2916. &connection_ready_cb,
  2917. ct);
  2918. if (NULL == ct->cc)
  2919. {
  2920. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2921. "%s refused inbound %s (duplicate)\n",
  2922. GCT_2s (t),
  2923. GCC_2s (ct->cc));
  2924. GNUNET_free (ct);
  2925. return GNUNET_SYSERR;
  2926. }
  2927. /* FIXME: schedule job to kill connection (and path?) if it takes
  2928. too long to get ready! (And track performance data on how long
  2929. other connections took with the tunnel!)
  2930. => Note: to be done within 'connection'-logic! */
  2931. GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
  2932. t->connection_busy_tail,
  2933. ct);
  2934. t->num_busy_connections++;
  2935. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2936. "%s has new %s\n",
  2937. GCT_2s (t),
  2938. GCC_2s (ct->cc));
  2939. return GNUNET_OK;
  2940. }
  2941. /**
  2942. * Handle encrypted message.
  2943. *
  2944. * @param ct connection/tunnel combo that received encrypted message
  2945. * @param msg the encrypted message to decrypt
  2946. */
  2947. void
  2948. GCT_handle_encrypted (struct CadetTConnection *ct,
  2949. const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
  2950. {
  2951. struct CadetTunnel *t = ct->t;
  2952. uint16_t size = ntohs (msg->header.size);
  2953. char cbuf [size] GNUNET_ALIGN;
  2954. ssize_t decrypted_size;
  2955. LOG (GNUNET_ERROR_TYPE_DEBUG,
  2956. "%s received %u bytes of encrypted data in state %d\n",
  2957. GCT_2s (t),
  2958. (unsigned int) size,
  2959. t->estate);
  2960. switch (t->estate)
  2961. {
  2962. case CADET_TUNNEL_KEY_UNINITIALIZED:
  2963. case CADET_TUNNEL_KEY_AX_RECV:
  2964. /* We did not even SEND our KX, how can the other peer
  2965. send us encrypted data? Must have been that we went
  2966. down and the other peer still things we are up.
  2967. Let's send it KX back. */
  2968. GNUNET_STATISTICS_update (stats,
  2969. "# received encrypted without any KX",
  2970. 1,
  2971. GNUNET_NO);
  2972. if (NULL != t->kx_task)
  2973. {
  2974. GNUNET_SCHEDULER_cancel (t->kx_task);
  2975. t->kx_task = NULL;
  2976. }
  2977. send_kx (t,
  2978. ct,
  2979. &t->ax);
  2980. return;
  2981. case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
  2982. /* We send KX, and other peer send KX to us at the same time.
  2983. Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
  2984. GNUNET_STATISTICS_update (stats,
  2985. "# received encrypted without KX_AUTH",
  2986. 1,
  2987. GNUNET_NO);
  2988. if (NULL != t->kx_task)
  2989. {
  2990. GNUNET_SCHEDULER_cancel (t->kx_task);
  2991. t->kx_task = NULL;
  2992. }
  2993. send_kx_auth (t,
  2994. ct,
  2995. &t->ax,
  2996. GNUNET_YES);
  2997. return;
  2998. case CADET_TUNNEL_KEY_AX_SENT:
  2999. /* We did not get the KX of the other peer, but that
  3000. might have been lost. Send our KX again immediately. */
  3001. GNUNET_STATISTICS_update (stats,
  3002. "# received encrypted without KX",
  3003. 1,
  3004. GNUNET_NO);
  3005. if (NULL != t->kx_task)
  3006. {
  3007. GNUNET_SCHEDULER_cancel (t->kx_task);
  3008. t->kx_task = NULL;
  3009. }
  3010. send_kx (t,
  3011. ct,
  3012. &t->ax);
  3013. return;
  3014. case CADET_TUNNEL_KEY_AX_AUTH_SENT:
  3015. /* Great, first payload, we might graduate to OK! */
  3016. case CADET_TUNNEL_KEY_OK:
  3017. /* We are up and running, all good. */
  3018. break;
  3019. }
  3020. decrypted_size = -1;
  3021. if (CADET_TUNNEL_KEY_OK == t->estate)
  3022. {
  3023. /* We have well-established key material available,
  3024. try that. (This is the common case.) */
  3025. decrypted_size = t_ax_decrypt_and_validate (&t->ax,
  3026. cbuf,
  3027. msg,
  3028. size);
  3029. }
  3030. if ((-1 == decrypted_size) &&
  3031. (NULL != t->unverified_ax))
  3032. {
  3033. /* We have un-authenticated KX material available. We should try
  3034. this as a back-up option, in case the sender crashed and
  3035. switched keys. */
  3036. decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
  3037. cbuf,
  3038. msg,
  3039. size);
  3040. if (-1 != decrypted_size)
  3041. {
  3042. /* It worked! Treat this as authentication of the AX data! */
  3043. cleanup_ax (&t->ax);
  3044. t->ax = *t->unverified_ax;
  3045. GNUNET_free (t->unverified_ax);
  3046. t->unverified_ax = NULL;
  3047. }
  3048. if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
  3049. {
  3050. /* First time it worked, move tunnel into production! */
  3051. GCT_change_estate (t,
  3052. CADET_TUNNEL_KEY_OK);
  3053. if (NULL != t->send_task)
  3054. GNUNET_SCHEDULER_cancel (t->send_task);
  3055. t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
  3056. t);
  3057. }
  3058. }
  3059. if (NULL != t->unverified_ax)
  3060. {
  3061. /* We had unverified KX material that was useless; so increment
  3062. counter and eventually move to ignore it. Note that we even do
  3063. this increment if we successfully decrypted with the old KX
  3064. material and thus didn't even both with the new one. This is
  3065. the ideal case, as a malicious injection of bogus KX data
  3066. basically only causes us to increment a counter a few times. */t->unverified_attempts++;
  3067. LOG (GNUNET_ERROR_TYPE_DEBUG,
  3068. "Failed to decrypt message with unverified KX data %u times\n",
  3069. t->unverified_attempts);
  3070. if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
  3071. {
  3072. cleanup_ax (t->unverified_ax);
  3073. GNUNET_free (t->unverified_ax);
  3074. t->unverified_ax = NULL;
  3075. }
  3076. }
  3077. if (-1 == decrypted_size)
  3078. {
  3079. /* Decryption failed for good, complain. */
  3080. LOG (GNUNET_ERROR_TYPE_WARNING,
  3081. "%s failed to decrypt and validate encrypted data, retrying KX\n",
  3082. GCT_2s (t));
  3083. GNUNET_STATISTICS_update (stats,
  3084. "# unable to decrypt",
  3085. 1,
  3086. GNUNET_NO);
  3087. if (NULL != t->kx_task)
  3088. {
  3089. GNUNET_SCHEDULER_cancel (t->kx_task);
  3090. t->kx_task = NULL;
  3091. }
  3092. send_kx (t,
  3093. ct,
  3094. &t->ax);
  3095. return;
  3096. }
  3097. GNUNET_STATISTICS_update (stats,
  3098. "# decrypted bytes",
  3099. decrypted_size,
  3100. GNUNET_NO);
  3101. /* The MST will ultimately call #handle_decrypted() on each message. */
  3102. t->current_ct = ct;
  3103. GNUNET_break_op (GNUNET_OK ==
  3104. GNUNET_MST_from_buffer (t->mst,
  3105. cbuf,
  3106. decrypted_size,
  3107. GNUNET_YES,
  3108. GNUNET_NO));
  3109. t->current_ct = NULL;
  3110. }
  3111. /**
  3112. * Sends an already built message on a tunnel, encrypting it and
  3113. * choosing the best connection if not provided.
  3114. *
  3115. * @param message Message to send. Function modifies it.
  3116. * @param t Tunnel on which this message is transmitted.
  3117. * @param cont Continuation to call once message is really sent.
  3118. * @param cont_cls Closure for @c cont.
  3119. * @return Handle to cancel message
  3120. */
  3121. struct CadetTunnelQueueEntry *
  3122. GCT_send (struct CadetTunnel *t,
  3123. const struct GNUNET_MessageHeader *message,
  3124. GCT_SendContinuation cont,
  3125. void *cont_cls)
  3126. {
  3127. struct CadetTunnelQueueEntry *tq;
  3128. uint16_t payload_size;
  3129. struct GNUNET_MQ_Envelope *env;
  3130. struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
  3131. if (CADET_TUNNEL_KEY_OK != t->estate)
  3132. {
  3133. GNUNET_break (0);
  3134. return NULL;
  3135. }
  3136. payload_size = ntohs (message->size);
  3137. LOG (GNUNET_ERROR_TYPE_DEBUG,
  3138. "Encrypting %u bytes for %s\n",
  3139. (unsigned int) payload_size,
  3140. GCT_2s (t));
  3141. env = GNUNET_MQ_msg_extra (ax_msg,
  3142. payload_size,
  3143. GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
  3144. t_ax_encrypt (&t->ax,
  3145. &ax_msg[1],
  3146. message,
  3147. payload_size);
  3148. GNUNET_STATISTICS_update (stats,
  3149. "# encrypted bytes",
  3150. payload_size,
  3151. GNUNET_NO);
  3152. ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
  3153. ax_msg->ax_header.PNs = htonl (t->ax.PNs);
  3154. /* FIXME: we should do this once, not once per message;
  3155. this is a point multiplication, and DHRs does not
  3156. change all the time. */
  3157. GNUNET_CRYPTO_ecdhe_key_get_public (&t->ax.DHRs,
  3158. &ax_msg->ax_header.DHRs);
  3159. t_h_encrypt (&t->ax,
  3160. ax_msg);
  3161. t_hmac (&ax_msg->ax_header,
  3162. sizeof(struct GNUNET_CADET_AxHeader) + payload_size,
  3163. 0,
  3164. &t->ax.HKs,
  3165. &ax_msg->hmac);
  3166. tq = GNUNET_malloc (sizeof(*tq));
  3167. tq->t = t;
  3168. tq->env = env;
  3169. tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
  3170. tq->cont = cont;
  3171. tq->cont_cls = cont_cls;
  3172. GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
  3173. t->tq_tail,
  3174. tq);
  3175. if (NULL != t->send_task)
  3176. GNUNET_SCHEDULER_cancel (t->send_task);
  3177. t->send_task
  3178. = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
  3179. t);
  3180. return tq;
  3181. }
  3182. /**
  3183. * Cancel a previously sent message while it's in the queue.
  3184. *
  3185. * ONLY can be called before the continuation given to the send
  3186. * function is called. Once the continuation is called, the message is
  3187. * no longer in the queue!
  3188. *
  3189. * @param tq Handle to the queue entry to cancel.
  3190. */
  3191. void
  3192. GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
  3193. {
  3194. struct CadetTunnel *t = tq->t;
  3195. GNUNET_CONTAINER_DLL_remove (t->tq_head,
  3196. t->tq_tail,
  3197. tq);
  3198. GNUNET_MQ_discard (tq->env);
  3199. GNUNET_free (tq);
  3200. }
  3201. /**
  3202. * Iterate over all connections of a tunnel.
  3203. *
  3204. * @param t Tunnel whose connections to iterate.
  3205. * @param iter Iterator.
  3206. * @param iter_cls Closure for @c iter.
  3207. */
  3208. void
  3209. GCT_iterate_connections (struct CadetTunnel *t,
  3210. GCT_ConnectionIterator iter,
  3211. void *iter_cls)
  3212. {
  3213. struct CadetTConnection *n;
  3214. for (struct CadetTConnection *ct = t->connection_ready_head;
  3215. NULL != ct;
  3216. ct = n)
  3217. {
  3218. n = ct->next;
  3219. iter (iter_cls,
  3220. ct);
  3221. }
  3222. for (struct CadetTConnection *ct = t->connection_busy_head;
  3223. NULL != ct;
  3224. ct = n)
  3225. {
  3226. n = ct->next;
  3227. iter (iter_cls,
  3228. ct);
  3229. }
  3230. }
  3231. /**
  3232. * Closure for #iterate_channels_cb.
  3233. */
  3234. struct ChanIterCls
  3235. {
  3236. /**
  3237. * Function to call.
  3238. */
  3239. GCT_ChannelIterator iter;
  3240. /**
  3241. * Closure for @e iter.
  3242. */
  3243. void *iter_cls;
  3244. };
  3245. /**
  3246. * Helper function for #GCT_iterate_channels.
  3247. *
  3248. * @param cls the `struct ChanIterCls`
  3249. * @param key unused
  3250. * @param value a `struct CadetChannel`
  3251. * @return #GNUNET_OK
  3252. */
  3253. static int
  3254. iterate_channels_cb (void *cls,
  3255. uint32_t key,
  3256. void *value)
  3257. {
  3258. struct ChanIterCls *ctx = cls;
  3259. struct CadetChannel *ch = value;
  3260. ctx->iter (ctx->iter_cls,
  3261. ch);
  3262. return GNUNET_OK;
  3263. }
  3264. /**
  3265. * Iterate over all channels of a tunnel.
  3266. *
  3267. * @param t Tunnel whose channels to iterate.
  3268. * @param iter Iterator.
  3269. * @param iter_cls Closure for @c iter.
  3270. */
  3271. void
  3272. GCT_iterate_channels (struct CadetTunnel *t,
  3273. GCT_ChannelIterator iter,
  3274. void *iter_cls)
  3275. {
  3276. struct ChanIterCls ctx;
  3277. ctx.iter = iter;
  3278. ctx.iter_cls = iter_cls;
  3279. GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
  3280. &iterate_channels_cb,
  3281. &ctx);
  3282. }
  3283. /**
  3284. * Call #GCCH_debug() on a channel.
  3285. *
  3286. * @param cls points to the log level to use
  3287. * @param key unused
  3288. * @param value the `struct CadetChannel` to dump
  3289. * @return #GNUNET_OK (continue iteration)
  3290. */
  3291. static int
  3292. debug_channel (void *cls,
  3293. uint32_t key,
  3294. void *value)
  3295. {
  3296. const enum GNUNET_ErrorType *level = cls;
  3297. struct CadetChannel *ch = value;
  3298. GCCH_debug (ch, *level);
  3299. return GNUNET_OK;
  3300. }
  3301. #define LOG2(level, ...) GNUNET_log_from_nocheck (level, "cadet-tun", \
  3302. __VA_ARGS__)
  3303. /**
  3304. * Log all possible info about the tunnel state.
  3305. *
  3306. * @param t Tunnel to debug.
  3307. * @param level Debug level to use.
  3308. */
  3309. void
  3310. GCT_debug (const struct CadetTunnel *t,
  3311. enum GNUNET_ErrorType level)
  3312. {
  3313. #if ! defined(GNUNET_CULL_LOGGING)
  3314. struct CadetTConnection *iter_c;
  3315. int do_log;
  3316. do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
  3317. "cadet-tun",
  3318. __FILE__, __FUNCTION__, __LINE__);
  3319. if (0 == do_log)
  3320. return;
  3321. LOG2 (level,
  3322. "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
  3323. GCT_2s (t),
  3324. estate2s (t->estate),
  3325. t->tq_len,
  3326. GCT_count_any_connections (t));
  3327. LOG2 (level,
  3328. "TTT channels:\n");
  3329. GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
  3330. &debug_channel,
  3331. &level);
  3332. LOG2 (level,
  3333. "TTT connections:\n");
  3334. for (iter_c = t->connection_ready_head; NULL != iter_c; iter_c = iter_c->next)
  3335. GCC_debug (iter_c->cc,
  3336. level);
  3337. for (iter_c = t->connection_busy_head; NULL != iter_c; iter_c = iter_c->next)
  3338. GCC_debug (iter_c->cc,
  3339. level);
  3340. LOG2 (level,
  3341. "TTT TUNNEL END\n");
  3342. #endif
  3343. }
  3344. /* end of gnunet-service-cadet_tunnels.c */