connection_or.c 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file connection_or.c
  8. * \brief Functions to handle OR connections, TLS handshaking, and
  9. * cells on the network.
  10. *
  11. * An or_connection_t is a subtype of connection_t (as implemented in
  12. * connection.c) that uses a TLS connection to send and receive cells on the
  13. * Tor network. (By sending and receiving cells connection_or.c, it cooperates
  14. * with channeltls.c to implement a the channel interface of channel.c.)
  15. *
  16. * Every OR connection has an underlying tortls_t object (as implemented in
  17. * tortls.c) which it uses as its TLS stream. It is responsible for
  18. * sending and receiving cells over that TLS.
  19. *
  20. * This module also implements the client side of the v3 Tor link handshake,
  21. **/
  22. #include "core/or/or.h"
  23. #include "feature/client/bridges.h"
  24. #include "lib/buf/buffers.h"
  25. /*
  26. * Define this so we get channel internal functions, since we're implementing
  27. * part of a subclass (channel_tls_t).
  28. */
  29. #define TOR_CHANNEL_INTERNAL_
  30. #define CONNECTION_OR_PRIVATE
  31. #define ORCONN_EVENT_PRIVATE
  32. #include "core/or/channel.h"
  33. #include "core/or/channeltls.h"
  34. #include "core/or/circuitbuild.h"
  35. #include "core/or/circuitlist.h"
  36. #include "core/or/circuitstats.h"
  37. #include "core/or/command.h"
  38. #include "app/config/config.h"
  39. #include "core/mainloop/connection.h"
  40. #include "core/or/connection_or.h"
  41. #include "feature/control/control_events.h"
  42. #include "lib/crypt_ops/crypto_rand.h"
  43. #include "lib/crypt_ops/crypto_util.h"
  44. #include "feature/dirauth/reachability.h"
  45. #include "feature/client/entrynodes.h"
  46. #include "lib/geoip/geoip.h"
  47. #include "core/mainloop/mainloop.h"
  48. #include "trunnel/link_handshake.h"
  49. #include "trunnel/netinfo.h"
  50. #include "feature/nodelist/microdesc.h"
  51. #include "feature/nodelist/networkstatus.h"
  52. #include "feature/nodelist/nodelist.h"
  53. #include "core/proto/proto_cell.h"
  54. #include "core/or/reasons.h"
  55. #include "core/or/relay.h"
  56. #include "feature/rend/rendcommon.h"
  57. #include "feature/stats/rephist.h"
  58. #include "feature/relay/router.h"
  59. #include "feature/relay/routerkeys.h"
  60. #include "feature/relay/routermode.h"
  61. #include "feature/nodelist/dirlist.h"
  62. #include "feature/nodelist/routerlist.h"
  63. #include "feature/relay/ext_orport.h"
  64. #include "core/or/scheduler.h"
  65. #include "feature/nodelist/torcert.h"
  66. #include "core/or/channelpadding.h"
  67. #include "feature/dirauth/authmode.h"
  68. #include "core/or/cell_st.h"
  69. #include "core/or/cell_queue_st.h"
  70. #include "core/or/or_connection_st.h"
  71. #include "core/or/or_handshake_certs_st.h"
  72. #include "core/or/or_handshake_state_st.h"
  73. #include "app/config/or_state_st.h"
  74. #include "feature/nodelist/routerinfo_st.h"
  75. #include "core/or/var_cell_st.h"
  76. #include "lib/crypt_ops/crypto_format.h"
  77. #include "lib/tls/tortls.h"
  78. #include "lib/tls/x509.h"
  79. #include "core/or/orconn_event.h"
  80. //static int connection_tls_finish_handshake(or_connection_t *conn);
  81. static int connection_or_launch_v3_or_handshake(or_connection_t *conn);
  82. static int connection_or_new_process_cells_from_inbuf(or_connection_t *conn);
  83. //static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
  84. //static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
  85. // int started_here,
  86. // char *digest_rcvd_out);
  87. //static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn);
  88. static unsigned int
  89. connection_or_is_bad_for_new_circs(or_connection_t *or_conn);
  90. static void connection_or_mark_bad_for_new_circs(or_connection_t *or_conn);
  91. /*
  92. * Call this when changing connection state, so notifications to the owning
  93. * channel can be handled.
  94. */
  95. static void connection_or_change_state(or_connection_t *conn, uint8_t state);
  96. static void connection_or_check_canonicity(or_connection_t *conn,
  97. int started_here);
  98. /**************************************************************/
  99. /** Convert a connection_t* to an or_connection_t*; assert if the cast is
  100. * invalid. */
  101. or_connection_t *
  102. TO_OR_CONN(connection_t *c)
  103. {
  104. tor_assert(c->magic == OR_CONNECTION_MAGIC);
  105. return DOWNCAST(or_connection_t, c);
  106. }
  107. /** Global map between Extended ORPort identifiers and OR
  108. * connections. */
  109. static digestmap_t *orconn_ext_or_id_map = NULL;
  110. /** Clear clear conn->identity_digest and update other data
  111. * structures as appropriate.*/
  112. void
  113. connection_or_clear_identity(or_connection_t *conn)
  114. {
  115. tor_assert(conn);
  116. memset(conn->identity_digest, 0, DIGEST_LEN);
  117. }
  118. /** Clear all identities in OR conns.*/
  119. void
  120. connection_or_clear_identity_map(void)
  121. {
  122. smartlist_t *conns = get_connection_array();
  123. SMARTLIST_FOREACH(conns, connection_t *, conn,
  124. {
  125. if (conn->type == CONN_TYPE_OR) {
  126. connection_or_clear_identity(TO_OR_CONN(conn));
  127. }
  128. });
  129. }
  130. /** Change conn->identity_digest to digest, and add conn into
  131. * the appropriate digest maps.
  132. *
  133. * NOTE that this function only allows two kinds of transitions: from
  134. * unset identity to set identity, and from idempotent re-settings
  135. * of the same identity. It's not allowed to clear an identity or to
  136. * change an identity. Return 0 on success, and -1 if the transition
  137. * is not allowed.
  138. **/
  139. static void
  140. connection_or_set_identity_digest(or_connection_t *conn,
  141. const char *rsa_digest,
  142. const ed25519_public_key_t *ed_id)
  143. {
  144. channel_t *chan = NULL;
  145. tor_assert(conn);
  146. tor_assert(rsa_digest);
  147. if (conn->chan)
  148. chan = TLS_CHAN_TO_BASE(conn->chan);
  149. log_info(LD_HANDSHAKE, "Set identity digest for %p (%s): %s %s.",
  150. conn,
  151. escaped_safe_str(conn->base_.address),
  152. hex_str(rsa_digest, DIGEST_LEN),
  153. ed25519_fmt(ed_id));
  154. log_info(LD_HANDSHAKE, " (Previously: %s %s)",
  155. hex_str(conn->identity_digest, DIGEST_LEN),
  156. chan ? ed25519_fmt(&chan->ed25519_identity) : "<null>");
  157. const int rsa_id_was_set = ! tor_digest_is_zero(conn->identity_digest);
  158. const int ed_id_was_set =
  159. chan && !ed25519_public_key_is_zero(&chan->ed25519_identity);
  160. const int rsa_changed =
  161. tor_memneq(conn->identity_digest, rsa_digest, DIGEST_LEN);
  162. const int ed_changed = ed_id_was_set &&
  163. (!ed_id || !ed25519_pubkey_eq(ed_id, &chan->ed25519_identity));
  164. tor_assert(!rsa_changed || !rsa_id_was_set);
  165. tor_assert(!ed_changed || !ed_id_was_set);
  166. if (!rsa_changed && !ed_changed)
  167. return;
  168. /* If the identity was set previously, remove the old mapping. */
  169. if (rsa_id_was_set) {
  170. connection_or_clear_identity(conn);
  171. if (chan)
  172. channel_clear_identity_digest(chan);
  173. }
  174. memcpy(conn->identity_digest, rsa_digest, DIGEST_LEN);
  175. /* If we're initializing the IDs to zero, don't add a mapping yet. */
  176. if (tor_digest_is_zero(rsa_digest) &&
  177. (!ed_id || ed25519_public_key_is_zero(ed_id)))
  178. return;
  179. /* Deal with channels */
  180. if (chan)
  181. channel_set_identity_digest(chan, rsa_digest, ed_id);
  182. }
  183. /** Remove the Extended ORPort identifier of <b>conn</b> from the
  184. * global identifier list. Also, clear the identifier from the
  185. * connection itself. */
  186. void
  187. connection_or_remove_from_ext_or_id_map(or_connection_t *conn)
  188. {
  189. or_connection_t *tmp;
  190. if (!orconn_ext_or_id_map)
  191. return;
  192. if (!conn->ext_or_conn_id)
  193. return;
  194. tmp = digestmap_remove(orconn_ext_or_id_map, conn->ext_or_conn_id);
  195. if (!tor_digest_is_zero(conn->ext_or_conn_id))
  196. tor_assert(tmp == conn);
  197. memset(conn->ext_or_conn_id, 0, EXT_OR_CONN_ID_LEN);
  198. }
  199. /** Return the connection whose ext_or_id is <b>id</b>. Return NULL if no such
  200. * connection is found. */
  201. or_connection_t *
  202. connection_or_get_by_ext_or_id(const char *id)
  203. {
  204. if (!orconn_ext_or_id_map)
  205. return NULL;
  206. return digestmap_get(orconn_ext_or_id_map, id);
  207. }
  208. /** Deallocate the global Extended ORPort identifier list */
  209. void
  210. connection_or_clear_ext_or_id_map(void)
  211. {
  212. digestmap_free(orconn_ext_or_id_map, NULL);
  213. orconn_ext_or_id_map = NULL;
  214. }
  215. /** Creates an Extended ORPort identifier for <b>conn</b> and deposits
  216. * it into the global list of identifiers. */
  217. void
  218. connection_or_set_ext_or_identifier(or_connection_t *conn)
  219. {
  220. char random_id[EXT_OR_CONN_ID_LEN];
  221. or_connection_t *tmp;
  222. if (!orconn_ext_or_id_map)
  223. orconn_ext_or_id_map = digestmap_new();
  224. /* Remove any previous identifiers: */
  225. if (conn->ext_or_conn_id && !tor_digest_is_zero(conn->ext_or_conn_id))
  226. connection_or_remove_from_ext_or_id_map(conn);
  227. do {
  228. crypto_rand(random_id, sizeof(random_id));
  229. } while (digestmap_get(orconn_ext_or_id_map, random_id));
  230. if (!conn->ext_or_conn_id)
  231. conn->ext_or_conn_id = tor_malloc_zero(EXT_OR_CONN_ID_LEN);
  232. memcpy(conn->ext_or_conn_id, random_id, EXT_OR_CONN_ID_LEN);
  233. tmp = digestmap_set(orconn_ext_or_id_map, random_id, conn);
  234. tor_assert(!tmp);
  235. }
  236. /**************************************************************/
  237. /** Map from a string describing what a non-open OR connection was doing when
  238. * failed, to an intptr_t describing the count of connections that failed that
  239. * way. Note that the count is stored _as_ the pointer.
  240. */
  241. static strmap_t *broken_connection_counts;
  242. /** If true, do not record information in <b>broken_connection_counts</b>. */
  243. static int disable_broken_connection_counts = 0;
  244. /** Record that an OR connection failed in <b>state</b>. */
  245. static void
  246. note_broken_connection(const char *state)
  247. {
  248. void *ptr;
  249. intptr_t val;
  250. if (disable_broken_connection_counts)
  251. return;
  252. if (!broken_connection_counts)
  253. broken_connection_counts = strmap_new();
  254. ptr = strmap_get(broken_connection_counts, state);
  255. val = (intptr_t)ptr;
  256. val++;
  257. ptr = (void*)val;
  258. strmap_set(broken_connection_counts, state, ptr);
  259. }
  260. /** Forget all recorded states for failed connections. If
  261. * <b>stop_recording</b> is true, don't record any more. */
  262. void
  263. clear_broken_connection_map(int stop_recording)
  264. {
  265. if (broken_connection_counts)
  266. strmap_free(broken_connection_counts, NULL);
  267. broken_connection_counts = NULL;
  268. if (stop_recording)
  269. disable_broken_connection_counts = 1;
  270. }
  271. /** Write a detailed description the state of <b>orconn</b> into the
  272. * <b>buflen</b>-byte buffer at <b>buf</b>. This description includes not
  273. * only the OR-conn level state but also the TLS state. It's useful for
  274. * diagnosing broken handshakes. */
  275. static void
  276. connection_or_get_state_description(or_connection_t *orconn,
  277. char *buf, size_t buflen)
  278. {
  279. connection_t *conn = TO_CONN(orconn);
  280. const char *conn_state;
  281. char tls_state[256];
  282. tor_assert(conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR);
  283. conn_state = conn_state_to_string(conn->type, conn->state);
  284. //tor_tls_get_state_description(orconn->tls, tls_state, sizeof(tls_state));
  285. tor_assert(conn->safe_conn != NULL);
  286. safe_or_connection_get_tls_desc(TO_SAFE_OR_CONN(conn->safe_conn), tls_state, sizeof(tls_state));
  287. tor_snprintf(buf, buflen, "%s with SSL state %s", conn_state, tls_state);
  288. }
  289. /** Record the current state of <b>orconn</b> as the state of a broken
  290. * connection. */
  291. static void
  292. connection_or_note_state_when_broken(or_connection_t *orconn)
  293. {
  294. char buf[256];
  295. if (disable_broken_connection_counts)
  296. return;
  297. connection_or_get_state_description(orconn, buf, sizeof(buf));
  298. log_info(LD_HANDSHAKE,"Connection died in state '%s'", buf);
  299. note_broken_connection(buf);
  300. }
  301. /** Helper type used to sort connection states and find the most frequent. */
  302. typedef struct broken_state_count_t {
  303. intptr_t count;
  304. const char *state;
  305. } broken_state_count_t;
  306. /** Helper function used to sort broken_state_count_t by frequency. */
  307. static int
  308. broken_state_count_compare(const void **a_ptr, const void **b_ptr)
  309. {
  310. const broken_state_count_t *a = *a_ptr, *b = *b_ptr;
  311. if (b->count < a->count)
  312. return -1;
  313. else if (b->count == a->count)
  314. return 0;
  315. else
  316. return 1;
  317. }
  318. /** Upper limit on the number of different states to report for connection
  319. * failure. */
  320. #define MAX_REASONS_TO_REPORT 10
  321. /** Report a list of the top states for failed OR connections at log level
  322. * <b>severity</b>, in log domain <b>domain</b>. */
  323. void
  324. connection_or_report_broken_states(int severity, int domain)
  325. {
  326. int total = 0;
  327. smartlist_t *items;
  328. if (!broken_connection_counts || disable_broken_connection_counts)
  329. return;
  330. items = smartlist_new();
  331. STRMAP_FOREACH(broken_connection_counts, state, void *, countptr) {
  332. broken_state_count_t *c = tor_malloc(sizeof(broken_state_count_t));
  333. c->count = (intptr_t)countptr;
  334. total += (int)c->count;
  335. c->state = state;
  336. smartlist_add(items, c);
  337. } STRMAP_FOREACH_END;
  338. smartlist_sort(items, broken_state_count_compare);
  339. tor_log(severity, domain, "%d connections have failed%s", total,
  340. smartlist_len(items) > MAX_REASONS_TO_REPORT ? ". Top reasons:" : ":");
  341. SMARTLIST_FOREACH_BEGIN(items, const broken_state_count_t *, c) {
  342. if (c_sl_idx > MAX_REASONS_TO_REPORT)
  343. break;
  344. tor_log(severity, domain,
  345. " %d connections died in state %s", (int)c->count, c->state);
  346. } SMARTLIST_FOREACH_END(c);
  347. SMARTLIST_FOREACH(items, broken_state_count_t *, c, tor_free(c));
  348. smartlist_free(items);
  349. }
  350. /**
  351. * Helper function to publish an OR connection status event
  352. *
  353. * Publishes a messages to subscribers of ORCONN messages, and sends
  354. * the control event.
  355. **/
  356. void
  357. connection_or_event_status(or_connection_t *conn, or_conn_status_event_t tp,
  358. int reason)
  359. {
  360. orconn_status_msg_t *msg = tor_malloc(sizeof(*msg));
  361. msg->gid = conn->base_.global_identifier;
  362. msg->status = tp;
  363. msg->reason = reason;
  364. orconn_status_publish(msg);
  365. control_event_or_conn_status(conn, tp, reason);
  366. }
  367. /**
  368. * Helper function to publish a state change message
  369. *
  370. * connection_or_change_state() calls this to notify subscribers about
  371. * a change of an OR connection state.
  372. **/
  373. static void
  374. connection_or_state_publish(const or_connection_t *conn, uint8_t state)
  375. {
  376. orconn_state_msg_t *msg = tor_malloc(sizeof(*msg));
  377. msg->gid = conn->base_.global_identifier;
  378. if (conn->is_pt) {
  379. /* Do extra decoding because conn->proxy_type indicates the proxy
  380. * protocol that tor uses to talk with the transport plugin,
  381. * instead of PROXY_PLUGGABLE. */
  382. tor_assert_nonfatal(conn->proxy_type != PROXY_NONE);
  383. msg->proxy_type = PROXY_PLUGGABLE;
  384. } else {
  385. msg->proxy_type = conn->proxy_type;
  386. }
  387. msg->state = state;
  388. if (conn->chan) {
  389. msg->chan = TLS_CHAN_TO_BASE(conn->chan)->global_identifier;
  390. } else {
  391. msg->chan = 0;
  392. }
  393. orconn_state_publish(msg);
  394. }
  395. /** Call this to change or_connection_t states, so the owning channel_tls_t can
  396. * be notified.
  397. */
  398. static void
  399. connection_or_change_state(or_connection_t *conn, uint8_t state)
  400. {
  401. tor_assert(conn);
  402. conn->base_.state = state;
  403. connection_or_state_publish(conn, state);
  404. if (conn->chan)
  405. channel_tls_handle_state_change_on_orconn(conn->chan, conn, state);
  406. }
  407. /** Return the number of circuits using an or_connection_t; this used to
  408. * be an or_connection_t field, but it got moved to channel_t and we
  409. * shouldn't maintain two copies. */
  410. MOCK_IMPL(int,
  411. connection_or_get_num_circuits, (or_connection_t *conn))
  412. {
  413. tor_assert(conn);
  414. if (conn->chan) {
  415. return channel_num_circuits(TLS_CHAN_TO_BASE(conn->chan));
  416. } else return 0;
  417. }
  418. void
  419. connection_or_process_event(event_label_t label, event_data_t data,
  420. void *context)
  421. {
  422. or_connection_t *or_conn = context;
  423. if (label == safe_or_conn_tcp_connecting_ev) {
  424. // TODO: anything to do here?
  425. } else if (label == safe_or_conn_tls_handshaking_ev) {
  426. connection_or_change_state(or_conn, OR_CONN_STATE_TLS_HANDSHAKING);
  427. } else if (label == safe_or_conn_link_handshaking_ev) {
  428. link_handshaking_ev_data *handshake_data = data.ptr;
  429. or_conn->tls_own_cert = handshake_data->tls_own_cert;
  430. or_conn->tls_peer_cert = handshake_data->tls_peer_cert;
  431. tor_assert(or_conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING);
  432. log_warn(LD_OR, "OR conn recieved link handshaking event: %s", or_conn->is_outgoing?"outgoing":"incoming");
  433. if (or_conn->is_outgoing) {
  434. tor_assert(connection_or_launch_v3_or_handshake(or_conn) == 0);
  435. } else {
  436. connection_or_change_state(or_conn,
  437. OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
  438. // TODO: should we choose a different state here?
  439. // enter_v3_handshake_with_cell() assumes we're in state
  440. // 'OR_CONN_STATE_TLS_SERVER_RENEGOTIATING'
  441. }
  442. } else if (label == safe_or_conn_open_ev) {
  443. // TODO: anything to do here?
  444. } else if (label == safe_or_conn_closed_ev) {
  445. // TODO: improve the error handling below
  446. connection_or_notify_error(or_conn, END_OR_CONN_REASON_CONNRESET, "unknown");
  447. connection_close_immediate(TO_CONN(or_conn));
  448. connection_mark_for_close_internal(TO_CONN(or_conn));
  449. } else if (label == safe_or_conn_has_buffered_data_ev) {
  450. connection_or_new_process_cells_from_inbuf(or_conn);
  451. } else {
  452. log_warn(LD_OR, "Received an OR event that we don't recognize");
  453. }
  454. }
  455. /**************************************************************/
  456. /** Pack the cell_t host-order structure <b>src</b> into network-order
  457. * in the buffer <b>dest</b>. See tor-spec.txt for details about the
  458. * wire format.
  459. *
  460. * Note that this function doesn't touch <b>dst</b>-\>next: the caller
  461. * should set it or clear it as appropriate.
  462. */
  463. void
  464. cell_pack(packed_cell_t *dst, const cell_t *src, int wide_circ_ids)
  465. {
  466. char *dest = dst->body;
  467. if (wide_circ_ids) {
  468. set_uint32(dest, htonl(src->circ_id));
  469. dest += 4;
  470. } else {
  471. /* Clear the last two bytes of dest, in case we can accidentally
  472. * send them to the network somehow. */
  473. memset(dest+CELL_MAX_NETWORK_SIZE-2, 0, 2);
  474. set_uint16(dest, htons(src->circ_id));
  475. dest += 2;
  476. }
  477. set_uint8(dest, src->command);
  478. memcpy(dest+1, src->payload, CELL_PAYLOAD_SIZE);
  479. }
  480. /** Unpack the network-order buffer <b>src</b> into a host-order
  481. * cell_t structure <b>dest</b>.
  482. */
  483. static void
  484. cell_unpack(cell_t *dest, const char *src, int wide_circ_ids)
  485. {
  486. if (wide_circ_ids) {
  487. dest->circ_id = ntohl(get_uint32(src));
  488. src += 4;
  489. } else {
  490. dest->circ_id = ntohs(get_uint16(src));
  491. src += 2;
  492. }
  493. dest->command = get_uint8(src);
  494. memcpy(dest->payload, src+1, CELL_PAYLOAD_SIZE);
  495. }
  496. /** Write the header of <b>cell</b> into the first VAR_CELL_MAX_HEADER_SIZE
  497. * bytes of <b>hdr_out</b>. Returns number of bytes used. */
  498. int
  499. var_cell_pack_header(const var_cell_t *cell, char *hdr_out, int wide_circ_ids)
  500. {
  501. int r;
  502. if (wide_circ_ids) {
  503. set_uint32(hdr_out, htonl(cell->circ_id));
  504. hdr_out += 4;
  505. r = VAR_CELL_MAX_HEADER_SIZE;
  506. } else {
  507. set_uint16(hdr_out, htons(cell->circ_id));
  508. hdr_out += 2;
  509. r = VAR_CELL_MAX_HEADER_SIZE - 2;
  510. }
  511. set_uint8(hdr_out, cell->command);
  512. set_uint16(hdr_out+1, htons(cell->payload_len));
  513. return r;
  514. }
  515. /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
  516. * payload space. */
  517. var_cell_t *
  518. var_cell_new(uint16_t payload_len)
  519. {
  520. size_t size = offsetof(var_cell_t, payload) + payload_len;
  521. var_cell_t *cell = tor_malloc_zero(size);
  522. cell->payload_len = payload_len;
  523. cell->command = 0;
  524. cell->circ_id = 0;
  525. return cell;
  526. }
  527. /**
  528. * Copy a var_cell_t
  529. */
  530. var_cell_t *
  531. var_cell_copy(const var_cell_t *src)
  532. {
  533. var_cell_t *copy = NULL;
  534. size_t size = 0;
  535. if (src != NULL) {
  536. size = offsetof(var_cell_t, payload) + src->payload_len;
  537. copy = tor_malloc_zero(size);
  538. copy->payload_len = src->payload_len;
  539. copy->command = src->command;
  540. copy->circ_id = src->circ_id;
  541. memcpy(copy->payload, src->payload, copy->payload_len);
  542. }
  543. return copy;
  544. }
  545. /** Release all space held by <b>cell</b>. */
  546. void
  547. var_cell_free_(var_cell_t *cell)
  548. {
  549. tor_free(cell);
  550. }
  551. /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
  552. int
  553. connection_or_reached_eof(or_connection_t *conn)
  554. {
  555. tor_assert(conn);
  556. log_info(LD_OR,"OR connection reached EOF. Closing.");
  557. connection_or_close_normally(conn, 1);
  558. return 0;
  559. }
  560. /** Handle any new bytes that have come in on connection <b>conn</b>.
  561. * If conn is in 'open' state, hand it to
  562. * connection_or_process_cells_from_inbuf()
  563. * (else do nothing).
  564. */
  565. //int
  566. //connection_or_process_inbuf(or_connection_t *conn)
  567. //{
  568. // /** Don't let the inbuf of a nonopen OR connection grow beyond this many
  569. // * bytes: it's either a broken client, a non-Tor client, or a DOS
  570. // * attempt. */
  571. //#define MAX_OR_INBUF_WHEN_NONOPEN 0
  572. //
  573. // int ret = 0;
  574. // tor_assert(conn);
  575. //
  576. // switch (conn->base_.state) {
  577. // case OR_CONN_STATE_PROXY_HANDSHAKING:
  578. // ret = connection_read_proxy_handshake(TO_CONN(conn));
  579. //
  580. // /* start TLS after handshake completion, or deal with error */
  581. // if (ret == 1) {
  582. // tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
  583. // if (connection_tls_start_handshake(conn, 0) < 0)
  584. // ret = -1;
  585. // /* Touch the channel's active timestamp if there is one */
  586. // if (conn->chan)
  587. // channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
  588. // }
  589. // if (ret < 0) {
  590. // connection_or_close_for_error(conn, 0);
  591. // }
  592. //
  593. // return ret;
  594. // case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  595. // case OR_CONN_STATE_OPEN:
  596. // case OR_CONN_STATE_OR_HANDSHAKING_V2:
  597. // case OR_CONN_STATE_OR_HANDSHAKING_V3:
  598. // return connection_or_process_cells_from_inbuf(conn);
  599. // default:
  600. // break; /* don't do anything */
  601. // }
  602. //
  603. // /* This check was necessary with 0.2.2, when the TLS_SERVER_RENEGOTIATING
  604. // * check would otherwise just let data accumulate. It serves no purpose
  605. // * in 0.2.3.
  606. // *
  607. // * XXXX Remove this check once we verify that the above paragraph is
  608. // * 100% true. */
  609. // if (buf_datalen(conn->base_.inbuf) > MAX_OR_INBUF_WHEN_NONOPEN) {
  610. // log_fn(LOG_PROTOCOL_WARN, LD_NET, "Accumulated too much data (%d bytes) "
  611. // "on nonopen OR connection %s %s:%u in state %s; closing.",
  612. // (int)buf_datalen(conn->base_.inbuf),
  613. // connection_or_nonopen_was_started_here(conn) ? "to" : "from",
  614. // conn->base_.address, conn->base_.port,
  615. // conn_state_to_string(conn->base_.type, conn->base_.state));
  616. // connection_or_close_for_error(conn, 0);
  617. // ret = -1;
  618. // }
  619. //
  620. // return ret;
  621. //}
  622. /** Called whenever we have flushed some data on an or_conn: add more data
  623. * from active circuits. */
  624. int
  625. connection_or_flushed_some(or_connection_t *conn)
  626. {
  627. size_t datalen;
  628. /* Update the channel's active timestamp if there is one */
  629. if (conn->chan)
  630. channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
  631. /* If we're under the low water mark, add cells until we're just over the
  632. * high water mark. */
  633. // TODO: fix this ugly locking
  634. tor_assert(TO_CONN(conn)->safe_conn != NULL);
  635. tor_mutex_acquire(&(TO_CONN(conn)->safe_conn->lock));
  636. datalen = buf_datalen(TO_CONN(conn)->safe_conn->outbuf);
  637. tor_mutex_release(&(TO_CONN(conn)->safe_conn->lock));
  638. //datalen = connection_get_outbuf_len(TO_CONN(conn));
  639. if (datalen < OR_CONN_LOWWATER) {
  640. /* Let the scheduler know */
  641. scheduler_channel_wants_writes(TLS_CHAN_TO_BASE(conn->chan));
  642. }
  643. return 0;
  644. }
  645. /** This is for channeltls.c to ask how many cells we could accept if
  646. * they were available. */
  647. ssize_t
  648. connection_or_num_cells_writeable(or_connection_t *conn)
  649. {
  650. size_t datalen, cell_network_size;
  651. ssize_t n = 0;
  652. tor_assert(conn);
  653. /*
  654. * If we're under the high water mark, we're potentially
  655. * writeable; note this is different from the calculation above
  656. * used to trigger when to start writing after we've stopped.
  657. */
  658. // TODO: fix this ugly locking
  659. tor_assert(TO_CONN(conn)->safe_conn != NULL);
  660. tor_mutex_acquire(&(TO_CONN(conn)->safe_conn->lock));
  661. datalen = buf_datalen(TO_CONN(conn)->safe_conn->outbuf);
  662. tor_mutex_release(&(TO_CONN(conn)->safe_conn->lock));
  663. //datalen = connection_get_outbuf_len(TO_CONN(conn));
  664. if (datalen < OR_CONN_HIGHWATER) {
  665. cell_network_size = get_cell_network_size(conn->wide_circ_ids);
  666. n = CEIL_DIV(OR_CONN_HIGHWATER - datalen, cell_network_size);
  667. }
  668. return n;
  669. }
  670. /** Connection <b>conn</b> has finished writing and has no bytes left on
  671. * its outbuf.
  672. *
  673. * Otherwise it's in state "open": stop writing and return.
  674. *
  675. * If <b>conn</b> is broken, mark it for close and return -1, else
  676. * return 0.
  677. */
  678. int
  679. connection_or_finished_flushing(or_connection_t *conn)
  680. {
  681. tor_assert(conn);
  682. assert_connection_ok(TO_CONN(conn),0);
  683. switch (conn->base_.state) {
  684. case OR_CONN_STATE_PROXY_HANDSHAKING:
  685. case OR_CONN_STATE_OPEN:
  686. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  687. case OR_CONN_STATE_OR_HANDSHAKING_V3:
  688. break;
  689. default:
  690. log_err(LD_BUG,"Called in unexpected state %d.", conn->base_.state);
  691. tor_fragile_assert();
  692. return -1;
  693. }
  694. /* Update the channel's active timestamp if there is one */
  695. if (conn->chan)
  696. channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
  697. return 0;
  698. }
  699. /** Connected handler for OR connections: begin the TLS handshake.
  700. */
  701. int
  702. connection_or_finished_connecting(or_connection_t *or_conn)
  703. {
  704. const int proxy_type = or_conn->proxy_type;
  705. connection_t *conn;
  706. tor_assert(or_conn);
  707. conn = TO_CONN(or_conn);
  708. tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
  709. log_debug(LD_HANDSHAKE,"OR connect() to router at %s:%u finished.",
  710. conn->address,conn->port);
  711. if (proxy_type != PROXY_NONE) {
  712. log_warn(LD_BUG, "Connection proxies aren't yet supported by safe connections");
  713. tor_assert(0);
  714. /* start proxy handshake */
  715. //if (connection_proxy_connect(conn, proxy_type) < 0) {
  716. // connection_or_close_for_error(or_conn, 0);
  717. // return -1;
  718. //}
  719. //connection_start_reading(conn);
  720. //connection_or_change_state(or_conn, OR_CONN_STATE_PROXY_HANDSHAKING);
  721. //return 0;
  722. }
  723. //if (connection_tls_start_handshake(or_conn, 0) < 0) {
  724. // /* TLS handshaking error of some kind. */
  725. // connection_or_close_for_error(or_conn, 0);
  726. // return -1;
  727. //}
  728. return 0;
  729. }
  730. /** Called when we're about to finally unlink and free an OR connection:
  731. * perform necessary accounting and cleanup */
  732. void
  733. connection_or_about_to_close(or_connection_t *or_conn)
  734. {
  735. connection_t *conn = TO_CONN(or_conn);
  736. /* Tell the controlling channel we're closed */
  737. if (or_conn->chan) {
  738. channel_closed(TLS_CHAN_TO_BASE(or_conn->chan));
  739. /*
  740. * NULL this out because the channel might hang around a little
  741. * longer before channel_run_cleanup() gets it.
  742. */
  743. or_conn->chan->conn = NULL;
  744. or_conn->chan = NULL;
  745. }
  746. /* Remember why we're closing this connection. */
  747. if (conn->state != OR_CONN_STATE_OPEN) {
  748. /* now mark things down as needed */
  749. if (connection_or_nonopen_was_started_here(or_conn)) {
  750. const or_options_t *options = get_options();
  751. connection_or_note_state_when_broken(or_conn);
  752. /* Tell the new guard API about the channel failure */
  753. entry_guard_chan_failed(TLS_CHAN_TO_BASE(or_conn->chan));
  754. if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
  755. int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
  756. connection_or_event_status(or_conn, OR_CONN_EVENT_FAILED,
  757. reason);
  758. if (!authdir_mode_tests_reachability(options))
  759. control_event_bootstrap_prob_or(
  760. orconn_end_reason_to_control_string(reason),
  761. reason, or_conn);
  762. }
  763. }
  764. } else if (conn->hold_open_until_flushed) {
  765. /* We only set hold_open_until_flushed when we're intentionally
  766. * closing a connection. */
  767. connection_or_event_status(or_conn, OR_CONN_EVENT_CLOSED,
  768. tls_error_to_orconn_end_reason(or_conn->tls_error));
  769. } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
  770. connection_or_event_status(or_conn, OR_CONN_EVENT_CLOSED,
  771. tls_error_to_orconn_end_reason(or_conn->tls_error));
  772. }
  773. }
  774. /** Return 1 if identity digest <b>id_digest</b> is known to be a
  775. * currently or recently running relay. Otherwise return 0. */
  776. int
  777. connection_or_digest_is_known_relay(const char *id_digest)
  778. {
  779. if (router_get_consensus_status_by_id(id_digest))
  780. return 1; /* It's in the consensus: "yes" */
  781. if (router_get_by_id_digest(id_digest))
  782. return 1; /* Not in the consensus, but we have a descriptor for
  783. * it. Probably it was in a recent consensus. "Yes". */
  784. return 0;
  785. }
  786. /** Set the per-conn read and write limits for <b>conn</b>. If it's a known
  787. * relay, we will rely on the global read and write buckets, so give it
  788. * per-conn limits that are big enough they'll never matter. But if it's
  789. * not a known relay, first check if we set PerConnBwRate/Burst, then
  790. * check if the consensus sets them, else default to 'big enough'.
  791. *
  792. * If <b>reset</b> is true, set the bucket to be full. Otherwise, just
  793. * clip the bucket if it happens to be <em>too</em> full.
  794. */
  795. static void
  796. connection_or_update_token_buckets_helper(or_connection_t *conn, int reset,
  797. const or_options_t *options)
  798. {
  799. int rate, burst; /* per-connection rate limiting params */
  800. if (connection_or_digest_is_known_relay(conn->identity_digest)) {
  801. /* It's in the consensus, or we have a descriptor for it meaning it
  802. * was probably in a recent consensus. It's a recognized relay:
  803. * give it full bandwidth. */
  804. rate = (int)options->BandwidthRate;
  805. burst = (int)options->BandwidthBurst;
  806. } else {
  807. /* Not a recognized relay. Squeeze it down based on the suggested
  808. * bandwidth parameters in the consensus, but allow local config
  809. * options to override. */
  810. rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
  811. networkstatus_get_param(NULL, "perconnbwrate",
  812. (int)options->BandwidthRate, 1, INT32_MAX);
  813. burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
  814. networkstatus_get_param(NULL, "perconnbwburst",
  815. (int)options->BandwidthBurst, 1, INT32_MAX);
  816. }
  817. safe_or_connection_adjust_buckets(TO_SAFE_OR_CONN(TO_CONN(conn)->safe_conn),
  818. rate, burst, reset,
  819. monotime_coarse_get_stamp());
  820. //token_bucket_rw_adjust(&conn->bucket, rate, burst);
  821. //if (reset) {
  822. // token_bucket_rw_reset(&conn->bucket, monotime_coarse_get_stamp());
  823. //}
  824. }
  825. /** Either our set of relays or our per-conn rate limits have changed.
  826. * Go through all the OR connections and update their token buckets to make
  827. * sure they don't exceed their maximum values. */
  828. void
  829. connection_or_update_token_buckets(smartlist_t *conns,
  830. const or_options_t *options)
  831. {
  832. SMARTLIST_FOREACH(conns, connection_t *, conn,
  833. {
  834. if (connection_speaks_cells(conn))
  835. connection_or_update_token_buckets_helper(TO_OR_CONN(conn), 0, options);
  836. });
  837. }
  838. /* Mark <b>or_conn</b> as canonical if <b>is_canonical</b> is set, and
  839. * non-canonical otherwise. Adjust idle_timeout accordingly.
  840. */
  841. void
  842. connection_or_set_canonical(or_connection_t *or_conn,
  843. int is_canonical)
  844. {
  845. if (bool_eq(is_canonical, or_conn->is_canonical) &&
  846. or_conn->idle_timeout != 0) {
  847. /* Don't recalculate an existing idle_timeout unless the canonical
  848. * status changed. */
  849. return;
  850. }
  851. or_conn->is_canonical = !! is_canonical; /* force to a 1-bit boolean */
  852. or_conn->idle_timeout = channelpadding_get_channel_idle_timeout(
  853. TLS_CHAN_TO_BASE(or_conn->chan), is_canonical);
  854. log_info(LD_CIRC,
  855. "Channel %"PRIu64 " chose an idle timeout of %d.",
  856. or_conn->chan ?
  857. (TLS_CHAN_TO_BASE(or_conn->chan)->global_identifier):0,
  858. or_conn->idle_timeout);
  859. }
  860. /** If we don't necessarily know the router we're connecting to, but we
  861. * have an addr/port/id_digest, then fill in as much as we can. Start
  862. * by checking to see if this describes a router we know.
  863. * <b>started_here</b> is 1 if we are the initiator of <b>conn</b> and
  864. * 0 if it's an incoming connection. */
  865. void
  866. connection_or_init_conn_from_address(or_connection_t *conn,
  867. const tor_addr_t *addr, uint16_t port,
  868. const char *id_digest,
  869. const ed25519_public_key_t *ed_id,
  870. int started_here)
  871. {
  872. log_debug(LD_HANDSHAKE, "init conn from address %s: %s, %s (%d)",
  873. fmt_addr(addr),
  874. hex_str((const char*)id_digest, DIGEST_LEN),
  875. ed25519_fmt(ed_id),
  876. started_here);
  877. connection_or_set_identity_digest(conn, id_digest, ed_id);
  878. connection_or_update_token_buckets_helper(conn, 1, get_options());
  879. conn->base_.port = port;
  880. tor_addr_copy(&conn->base_.addr, addr);
  881. tor_addr_copy(&conn->real_addr, addr);
  882. connection_or_check_canonicity(conn, started_here);
  883. }
  884. /** Check whether the identity of <b>conn</b> matches a known node. If it
  885. * does, check whether the address of conn matches the expected address, and
  886. * update the connection's is_canonical flag, nickname, and address fields as
  887. * appropriate. */
  888. static void
  889. connection_or_check_canonicity(or_connection_t *conn, int started_here)
  890. {
  891. const char *id_digest = conn->identity_digest;
  892. const ed25519_public_key_t *ed_id = NULL;
  893. const tor_addr_t *addr = &conn->real_addr;
  894. if (conn->chan)
  895. ed_id = & TLS_CHAN_TO_BASE(conn->chan)->ed25519_identity;
  896. const node_t *r = node_get_by_id(id_digest);
  897. if (r &&
  898. node_supports_ed25519_link_authentication(r, 1) &&
  899. ! node_ed25519_id_matches(r, ed_id)) {
  900. /* If this node is capable of proving an ed25519 ID,
  901. * we can't call this a canonical connection unless both IDs match. */
  902. r = NULL;
  903. }
  904. if (r) {
  905. tor_addr_port_t node_ap;
  906. node_get_pref_orport(r, &node_ap);
  907. /* XXXX proposal 186 is making this more complex. For now, a conn
  908. is canonical when it uses the _preferred_ address. */
  909. if (tor_addr_eq(&conn->base_.addr, &node_ap.addr))
  910. connection_or_set_canonical(conn, 1);
  911. if (!started_here) {
  912. /* Override the addr/port, so our log messages will make sense.
  913. * This is dangerous, since if we ever try looking up a conn by
  914. * its actual addr/port, we won't remember. Careful! */
  915. /* XXXX arma: this is stupid, and it's the reason we need real_addr
  916. * to track is_canonical properly. What requires it? */
  917. /* XXXX <arma> i believe the reason we did this, originally, is because
  918. * we wanted to log what OR a connection was to, and if we logged the
  919. * right IP address and port 56244, that wouldn't be as helpful. now we
  920. * log the "right" port too, so we know if it's moria1 or moria2.
  921. */
  922. tor_addr_copy(&conn->base_.addr, &node_ap.addr);
  923. conn->base_.port = node_ap.port;
  924. }
  925. tor_free(conn->nickname);
  926. conn->nickname = tor_strdup(node_get_nickname(r));
  927. tor_free(conn->base_.address);
  928. conn->base_.address = tor_addr_to_str_dup(&node_ap.addr);
  929. } else {
  930. tor_free(conn->nickname);
  931. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  932. conn->nickname[0] = '$';
  933. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  934. conn->identity_digest, DIGEST_LEN);
  935. tor_free(conn->base_.address);
  936. conn->base_.address = tor_addr_to_str_dup(addr);
  937. }
  938. /*
  939. * We have to tell channeltls.c to update the channel marks (local, in
  940. * particular), since we may have changed the address.
  941. */
  942. if (conn->chan) {
  943. channel_tls_update_marks(conn);
  944. }
  945. }
  946. /** These just pass all the is_bad_for_new_circs manipulation on to
  947. * channel_t */
  948. static unsigned int
  949. connection_or_is_bad_for_new_circs(or_connection_t *or_conn)
  950. {
  951. tor_assert(or_conn);
  952. if (or_conn->chan)
  953. return channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
  954. else return 0;
  955. }
  956. static void
  957. connection_or_mark_bad_for_new_circs(or_connection_t *or_conn)
  958. {
  959. tor_assert(or_conn);
  960. if (or_conn->chan)
  961. channel_mark_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
  962. }
  963. /** How old do we let a connection to an OR get before deciding it's
  964. * too old for new circuits? */
  965. #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
  966. /** Expire an or_connection if it is too old. Helper for
  967. * connection_or_group_set_badness_ and fast path for
  968. * channel_rsa_id_group_set_badness.
  969. *
  970. * Returns 1 if the connection was already expired, else 0.
  971. */
  972. int
  973. connection_or_single_set_badness_(time_t now,
  974. or_connection_t *or_conn,
  975. int force)
  976. {
  977. /* XXXX this function should also be about channels? */
  978. if (or_conn->base_.marked_for_close ||
  979. connection_or_is_bad_for_new_circs(or_conn))
  980. return 1;
  981. if (force ||
  982. or_conn->base_.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
  983. < now) {
  984. log_info(LD_OR,
  985. "Marking OR conn to %s:%d as too old for new circuits "
  986. "(fd "TOR_SOCKET_T_FORMAT", %d secs old).",
  987. or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
  988. (int)(now - or_conn->base_.timestamp_created));
  989. connection_or_mark_bad_for_new_circs(or_conn);
  990. }
  991. return 0;
  992. }
  993. /** Given a list of all the or_connections with a given
  994. * identity, set elements of that list as is_bad_for_new_circs as
  995. * appropriate. Helper for connection_or_set_bad_connections().
  996. *
  997. * Specifically, we set the is_bad_for_new_circs flag on:
  998. * - all connections if <b>force</b> is true.
  999. * - all connections that are too old.
  1000. * - all open non-canonical connections for which a canonical connection
  1001. * exists to the same router.
  1002. * - all open canonical connections for which a 'better' canonical
  1003. * connection exists to the same router.
  1004. * - all open non-canonical connections for which a 'better' non-canonical
  1005. * connection exists to the same router at the same address.
  1006. *
  1007. * See channel_is_better() in channel.c for our idea of what makes one OR
  1008. * connection better than another.
  1009. */
  1010. void
  1011. connection_or_group_set_badness_(smartlist_t *group, int force)
  1012. {
  1013. /* XXXX this function should be entirely about channels, not OR
  1014. * XXXX connections. */
  1015. or_connection_t *best = NULL;
  1016. int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
  1017. time_t now = time(NULL);
  1018. /* Pass 1: expire everything that's old, and see what the status of
  1019. * everything else is. */
  1020. SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
  1021. if (connection_or_single_set_badness_(now, or_conn, force))
  1022. continue;
  1023. if (connection_or_is_bad_for_new_circs(or_conn)) {
  1024. ++n_old;
  1025. } else if (or_conn->base_.state != OR_CONN_STATE_OPEN) {
  1026. ++n_inprogress;
  1027. } else if (or_conn->is_canonical) {
  1028. ++n_canonical;
  1029. } else {
  1030. ++n_other;
  1031. }
  1032. } SMARTLIST_FOREACH_END(or_conn);
  1033. /* Pass 2: We know how about how good the best connection is.
  1034. * expire everything that's worse, and find the very best if we can. */
  1035. SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
  1036. if (or_conn->base_.marked_for_close ||
  1037. connection_or_is_bad_for_new_circs(or_conn))
  1038. continue; /* This one doesn't need to be marked bad. */
  1039. if (or_conn->base_.state != OR_CONN_STATE_OPEN)
  1040. continue; /* Don't mark anything bad until we have seen what happens
  1041. * when the connection finishes. */
  1042. if (n_canonical && !or_conn->is_canonical) {
  1043. /* We have at least one open canonical connection to this router,
  1044. * and this one is open but not canonical. Mark it bad. */
  1045. log_info(LD_OR,
  1046. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  1047. "(fd "TOR_SOCKET_T_FORMAT", %d secs old). It is not "
  1048. "canonical, and we have another connection to that OR that is.",
  1049. or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
  1050. (int)(now - or_conn->base_.timestamp_created));
  1051. connection_or_mark_bad_for_new_circs(or_conn);
  1052. continue;
  1053. }
  1054. if (!best ||
  1055. channel_is_better(TLS_CHAN_TO_BASE(or_conn->chan),
  1056. TLS_CHAN_TO_BASE(best->chan))) {
  1057. best = or_conn;
  1058. }
  1059. } SMARTLIST_FOREACH_END(or_conn);
  1060. if (!best)
  1061. return;
  1062. /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
  1063. * every other open connection. If it's non-canonical, mark as bad
  1064. * every other open connection to the same address.
  1065. *
  1066. * XXXX This isn't optimal; if we have connections to an OR at multiple
  1067. * addresses, we'd like to pick the best _for each address_, and mark as
  1068. * bad every open connection that isn't best for its address. But this
  1069. * can only occur in cases where the other OR is old (so we have no
  1070. * canonical connection to it), or where all the connections to the OR are
  1071. * at noncanonical addresses and we have no good direct connection (which
  1072. * means we aren't at risk of attaching circuits to it anyway). As
  1073. * 0.1.2.x dies out, the first case will go away, and the second one is
  1074. * "mostly harmless", so a fix can wait until somebody is bored.
  1075. */
  1076. SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
  1077. if (or_conn->base_.marked_for_close ||
  1078. connection_or_is_bad_for_new_circs(or_conn) ||
  1079. or_conn->base_.state != OR_CONN_STATE_OPEN)
  1080. continue;
  1081. if (or_conn != best &&
  1082. channel_is_better(TLS_CHAN_TO_BASE(best->chan),
  1083. TLS_CHAN_TO_BASE(or_conn->chan))) {
  1084. /* This isn't the best conn, _and_ the best conn is better than it */
  1085. if (best->is_canonical) {
  1086. log_info(LD_OR,
  1087. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  1088. "(fd "TOR_SOCKET_T_FORMAT", %d secs old). "
  1089. "We have a better canonical one "
  1090. "(fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
  1091. or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
  1092. (int)(now - or_conn->base_.timestamp_created),
  1093. best->base_.s, (int)(now - best->base_.timestamp_created));
  1094. connection_or_mark_bad_for_new_circs(or_conn);
  1095. } else if (!tor_addr_compare(&or_conn->real_addr,
  1096. &best->real_addr, CMP_EXACT)) {
  1097. log_info(LD_OR,
  1098. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  1099. "(fd "TOR_SOCKET_T_FORMAT", %d secs old). We have a better "
  1100. "one with the "
  1101. "same address (fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
  1102. or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
  1103. (int)(now - or_conn->base_.timestamp_created),
  1104. best->base_.s, (int)(now - best->base_.timestamp_created));
  1105. connection_or_mark_bad_for_new_circs(or_conn);
  1106. }
  1107. }
  1108. } SMARTLIST_FOREACH_END(or_conn);
  1109. }
  1110. /* Lifetime of a connection failure. After that, we'll retry. This is in
  1111. * seconds. */
  1112. #define OR_CONNECT_FAILURE_LIFETIME 60
  1113. /* The interval to use with when to clean up the failure cache. */
  1114. #define OR_CONNECT_FAILURE_CLEANUP_INTERVAL 60
  1115. /* When is the next time we have to cleanup the failure map. We keep this
  1116. * because we clean it opportunistically. */
  1117. static time_t or_connect_failure_map_next_cleanup_ts = 0;
  1118. /* OR connection failure entry data structure. It is kept in the connection
  1119. * failure map defined below and indexed by OR identity digest, address and
  1120. * port.
  1121. *
  1122. * We need to identify a connection failure with these three values because we
  1123. * want to avoid to wrongfully blacklist a relay if someone is trying to
  1124. * extend to a known identity digest but with the wrong IP/port. For instance,
  1125. * it can happen if a relay changed its port but the client still has an old
  1126. * descriptor with the old port. We want to stop connecting to that
  1127. * IP/port/identity all together, not only the relay identity. */
  1128. typedef struct or_connect_failure_entry_t {
  1129. HT_ENTRY(or_connect_failure_entry_t) node;
  1130. /* Identity digest of the connection where it is connecting to. */
  1131. uint8_t identity_digest[DIGEST_LEN];
  1132. /* This is the connection address from the base connection_t. After the
  1133. * connection is checked for canonicity, the base address should represent
  1134. * what we know instead of where we are connecting to. This is what we need
  1135. * so we can correlate known relays within the consensus. */
  1136. tor_addr_t addr;
  1137. uint16_t port;
  1138. /* Last time we were unable to connect. */
  1139. time_t last_failed_connect_ts;
  1140. } or_connect_failure_entry_t;
  1141. /* Map where we keep connection failure entries. They are indexed by addr,
  1142. * port and identity digest. */
  1143. static HT_HEAD(or_connect_failure_ht, or_connect_failure_entry_t)
  1144. or_connect_failures_map = HT_INITIALIZER();
  1145. /* Helper: Hashtable equal function. Return 1 if equal else 0. */
  1146. static int
  1147. or_connect_failure_ht_eq(const or_connect_failure_entry_t *a,
  1148. const or_connect_failure_entry_t *b)
  1149. {
  1150. return fast_memeq(a->identity_digest, b->identity_digest, DIGEST_LEN) &&
  1151. tor_addr_eq(&a->addr, &b->addr) &&
  1152. a->port == b->port;
  1153. }
  1154. /* Helper: Return the hash for the hashtable of the given entry. For this
  1155. * table, it is a combination of address, port and identity digest. */
  1156. static unsigned int
  1157. or_connect_failure_ht_hash(const or_connect_failure_entry_t *entry)
  1158. {
  1159. size_t offset = 0, addr_size;
  1160. const void *addr_ptr;
  1161. /* Largest size is IPv6 and IPv4 is smaller so it is fine. */
  1162. uint8_t data[16 + sizeof(uint16_t) + DIGEST_LEN];
  1163. /* Get the right address bytes depending on the family. */
  1164. switch (tor_addr_family(&entry->addr)) {
  1165. case AF_INET:
  1166. addr_size = 4;
  1167. addr_ptr = &entry->addr.addr.in_addr.s_addr;
  1168. break;
  1169. case AF_INET6:
  1170. addr_size = 16;
  1171. addr_ptr = &entry->addr.addr.in6_addr.s6_addr;
  1172. break;
  1173. default:
  1174. tor_assert_nonfatal_unreached();
  1175. return 0;
  1176. }
  1177. memcpy(data, addr_ptr, addr_size);
  1178. offset += addr_size;
  1179. memcpy(data + offset, entry->identity_digest, DIGEST_LEN);
  1180. offset += DIGEST_LEN;
  1181. set_uint16(data + offset, entry->port);
  1182. offset += sizeof(uint16_t);
  1183. return (unsigned int) siphash24g(data, offset);
  1184. }
  1185. HT_PROTOTYPE(or_connect_failure_ht, or_connect_failure_entry_t, node,
  1186. or_connect_failure_ht_hash, or_connect_failure_ht_eq)
  1187. HT_GENERATE2(or_connect_failure_ht, or_connect_failure_entry_t, node,
  1188. or_connect_failure_ht_hash, or_connect_failure_ht_eq,
  1189. 0.6, tor_reallocarray_, tor_free_)
  1190. /* Initialize a given connect failure entry with the given identity_digest,
  1191. * addr and port. All field are optional except ocf. */
  1192. static void
  1193. or_connect_failure_init(const char *identity_digest, const tor_addr_t *addr,
  1194. uint16_t port, or_connect_failure_entry_t *ocf)
  1195. {
  1196. tor_assert(ocf);
  1197. if (identity_digest) {
  1198. memcpy(ocf->identity_digest, identity_digest,
  1199. sizeof(ocf->identity_digest));
  1200. }
  1201. if (addr) {
  1202. tor_addr_copy(&ocf->addr, addr);
  1203. }
  1204. ocf->port = port;
  1205. }
  1206. /* Return a newly allocated connection failure entry. It is initialized with
  1207. * the given or_conn data. This can't fail. */
  1208. static or_connect_failure_entry_t *
  1209. or_connect_failure_new(const or_connection_t *or_conn)
  1210. {
  1211. or_connect_failure_entry_t *ocf = tor_malloc_zero(sizeof(*ocf));
  1212. or_connect_failure_init(or_conn->identity_digest, &or_conn->real_addr,
  1213. TO_CONN(or_conn)->port, ocf);
  1214. return ocf;
  1215. }
  1216. /* Return a connection failure entry matching the given or_conn. NULL is
  1217. * returned if not found. */
  1218. static or_connect_failure_entry_t *
  1219. or_connect_failure_find(const or_connection_t *or_conn)
  1220. {
  1221. or_connect_failure_entry_t lookup;
  1222. tor_assert(or_conn);
  1223. or_connect_failure_init(or_conn->identity_digest, &TO_CONN(or_conn)->addr,
  1224. TO_CONN(or_conn)->port, &lookup);
  1225. return HT_FIND(or_connect_failure_ht, &or_connect_failures_map, &lookup);
  1226. }
  1227. /* Note down in the connection failure cache that a failure occurred on the
  1228. * given or_conn. */
  1229. STATIC void
  1230. note_or_connect_failed(const or_connection_t *or_conn)
  1231. {
  1232. or_connect_failure_entry_t *ocf = NULL;
  1233. tor_assert(or_conn);
  1234. ocf = or_connect_failure_find(or_conn);
  1235. if (ocf == NULL) {
  1236. ocf = or_connect_failure_new(or_conn);
  1237. HT_INSERT(or_connect_failure_ht, &or_connect_failures_map, ocf);
  1238. }
  1239. ocf->last_failed_connect_ts = approx_time();
  1240. }
  1241. /* Cleanup the connection failure cache and remove all entries below the
  1242. * given cutoff. */
  1243. static void
  1244. or_connect_failure_map_cleanup(time_t cutoff)
  1245. {
  1246. or_connect_failure_entry_t **ptr, **next, *entry;
  1247. for (ptr = HT_START(or_connect_failure_ht, &or_connect_failures_map);
  1248. ptr != NULL; ptr = next) {
  1249. entry = *ptr;
  1250. if (entry->last_failed_connect_ts <= cutoff) {
  1251. next = HT_NEXT_RMV(or_connect_failure_ht, &or_connect_failures_map, ptr);
  1252. tor_free(entry);
  1253. } else {
  1254. next = HT_NEXT(or_connect_failure_ht, &or_connect_failures_map, ptr);
  1255. }
  1256. }
  1257. }
  1258. /* Return true iff the given OR connection can connect to its destination that
  1259. * is the triplet identity_digest, address and port.
  1260. *
  1261. * The or_conn MUST have gone through connection_or_check_canonicity() so the
  1262. * base address is properly set to what we know or doesn't know. */
  1263. STATIC int
  1264. should_connect_to_relay(const or_connection_t *or_conn)
  1265. {
  1266. time_t now, cutoff;
  1267. time_t connect_failed_since_ts = 0;
  1268. or_connect_failure_entry_t *ocf;
  1269. tor_assert(or_conn);
  1270. now = approx_time();
  1271. cutoff = now - OR_CONNECT_FAILURE_LIFETIME;
  1272. /* Opportunistically try to cleanup the failure cache. We do that at regular
  1273. * interval so it doesn't grow too big. */
  1274. if (or_connect_failure_map_next_cleanup_ts <= now) {
  1275. or_connect_failure_map_cleanup(cutoff);
  1276. or_connect_failure_map_next_cleanup_ts =
  1277. now + OR_CONNECT_FAILURE_CLEANUP_INTERVAL;
  1278. }
  1279. /* Look if we have failed previously to the same destination as this
  1280. * OR connection. */
  1281. ocf = or_connect_failure_find(or_conn);
  1282. if (ocf) {
  1283. connect_failed_since_ts = ocf->last_failed_connect_ts;
  1284. }
  1285. /* If we do have an unable to connect timestamp and it is below cutoff, we
  1286. * can connect. Or we have never failed before so let it connect. */
  1287. if (connect_failed_since_ts > cutoff) {
  1288. goto no_connect;
  1289. }
  1290. /* Ok we can connect! */
  1291. return 1;
  1292. no_connect:
  1293. return 0;
  1294. }
  1295. /** <b>conn</b> is in the 'connecting' state, and it failed to complete
  1296. * a TCP connection. Send notifications appropriately.
  1297. *
  1298. * <b>reason</b> specifies the or_conn_end_reason for the failure;
  1299. * <b>msg</b> specifies the strerror-style error message.
  1300. */
  1301. void
  1302. connection_or_connect_failed(or_connection_t *conn,
  1303. int reason, const char *msg)
  1304. {
  1305. connection_or_event_status(conn, OR_CONN_EVENT_FAILED, reason);
  1306. if (!authdir_mode_tests_reachability(get_options()))
  1307. control_event_bootstrap_prob_or(msg, reason, conn);
  1308. note_or_connect_failed(conn);
  1309. }
  1310. /** <b>conn</b> got an error in connection_handle_read_impl() or
  1311. * connection_handle_write_impl() and is going to die soon.
  1312. *
  1313. * <b>reason</b> specifies the or_conn_end_reason for the failure;
  1314. * <b>msg</b> specifies the strerror-style error message.
  1315. */
  1316. void
  1317. connection_or_notify_error(or_connection_t *conn,
  1318. int reason, const char *msg)
  1319. {
  1320. channel_t *chan;
  1321. tor_assert(conn);
  1322. /* If we're connecting, call connect_failed() too */
  1323. if (TO_CONN(conn)->state == OR_CONN_STATE_CONNECTING)
  1324. connection_or_connect_failed(conn, reason, msg);
  1325. /* Tell the controlling channel if we have one */
  1326. if (conn->chan) {
  1327. chan = TLS_CHAN_TO_BASE(conn->chan);
  1328. /* Don't transition if we're already in closing, closed or error */
  1329. if (!CHANNEL_CONDEMNED(chan)) {
  1330. channel_close_for_error(chan);
  1331. }
  1332. }
  1333. /* No need to mark for error because connection.c is about to do that */
  1334. }
  1335. /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
  1336. * handshake with an OR with identity digest <b>id_digest</b>. Optionally,
  1337. * pass in a pointer to a channel using this connection.
  1338. *
  1339. * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
  1340. * return that connection. If the connect() is in progress, set the
  1341. * new conn's state to 'connecting' and return it. If connect() succeeds,
  1342. * call connection_tls_start_handshake() on it.
  1343. *
  1344. * This function is called from router_retry_connections(), for
  1345. * ORs connecting to ORs, and circuit_establish_circuit(), for
  1346. * OPs connecting to ORs.
  1347. *
  1348. * Return the launched conn, or NULL if it failed.
  1349. */
  1350. MOCK_IMPL(or_connection_t *,
  1351. connection_or_connect, (const tor_addr_t *_addr, uint16_t port,
  1352. const char *id_digest,
  1353. const ed25519_public_key_t *ed_id,
  1354. channel_tls_t *chan))
  1355. {
  1356. or_connection_t *conn;
  1357. const or_options_t *options = get_options();
  1358. int socket_error = 0;
  1359. tor_addr_t addr;
  1360. int r;
  1361. tor_addr_t proxy_addr;
  1362. uint16_t proxy_port;
  1363. int proxy_type, is_pt = 0;
  1364. tor_assert(_addr);
  1365. tor_assert(id_digest);
  1366. tor_addr_copy(&addr, _addr);
  1367. if (server_mode(options) && router_digest_is_me(id_digest)) {
  1368. log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
  1369. return NULL;
  1370. }
  1371. if (server_mode(options) && router_ed25519_id_is_me(ed_id)) {
  1372. log_info(LD_PROTOCOL,"Client asked me to connect to myself by Ed25519 "
  1373. "identity. Refusing.");
  1374. return NULL;
  1375. }
  1376. conn = or_connection_new(CONN_TYPE_OR, tor_addr_family(&addr));
  1377. safe_or_connection_t *safe_or_conn;
  1378. safe_or_conn = safe_or_connection_new(true, true, TO_CONN(conn)->address);
  1379. TO_CONN(conn)->safe_conn = TO_SAFE_CONN(safe_or_conn);
  1380. safe_connection_subscribe(TO_CONN(conn)->safe_conn,
  1381. TO_CONN(conn)->event_listener,
  1382. safe_or_conn_tcp_connecting_ev, true);
  1383. safe_connection_subscribe(TO_CONN(conn)->safe_conn,
  1384. TO_CONN(conn)->event_listener,
  1385. safe_or_conn_tls_handshaking_ev, true);
  1386. safe_connection_subscribe(TO_CONN(conn)->safe_conn,
  1387. TO_CONN(conn)->event_listener,
  1388. safe_or_conn_link_handshaking_ev, true);
  1389. safe_connection_subscribe(TO_CONN(conn)->safe_conn,
  1390. TO_CONN(conn)->event_listener,
  1391. safe_or_conn_open_ev, true);
  1392. safe_connection_subscribe(TO_CONN(conn)->safe_conn,
  1393. TO_CONN(conn)->event_listener,
  1394. safe_or_conn_closed_ev, true);
  1395. safe_connection_subscribe(TO_CONN(conn)->safe_conn,
  1396. TO_CONN(conn)->event_listener,
  1397. safe_or_conn_has_buffered_data_ev, false);
  1398. /*
  1399. * Set up conn so it's got all the data we need to remember for channels
  1400. *
  1401. * This stuff needs to happen before connection_or_init_conn_from_address()
  1402. * so connection_or_set_identity_digest() and such know where to look to
  1403. * keep the channel up to date.
  1404. */
  1405. conn->chan = chan;
  1406. chan->conn = conn;
  1407. connection_or_init_conn_from_address(conn, &addr, port, id_digest, ed_id, 1);
  1408. /* We have a proper OR connection setup, now check if we can connect to it
  1409. * that is we haven't had a failure earlier. This is to avoid to try to
  1410. * constantly connect to relays that we think are not reachable. */
  1411. if (!should_connect_to_relay(conn)) {
  1412. log_info(LD_GENERAL, "Can't connect to identity %s at %s:%u because we "
  1413. "failed earlier. Refusing.",
  1414. hex_str(id_digest, DIGEST_LEN), fmt_addr(&TO_CONN(conn)->addr),
  1415. TO_CONN(conn)->port);
  1416. connection_free_(TO_CONN(conn));
  1417. return NULL;
  1418. }
  1419. conn->is_outgoing = 1;
  1420. /* If we are using a proxy server, find it and use it. */
  1421. r = get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, &is_pt,
  1422. TO_CONN(conn));
  1423. if (r == 0) {
  1424. conn->proxy_type = proxy_type;
  1425. if (proxy_type != PROXY_NONE) {
  1426. tor_addr_copy(&addr, &proxy_addr);
  1427. port = proxy_port;
  1428. conn->base_.proxy_state = PROXY_INFANT;
  1429. conn->is_pt = is_pt;
  1430. }
  1431. connection_or_change_state(conn, OR_CONN_STATE_CONNECTING);
  1432. connection_or_event_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
  1433. } else {
  1434. /* This duplication of state change calls is necessary in case we
  1435. * run into an error condition below */
  1436. connection_or_change_state(conn, OR_CONN_STATE_CONNECTING);
  1437. connection_or_event_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
  1438. /* get_proxy_addrport() might fail if we have a Bridge line that
  1439. references a transport, but no ClientTransportPlugin lines
  1440. defining its transport proxy. If this is the case, let's try to
  1441. output a useful log message to the user. */
  1442. const char *transport_name =
  1443. find_transport_name_by_bridge_addrport(&TO_CONN(conn)->addr,
  1444. TO_CONN(conn)->port);
  1445. if (transport_name) {
  1446. log_warn(LD_GENERAL, "We were supposed to connect to bridge '%s' "
  1447. "using pluggable transport '%s', but we can't find a pluggable "
  1448. "transport proxy supporting '%s'. This can happen if you "
  1449. "haven't provided a ClientTransportPlugin line, or if "
  1450. "your pluggable transport proxy stopped running.",
  1451. fmt_addrport(&TO_CONN(conn)->addr, TO_CONN(conn)->port),
  1452. transport_name, transport_name);
  1453. control_event_bootstrap_prob_or(
  1454. "Can't connect to bridge",
  1455. END_OR_CONN_REASON_PT_MISSING,
  1456. conn);
  1457. } else {
  1458. log_warn(LD_GENERAL, "Tried to connect to '%s' through a proxy, but "
  1459. "the proxy address could not be found.",
  1460. fmt_addrport(&TO_CONN(conn)->addr, TO_CONN(conn)->port));
  1461. }
  1462. connection_free_(TO_CONN(conn));
  1463. return NULL;
  1464. }
  1465. switch (connection_connect(TO_CONN(conn), conn->base_.address,
  1466. &addr, port, &socket_error)) {
  1467. case -1:
  1468. /* We failed to establish a connection probably because of a local
  1469. * error. No need to blame the guard in this case. Notify the networking
  1470. * system of this failure. */
  1471. connection_or_connect_failed(conn,
  1472. errno_to_orconn_end_reason(socket_error),
  1473. tor_socket_strerror(socket_error));
  1474. connection_free_(TO_CONN(conn));
  1475. return NULL;
  1476. //case 0:
  1477. // connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
  1478. // /* writable indicates finish, readable indicates broken link,
  1479. // error indicates broken link on windows */
  1480. // return conn;
  1481. /* case 1: fall through */
  1482. }
  1483. tor_assert(conn->proxy_type == PROXY_NONE);
  1484. // we don't support proxy connections yet
  1485. //if (connection_or_finished_connecting(conn) < 0) {
  1486. // /* already marked for close */
  1487. // return NULL;
  1488. //}
  1489. return conn;
  1490. }
  1491. /** Mark orconn for close and transition the associated channel, if any, to
  1492. * the closing state.
  1493. *
  1494. * It's safe to call this and connection_or_close_for_error() any time, and
  1495. * channel layer will treat it as a connection closing for reasons outside
  1496. * its control, like the remote end closing it. It can also be a local
  1497. * reason that's specific to connection_t/or_connection_t rather than
  1498. * the channel mechanism, such as expiration of old connections in
  1499. * run_connection_housekeeping(). If you want to close a channel_t
  1500. * from somewhere that logically works in terms of generic channels
  1501. * rather than connections, use channel_mark_for_close(); see also
  1502. * the comment on that function in channel.c.
  1503. */
  1504. void
  1505. connection_or_close_normally(or_connection_t *orconn, int flush)
  1506. {
  1507. channel_t *chan = NULL;
  1508. tor_assert(orconn);
  1509. if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
  1510. else connection_mark_for_close_internal(TO_CONN(orconn));
  1511. if (orconn->chan) {
  1512. chan = TLS_CHAN_TO_BASE(orconn->chan);
  1513. /* Don't transition if we're already in closing, closed or error */
  1514. if (!CHANNEL_CONDEMNED(chan)) {
  1515. channel_close_from_lower_layer(chan);
  1516. }
  1517. }
  1518. }
  1519. /** Mark orconn for close and transition the associated channel, if any, to
  1520. * the error state.
  1521. */
  1522. MOCK_IMPL(void,
  1523. connection_or_close_for_error,(or_connection_t *orconn, int flush))
  1524. {
  1525. channel_t *chan = NULL;
  1526. tor_assert(orconn);
  1527. if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
  1528. else connection_mark_for_close_internal(TO_CONN(orconn));
  1529. if (orconn->chan) {
  1530. chan = TLS_CHAN_TO_BASE(orconn->chan);
  1531. /* Don't transition if we're already in closing, closed or error */
  1532. if (!CHANNEL_CONDEMNED(chan)) {
  1533. channel_close_for_error(chan);
  1534. }
  1535. }
  1536. }
  1537. /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
  1538. * we initiated the connection, else it's 1.
  1539. *
  1540. * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
  1541. * pass <b>conn</b> to connection_tls_continue_handshake().
  1542. *
  1543. * Return -1 if <b>conn</b> is broken, else return 0.
  1544. */
  1545. //MOCK_IMPL(int,
  1546. //connection_tls_start_handshake,(or_connection_t *conn, int receiving))
  1547. //{
  1548. // tor_assert(conn->chan != NULL);
  1549. // connection_or_change_state(conn, OR_CONN_STATE_TLS_HANDSHAKING);
  1550. // tor_assert(!conn->tls);
  1551. // conn->tls = tor_tls_new(conn->base_.s, receiving);
  1552. // if (!conn->tls) {
  1553. // log_warn(LD_BUG,"tor_tls_new failed. Closing.");
  1554. // return -1;
  1555. // }
  1556. // tor_tls_set_logged_address(conn->tls, // XXX client and relay?
  1557. // escaped_safe_str(conn->base_.address));
  1558. //
  1559. // connection_start_reading(TO_CONN(conn));
  1560. // log_debug(LD_HANDSHAKE,"starting TLS handshake on fd "TOR_SOCKET_T_FORMAT,
  1561. // conn->base_.s);
  1562. //
  1563. // if (connection_tls_continue_handshake(conn) < 0)
  1564. // return -1;
  1565. //
  1566. // return 0;
  1567. //}
  1568. /** Block all future attempts to renegotiate on 'conn' */
  1569. //void
  1570. //connection_or_block_renegotiation(or_connection_t *conn)
  1571. //{
  1572. // tor_tls_t *tls = conn->tls;
  1573. // if (!tls)
  1574. // return;
  1575. // tor_tls_set_renegotiate_callback(tls, NULL, NULL);
  1576. // tor_tls_block_renegotiation(tls);
  1577. //}
  1578. /** Invoked on the server side from inside tor_tls_read() when the server
  1579. * gets a successful TLS renegotiation from the client. */
  1580. //static void
  1581. //connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
  1582. //{
  1583. // or_connection_t *conn = _conn;
  1584. // (void)tls;
  1585. //
  1586. // /* Don't invoke this again. */
  1587. // connection_or_block_renegotiation(conn);
  1588. //
  1589. // if (connection_tls_finish_handshake(conn) < 0) {
  1590. // /* XXXX_TLS double-check that it's ok to do this from inside read. */
  1591. // /* XXXX_TLS double-check that this verifies certificates. */
  1592. // connection_or_close_for_error(conn, 0);
  1593. // }
  1594. //}
  1595. /** Move forward with the tls handshake. If it finishes, hand
  1596. * <b>conn</b> to connection_tls_finish_handshake().
  1597. *
  1598. * Return -1 if <b>conn</b> is broken, else return 0.
  1599. */
  1600. //int
  1601. //connection_tls_continue_handshake(or_connection_t *conn)
  1602. //{
  1603. // int result;
  1604. // check_no_tls_errors();
  1605. //
  1606. // tor_assert(0);
  1607. //
  1608. // tor_assert(conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING);
  1609. // // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
  1610. // result = tor_tls_handshake(conn->tls);
  1611. // // log_notice(LD_OR, "Result: %d", result);
  1612. //
  1613. // switch (result) {
  1614. // CASE_TOR_TLS_ERROR_ANY:
  1615. // log_info(LD_OR,"tls error [%s]. breaking connection.",
  1616. // tor_tls_err_to_string(result));
  1617. // return -1;
  1618. // case TOR_TLS_DONE:
  1619. // if (! tor_tls_used_v1_handshake(conn->tls)) {
  1620. // if (!tor_tls_is_server(conn->tls)) {
  1621. // tor_assert(conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING);
  1622. // return connection_or_launch_v3_or_handshake(conn);
  1623. // } else {
  1624. // /* v2/v3 handshake, but we are not a client. */
  1625. // log_debug(LD_OR, "Done with initial SSL handshake (server-side). "
  1626. // "Expecting renegotiation or VERSIONS cell");
  1627. // tor_tls_set_renegotiate_callback(conn->tls,
  1628. // connection_or_tls_renegotiated_cb,
  1629. // conn);
  1630. // connection_or_change_state(conn,
  1631. // OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
  1632. // connection_stop_writing(TO_CONN(conn));
  1633. // connection_start_reading(TO_CONN(conn));
  1634. // return 0;
  1635. // }
  1636. // }
  1637. // tor_assert(tor_tls_is_server(conn->tls));
  1638. // return connection_tls_finish_handshake(conn);
  1639. // case TOR_TLS_WANTWRITE:
  1640. // connection_start_writing(TO_CONN(conn));
  1641. // log_debug(LD_OR,"wanted write");
  1642. // return 0;
  1643. // case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
  1644. // log_debug(LD_OR,"wanted read");
  1645. // return 0;
  1646. // case TOR_TLS_CLOSE:
  1647. // log_info(LD_OR,"tls closed. breaking connection.");
  1648. // return -1;
  1649. // }
  1650. // return 0;
  1651. //}
  1652. /** Return 1 if we initiated this connection, or 0 if it started
  1653. * out as an incoming connection.
  1654. */
  1655. int
  1656. connection_or_nonopen_was_started_here(or_connection_t *conn)
  1657. {
  1658. tor_assert(conn->base_.type == CONN_TYPE_OR ||
  1659. conn->base_.type == CONN_TYPE_EXT_OR);
  1660. //if (!conn->tls)
  1661. // return 1; /* it's still in proxy states or something */
  1662. if (conn->handshake_state)
  1663. return conn->handshake_state->started_here;
  1664. //return !tor_tls_is_server(conn->tls);
  1665. return conn->is_outgoing; // hopefully this is the same as the above
  1666. }
  1667. /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
  1668. * return -1 if they are lying, broken, or otherwise something is wrong.
  1669. *
  1670. * If we initiated this connection (<b>started_here</b> is true), make sure
  1671. * the other side sent a correctly formed certificate. If I initiated the
  1672. * connection, make sure it's the right relay by checking the certificate.
  1673. *
  1674. * Otherwise (if we _didn't_ initiate this connection), it's okay for
  1675. * the certificate to be weird or absent.
  1676. *
  1677. * If we return 0, and the certificate is as expected, write a hash of the
  1678. * identity key into <b>digest_rcvd_out</b>, which must have DIGEST_LEN
  1679. * space in it.
  1680. * If the certificate is invalid or missing on an incoming connection,
  1681. * we return 0 and set <b>digest_rcvd_out</b> to DIGEST_LEN NUL bytes.
  1682. * (If we return -1, the contents of this buffer are undefined.)
  1683. *
  1684. * As side effects,
  1685. * 1) Set conn->circ_id_type according to tor-spec.txt.
  1686. * 2) If we're an authdirserver and we initiated the connection: drop all
  1687. * descriptors that claim to be on that IP/port but that aren't
  1688. * this relay; and note that this relay is reachable.
  1689. * 3) If this is a bridge and we didn't configure its identity
  1690. * fingerprint, remember the keyid we just learned.
  1691. */
  1692. //static int
  1693. //connection_or_check_valid_tls_handshake(or_connection_t *conn,
  1694. // int started_here,
  1695. // char *digest_rcvd_out)
  1696. //{
  1697. // crypto_pk_t *identity_rcvd=NULL;
  1698. // const or_options_t *options = get_options();
  1699. // int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
  1700. // const char *safe_address =
  1701. // started_here ? conn->base_.address :
  1702. // safe_str_client(conn->base_.address);
  1703. // const char *conn_type = started_here ? "outgoing" : "incoming";
  1704. // int has_cert = 0;
  1705. //
  1706. // check_no_tls_errors();
  1707. // has_cert = tor_tls_peer_has_cert(conn->tls);
  1708. // if (started_here && !has_cert) {
  1709. // log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
  1710. // "send a cert! Closing.",
  1711. // safe_address, conn->base_.port);
  1712. // return -1;
  1713. // } else if (!has_cert) {
  1714. // log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
  1715. // "That's ok.");
  1716. // }
  1717. // check_no_tls_errors();
  1718. //
  1719. // if (has_cert) {
  1720. // int v = tor_tls_verify(started_here?severity:LOG_INFO,
  1721. // conn->tls, &identity_rcvd);
  1722. // if (started_here && v<0) {
  1723. // log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
  1724. // " has a cert but it's invalid. Closing.",
  1725. // safe_address, conn->base_.port);
  1726. // return -1;
  1727. // } else if (v<0) {
  1728. // log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
  1729. // "chain; ignoring.");
  1730. // } else {
  1731. // log_debug(LD_HANDSHAKE,
  1732. // "The certificate seems to be valid on %s connection "
  1733. // "with %s:%d", conn_type, safe_address, conn->base_.port);
  1734. // }
  1735. // check_no_tls_errors();
  1736. // }
  1737. //
  1738. // if (identity_rcvd) {
  1739. // if (crypto_pk_get_digest(identity_rcvd, digest_rcvd_out) < 0) {
  1740. // crypto_pk_free(identity_rcvd);
  1741. // return -1;
  1742. // }
  1743. // } else {
  1744. // memset(digest_rcvd_out, 0, DIGEST_LEN);
  1745. // }
  1746. //
  1747. // tor_assert(conn->chan);
  1748. // channel_set_circid_type(TLS_CHAN_TO_BASE(conn->chan), identity_rcvd, 1);
  1749. //
  1750. // crypto_pk_free(identity_rcvd);
  1751. //
  1752. // if (started_here) {
  1753. // /* A TLS handshake can't teach us an Ed25519 ID, so we set it to NULL
  1754. // * here. */
  1755. // log_debug(LD_HANDSHAKE, "Calling client_learned_peer_id from "
  1756. // "check_valid_tls_handshake");
  1757. // return connection_or_client_learned_peer_id(conn,
  1758. // (const uint8_t*)digest_rcvd_out,
  1759. // NULL);
  1760. // }
  1761. //
  1762. // return 0;
  1763. //}
  1764. /** Called when we (as a connection initiator) have definitively,
  1765. * authenticatedly, learned that ID of the Tor instance on the other
  1766. * side of <b>conn</b> is <b>rsa_peer_id</b> and optionally <b>ed_peer_id</b>.
  1767. * For v1 and v2 handshakes,
  1768. * this is right after we get a certificate chain in a TLS handshake
  1769. * or renegotiation. For v3+ handshakes, this is right after we get a
  1770. * certificate chain in a CERTS cell.
  1771. *
  1772. * If we did not know the ID before, record the one we got.
  1773. *
  1774. * If we wanted an ID, but we didn't get the one we expected, log a message
  1775. * and return -1.
  1776. * On relays:
  1777. * - log a protocol warning whenever the fingerprints don't match;
  1778. * On clients:
  1779. * - if a relay's fingerprint doesn't match, log a warning;
  1780. * - if we don't have updated relay fingerprints from a recent consensus, and
  1781. * a fallback directory mirror's hard-coded fingerprint has changed, log an
  1782. * info explaining that we will try another fallback.
  1783. *
  1784. * If we're testing reachability, remember what we learned.
  1785. *
  1786. * Return 0 on success, -1 on failure.
  1787. */
  1788. int
  1789. connection_or_client_learned_peer_id(or_connection_t *conn,
  1790. const uint8_t *rsa_peer_id,
  1791. const ed25519_public_key_t *ed_peer_id)
  1792. {
  1793. const or_options_t *options = get_options();
  1794. channel_tls_t *chan_tls = conn->chan;
  1795. channel_t *chan = channel_tls_to_base(chan_tls);
  1796. int changed_identity = 0;
  1797. tor_assert(chan);
  1798. const int expected_rsa_key =
  1799. ! tor_digest_is_zero(conn->identity_digest);
  1800. const int expected_ed_key =
  1801. ! ed25519_public_key_is_zero(&chan->ed25519_identity);
  1802. log_info(LD_HANDSHAKE, "learned peer id for %p (%s): %s, %s",
  1803. conn,
  1804. safe_str_client(conn->base_.address),
  1805. hex_str((const char*)rsa_peer_id, DIGEST_LEN),
  1806. ed25519_fmt(ed_peer_id));
  1807. if (! expected_rsa_key && ! expected_ed_key) {
  1808. log_info(LD_HANDSHAKE, "(we had no ID in mind when we made this "
  1809. "connection.");
  1810. connection_or_set_identity_digest(conn,
  1811. (const char*)rsa_peer_id, ed_peer_id);
  1812. tor_free(conn->nickname);
  1813. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  1814. conn->nickname[0] = '$';
  1815. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  1816. conn->identity_digest, DIGEST_LEN);
  1817. log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
  1818. "its key. Hoping for the best.",
  1819. conn->nickname, conn->base_.address, conn->base_.port);
  1820. /* if it's a bridge and we didn't know its identity fingerprint, now
  1821. * we do -- remember it for future attempts. */
  1822. learned_router_identity(&conn->base_.addr, conn->base_.port,
  1823. (const char*)rsa_peer_id, ed_peer_id);
  1824. changed_identity = 1;
  1825. }
  1826. const int rsa_mismatch = expected_rsa_key &&
  1827. tor_memneq(rsa_peer_id, conn->identity_digest, DIGEST_LEN);
  1828. /* It only counts as an ed25519 mismatch if we wanted an ed25519 identity
  1829. * and didn't get it. It's okay if we get one that we didn't ask for. */
  1830. const int ed25519_mismatch =
  1831. expected_ed_key &&
  1832. (ed_peer_id == NULL ||
  1833. ! ed25519_pubkey_eq(&chan->ed25519_identity, ed_peer_id));
  1834. if (rsa_mismatch || ed25519_mismatch) {
  1835. /* I was aiming for a particular digest. I didn't get it! */
  1836. char seen_rsa[HEX_DIGEST_LEN+1];
  1837. char expected_rsa[HEX_DIGEST_LEN+1];
  1838. char seen_ed[ED25519_BASE64_LEN+1];
  1839. char expected_ed[ED25519_BASE64_LEN+1];
  1840. base16_encode(seen_rsa, sizeof(seen_rsa),
  1841. (const char*)rsa_peer_id, DIGEST_LEN);
  1842. base16_encode(expected_rsa, sizeof(expected_rsa), conn->identity_digest,
  1843. DIGEST_LEN);
  1844. if (ed_peer_id) {
  1845. ed25519_public_to_base64(seen_ed, ed_peer_id);
  1846. } else {
  1847. strlcpy(seen_ed, "no ed25519 key", sizeof(seen_ed));
  1848. }
  1849. if (! ed25519_public_key_is_zero(&chan->ed25519_identity)) {
  1850. ed25519_public_to_base64(expected_ed, &chan->ed25519_identity);
  1851. } else {
  1852. strlcpy(expected_ed, "no ed25519 key", sizeof(expected_ed));
  1853. }
  1854. const int using_hardcoded_fingerprints =
  1855. !networkstatus_get_reasonably_live_consensus(time(NULL),
  1856. usable_consensus_flavor());
  1857. const int is_fallback_fingerprint = router_digest_is_fallback_dir(
  1858. conn->identity_digest);
  1859. const int is_authority_fingerprint = router_digest_is_trusted_dir(
  1860. conn->identity_digest);
  1861. const int non_anonymous_mode = rend_non_anonymous_mode_enabled(options);
  1862. int severity;
  1863. const char *extra_log = "";
  1864. /* Relays and Single Onion Services make direct connections using
  1865. * untrusted authentication keys. */
  1866. if (server_mode(options) || non_anonymous_mode) {
  1867. severity = LOG_PROTOCOL_WARN;
  1868. } else {
  1869. if (using_hardcoded_fingerprints) {
  1870. /* We need to do the checks in this order, because the list of
  1871. * fallbacks includes the list of authorities */
  1872. if (is_authority_fingerprint) {
  1873. severity = LOG_WARN;
  1874. } else if (is_fallback_fingerprint) {
  1875. /* we expect a small number of fallbacks to change from their
  1876. * hard-coded fingerprints over the life of a release */
  1877. severity = LOG_INFO;
  1878. extra_log = " Tor will try a different fallback.";
  1879. } else {
  1880. /* it's a bridge, it's either a misconfiguration, or unexpected */
  1881. severity = LOG_WARN;
  1882. }
  1883. } else {
  1884. /* a relay has changed its fingerprint from the one in the consensus */
  1885. severity = LOG_WARN;
  1886. }
  1887. }
  1888. log_fn(severity, LD_HANDSHAKE,
  1889. "Tried connecting to router at %s:%d, but RSA + ed25519 identity "
  1890. "keys were not as expected: wanted %s + %s but got %s + %s.%s",
  1891. conn->base_.address, conn->base_.port,
  1892. expected_rsa, expected_ed, seen_rsa, seen_ed, extra_log);
  1893. /* Tell the new guard API about the channel failure */
  1894. entry_guard_chan_failed(TLS_CHAN_TO_BASE(conn->chan));
  1895. connection_or_event_status(conn, OR_CONN_EVENT_FAILED,
  1896. END_OR_CONN_REASON_OR_IDENTITY);
  1897. if (!authdir_mode_tests_reachability(options))
  1898. control_event_bootstrap_prob_or(
  1899. "Unexpected identity in router certificate",
  1900. END_OR_CONN_REASON_OR_IDENTITY,
  1901. conn);
  1902. return -1;
  1903. }
  1904. if (!expected_ed_key && ed_peer_id) {
  1905. log_info(LD_HANDSHAKE, "(We had no Ed25519 ID in mind when we made this "
  1906. "connection.)");
  1907. connection_or_set_identity_digest(conn,
  1908. (const char*)rsa_peer_id, ed_peer_id);
  1909. changed_identity = 1;
  1910. }
  1911. if (changed_identity) {
  1912. /* If we learned an identity for this connection, then we might have
  1913. * just discovered it to be canonical. */
  1914. connection_or_check_canonicity(conn, conn->handshake_state->started_here);
  1915. }
  1916. if (authdir_mode_tests_reachability(options)) {
  1917. dirserv_orconn_tls_done(&conn->base_.addr, conn->base_.port,
  1918. (const char*)rsa_peer_id, ed_peer_id);
  1919. }
  1920. return 0;
  1921. }
  1922. /** Return when we last used this channel for client activity (origin
  1923. * circuits). This is called from connection.c, since client_used is now one
  1924. * of the timestamps in channel_t */
  1925. time_t
  1926. connection_or_client_used(or_connection_t *conn)
  1927. {
  1928. tor_assert(conn);
  1929. if (conn->chan) {
  1930. return channel_when_last_client(TLS_CHAN_TO_BASE(conn->chan));
  1931. } else return 0;
  1932. }
  1933. /** The v1/v2 TLS handshake is finished.
  1934. *
  1935. * Make sure we are happy with the peer we just handshaked with.
  1936. *
  1937. * If they initiated the connection, make sure they're not already connected,
  1938. * then initialize conn from the information in router.
  1939. *
  1940. * If all is successful, call circuit_n_conn_done() to handle events
  1941. * that have been pending on the <tls handshake completion. Also set the
  1942. * directory to be dirty (only matters if I'm an authdirserver).
  1943. *
  1944. * If this is a v2 TLS handshake, send a versions cell.
  1945. */
  1946. //static int
  1947. //connection_tls_finish_handshake(or_connection_t *conn)
  1948. //{
  1949. // char digest_rcvd[DIGEST_LEN];
  1950. // int started_here = connection_or_nonopen_was_started_here(conn);
  1951. //
  1952. // tor_assert(!started_here);
  1953. //
  1954. // log_debug(LD_HANDSHAKE,"%s tls handshake on %p with %s done, using "
  1955. // "ciphersuite %s. verifying.",
  1956. // started_here?"outgoing":"incoming",
  1957. // conn,
  1958. // safe_str_client(conn->base_.address),
  1959. // tor_tls_get_ciphersuite_name(conn->tls));
  1960. //
  1961. // if (connection_or_check_valid_tls_handshake(conn, started_here,
  1962. // digest_rcvd) < 0)
  1963. // return -1;
  1964. //
  1965. // circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  1966. //
  1967. // if (tor_tls_used_v1_handshake(conn->tls)) {
  1968. // conn->link_proto = 1;
  1969. // connection_or_init_conn_from_address(conn, &conn->base_.addr,
  1970. // conn->base_.port, digest_rcvd,
  1971. // NULL, 0);
  1972. // tor_tls_block_renegotiation(conn->tls);
  1973. // rep_hist_note_negotiated_link_proto(1, started_here);
  1974. // return connection_or_set_state_open(conn);
  1975. // } else {
  1976. // connection_or_change_state(conn, OR_CONN_STATE_OR_HANDSHAKING_V2);
  1977. // if (connection_init_or_handshake_state(conn, started_here) < 0)
  1978. // return -1;
  1979. // connection_or_init_conn_from_address(conn, &conn->base_.addr,
  1980. // conn->base_.port, digest_rcvd,
  1981. // NULL, 0);
  1982. // return connection_or_send_versions(conn, 0);
  1983. // }
  1984. //}
  1985. /**
  1986. * Called as client when initial TLS handshake is done, and we notice
  1987. * that we got a v3-handshake signalling certificate from the server.
  1988. * Set up structures, do bookkeeping, and send the versions cell.
  1989. * Return 0 on success and -1 on failure.
  1990. */
  1991. static int
  1992. connection_or_launch_v3_or_handshake(or_connection_t *conn)
  1993. {
  1994. tor_assert(connection_or_nonopen_was_started_here(conn));
  1995. circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  1996. connection_or_change_state(conn, OR_CONN_STATE_OR_HANDSHAKING_V3);
  1997. if (connection_init_or_handshake_state(conn, 1) < 0)
  1998. return -1;
  1999. return connection_or_send_versions(conn, 1);
  2000. }
  2001. /** Allocate a new connection handshake state for the connection
  2002. * <b>conn</b>. Return 0 on success, -1 on failure. */
  2003. int
  2004. connection_init_or_handshake_state(or_connection_t *conn, int started_here)
  2005. {
  2006. or_handshake_state_t *s;
  2007. if (conn->handshake_state) {
  2008. log_warn(LD_BUG, "Duplicate call to connection_init_or_handshake_state!");
  2009. return 0;
  2010. }
  2011. s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
  2012. s->started_here = started_here ? 1 : 0;
  2013. s->digest_sent_data = 1;
  2014. s->digest_received_data = 1;
  2015. if (! started_here && get_current_link_cert_cert()) {
  2016. s->own_link_cert = tor_cert_dup(get_current_link_cert_cert());
  2017. }
  2018. s->certs = or_handshake_certs_new();
  2019. s->certs->started_here = s->started_here;
  2020. return 0;
  2021. }
  2022. /** Free all storage held by <b>state</b>. */
  2023. void
  2024. or_handshake_state_free_(or_handshake_state_t *state)
  2025. {
  2026. if (!state)
  2027. return;
  2028. crypto_digest_free(state->digest_sent);
  2029. crypto_digest_free(state->digest_received);
  2030. or_handshake_certs_free(state->certs);
  2031. tor_cert_free(state->own_link_cert);
  2032. memwipe(state, 0xBE, sizeof(or_handshake_state_t));
  2033. tor_free(state);
  2034. }
  2035. /**
  2036. * Remember that <b>cell</b> has been transmitted (if <b>incoming</b> is
  2037. * false) or received (if <b>incoming</b> is true) during a V3 handshake using
  2038. * <b>state</b>.
  2039. *
  2040. * (We don't record the cell, but we keep a digest of everything sent or
  2041. * received during the v3 handshake, and the client signs it in an
  2042. * authenticate cell.)
  2043. */
  2044. void
  2045. or_handshake_state_record_cell(or_connection_t *conn,
  2046. or_handshake_state_t *state,
  2047. const cell_t *cell,
  2048. int incoming)
  2049. {
  2050. size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
  2051. crypto_digest_t *d, **dptr;
  2052. packed_cell_t packed;
  2053. if (incoming) {
  2054. if (!state->digest_received_data)
  2055. return;
  2056. } else {
  2057. if (!state->digest_sent_data)
  2058. return;
  2059. }
  2060. if (!incoming) {
  2061. log_warn(LD_BUG, "We shouldn't be sending any non-variable-length cells "
  2062. "while making a handshake digest. But we think we are sending "
  2063. "one with type %d.", (int)cell->command);
  2064. }
  2065. dptr = incoming ? &state->digest_received : &state->digest_sent;
  2066. if (! *dptr)
  2067. *dptr = crypto_digest256_new(DIGEST_SHA256);
  2068. d = *dptr;
  2069. /* Re-packing like this is a little inefficient, but we don't have to do
  2070. this very often at all. */
  2071. cell_pack(&packed, cell, conn->wide_circ_ids);
  2072. crypto_digest_add_bytes(d, packed.body, cell_network_size);
  2073. memwipe(&packed, 0, sizeof(packed));
  2074. }
  2075. /** Remember that a variable-length <b>cell</b> has been transmitted (if
  2076. * <b>incoming</b> is false) or received (if <b>incoming</b> is true) during a
  2077. * V3 handshake using <b>state</b>.
  2078. *
  2079. * (We don't record the cell, but we keep a digest of everything sent or
  2080. * received during the v3 handshake, and the client signs it in an
  2081. * authenticate cell.)
  2082. */
  2083. void
  2084. or_handshake_state_record_var_cell(or_connection_t *conn,
  2085. or_handshake_state_t *state,
  2086. const var_cell_t *cell,
  2087. int incoming)
  2088. {
  2089. crypto_digest_t *d, **dptr;
  2090. int n;
  2091. char buf[VAR_CELL_MAX_HEADER_SIZE];
  2092. if (incoming) {
  2093. if (!state->digest_received_data)
  2094. return;
  2095. } else {
  2096. if (!state->digest_sent_data)
  2097. return;
  2098. }
  2099. dptr = incoming ? &state->digest_received : &state->digest_sent;
  2100. if (! *dptr)
  2101. *dptr = crypto_digest256_new(DIGEST_SHA256);
  2102. d = *dptr;
  2103. n = var_cell_pack_header(cell, buf, conn->wide_circ_ids);
  2104. crypto_digest_add_bytes(d, buf, n);
  2105. crypto_digest_add_bytes(d, (const char *)cell->payload, cell->payload_len);
  2106. memwipe(buf, 0, sizeof(buf));
  2107. }
  2108. /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
  2109. * as appropriate. Called when we are done with all TLS and OR handshaking.
  2110. */
  2111. int
  2112. connection_or_set_state_open(or_connection_t *conn)
  2113. {
  2114. connection_or_change_state(conn, OR_CONN_STATE_OPEN);
  2115. connection_or_event_status(conn, OR_CONN_EVENT_CONNECTED, 0);
  2116. /* Link protocol 3 appeared in Tor 0.2.3.6-alpha, so any connection
  2117. * that uses an earlier link protocol should not be treated as a relay. */
  2118. if (conn->link_proto < 3) {
  2119. channel_mark_client(TLS_CHAN_TO_BASE(conn->chan));
  2120. }
  2121. or_handshake_state_free(conn->handshake_state);
  2122. conn->handshake_state = NULL;
  2123. //connection_start_reading(TO_CONN(conn));
  2124. return 0;
  2125. }
  2126. /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
  2127. * For cells that use or affect a circuit, this should only be called by
  2128. * connection_or_flush_from_first_active_circuit().
  2129. */
  2130. void
  2131. connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
  2132. {
  2133. packed_cell_t networkcell;
  2134. size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
  2135. tor_assert(cell);
  2136. tor_assert(conn);
  2137. cell_pack(&networkcell, cell, conn->wide_circ_ids);
  2138. /* We need to count padding cells from this non-packed code path
  2139. * since they are sent via chan->write_cell() (which is not packed) */
  2140. rep_hist_padding_count_write(PADDING_TYPE_TOTAL);
  2141. if (cell->command == CELL_PADDING)
  2142. rep_hist_padding_count_write(PADDING_TYPE_CELL);
  2143. connection_buf_add(networkcell.body, cell_network_size, TO_CONN(conn));
  2144. /* Touch the channel's active timestamp if there is one */
  2145. if (conn->chan) {
  2146. channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
  2147. if (TLS_CHAN_TO_BASE(conn->chan)->padding_enabled) {
  2148. rep_hist_padding_count_write(PADDING_TYPE_ENABLED_TOTAL);
  2149. if (cell->command == CELL_PADDING)
  2150. rep_hist_padding_count_write(PADDING_TYPE_ENABLED_CELL);
  2151. }
  2152. }
  2153. if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
  2154. or_handshake_state_record_cell(conn, conn->handshake_state, cell, 0);
  2155. }
  2156. /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
  2157. * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
  2158. * affect a circuit.
  2159. */
  2160. MOCK_IMPL(void,
  2161. connection_or_write_var_cell_to_buf,(const var_cell_t *cell,
  2162. or_connection_t *conn))
  2163. {
  2164. int n;
  2165. char hdr[VAR_CELL_MAX_HEADER_SIZE];
  2166. tor_assert(cell);
  2167. tor_assert(conn);
  2168. n = var_cell_pack_header(cell, hdr, conn->wide_circ_ids);
  2169. connection_buf_add(hdr, n, TO_CONN(conn));
  2170. connection_buf_add((char*)cell->payload,
  2171. cell->payload_len, TO_CONN(conn));
  2172. if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
  2173. or_handshake_state_record_var_cell(conn, conn->handshake_state, cell, 0);
  2174. rep_hist_padding_count_write(PADDING_TYPE_TOTAL);
  2175. /* Touch the channel's active timestamp if there is one */
  2176. if (conn->chan)
  2177. channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
  2178. }
  2179. ///** See whether there's a variable-length cell waiting on <b>or_conn</b>'s
  2180. // * inbuf. Return values as for fetch_var_cell_from_buf(). */
  2181. //static int
  2182. //connection_fetch_var_cell_from_buf(or_connection_t *or_conn, var_cell_t **out)
  2183. //{
  2184. // connection_t *conn = TO_CONN(or_conn);
  2185. // return fetch_var_cell_from_buf(conn->inbuf, out, or_conn->link_proto);
  2186. //}
  2187. //
  2188. ///** Process cells from <b>conn</b>'s inbuf.
  2189. // *
  2190. // * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
  2191. // * and hand it to command_process_cell().
  2192. // *
  2193. // * Always return 0.
  2194. // */
  2195. //static int
  2196. //connection_or_process_cells_from_inbuf(or_connection_t *conn)
  2197. //{
  2198. // var_cell_t *var_cell;
  2199. //
  2200. // /*
  2201. // * Note on memory management for incoming cells: below the channel layer,
  2202. // * we shouldn't need to consider its internal queueing/copying logic. It
  2203. // * is safe to pass cells to it on the stack or on the heap, but in the
  2204. // * latter case we must be sure we free them later.
  2205. // *
  2206. // * The incoming cell queue code in channel.c will (in the common case)
  2207. // * decide it can pass them to the upper layer immediately, in which case
  2208. // * those functions may run directly on the cell pointers we pass here, or
  2209. // * it may decide to queue them, in which case it will allocate its own
  2210. // * buffer and copy the cell.
  2211. // */
  2212. //
  2213. // while (1) {
  2214. // log_debug(LD_OR,
  2215. // TOR_SOCKET_T_FORMAT": starting, inbuf_datalen %d "
  2216. // "(%d pending in tls object).",
  2217. // conn->base_.s,(int)connection_get_inbuf_len(TO_CONN(conn)),
  2218. // tor_tls_get_pending_bytes(conn->tls));
  2219. // if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
  2220. // if (!var_cell)
  2221. // return 0; /* not yet. */
  2222. //
  2223. // /* Touch the channel's active timestamp if there is one */
  2224. // if (conn->chan)
  2225. // channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
  2226. //
  2227. // circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  2228. // channel_tls_handle_var_cell(var_cell, conn);
  2229. // var_cell_free(var_cell);
  2230. // } else {
  2231. // const int wide_circ_ids = conn->wide_circ_ids;
  2232. // size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
  2233. // char buf[CELL_MAX_NETWORK_SIZE];
  2234. // cell_t cell;
  2235. // if (connection_get_inbuf_len(TO_CONN(conn))
  2236. // < cell_network_size) /* whole response available? */
  2237. // return 0; /* not yet */
  2238. //
  2239. // /* Touch the channel's active timestamp if there is one */
  2240. // if (conn->chan)
  2241. // channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
  2242. //
  2243. // circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  2244. // connection_buf_get_bytes(buf, cell_network_size, TO_CONN(conn));
  2245. //
  2246. // /* retrieve cell info from buf (create the host-order struct from the
  2247. // * network-order string) */
  2248. // cell_unpack(&cell, buf, wide_circ_ids);
  2249. //
  2250. // channel_tls_handle_cell(&cell, conn);
  2251. // }
  2252. // }
  2253. //}
  2254. static int
  2255. connection_or_fetch_cell(or_connection_t *or_conn, char *cell_buf)
  2256. {
  2257. // TODO: fix this ugly locking
  2258. tor_assert(TO_CONN(or_conn)->safe_conn != NULL);
  2259. tor_mutex_acquire(&(TO_CONN(or_conn)->safe_conn->lock));
  2260. struct buf_t *inbuf = TO_CONN(or_conn)->safe_conn->inbuf;
  2261. size_t cell_network_size = get_cell_network_size(or_conn->wide_circ_ids);
  2262. if (buf_datalen(inbuf) < cell_network_size) {
  2263. // don't have a full cell
  2264. tor_mutex_release(&(TO_CONN(or_conn)->safe_conn->lock));
  2265. return 0;
  2266. }
  2267. buf_get_bytes(inbuf, cell_buf, cell_network_size);
  2268. safe_connection_inbuf_modified(TO_CONN(or_conn)->safe_conn);
  2269. tor_mutex_release(&(TO_CONN(or_conn)->safe_conn->lock));
  2270. return 1;
  2271. }
  2272. static int
  2273. connection_or_fetch_var_cell(or_connection_t *or_conn, var_cell_t **var_cell_ptr)
  2274. {
  2275. // TODO: fix this ugly locking
  2276. tor_assert(TO_CONN(or_conn)->safe_conn != NULL);
  2277. tor_mutex_acquire(&(TO_CONN(or_conn)->safe_conn->lock));
  2278. struct buf_t *inbuf = TO_CONN(or_conn)->safe_conn->inbuf;
  2279. int link_proto = or_conn->link_proto;
  2280. *var_cell_ptr = NULL;
  2281. int found_var_cell = fetch_var_cell_from_buf(inbuf, var_cell_ptr, link_proto);
  2282. safe_connection_inbuf_modified(TO_CONN(or_conn)->safe_conn);
  2283. tor_mutex_release(&(TO_CONN(or_conn)->safe_conn->lock));
  2284. return found_var_cell;
  2285. }
  2286. static int
  2287. connection_or_new_process_cells_from_inbuf(or_connection_t *conn)
  2288. {
  2289. //log_debug(LD_OR, "Starting OR conn process inbuf");
  2290. log_warn(LD_OR, "Starting OR conn process inbuf for conn %p", conn);
  2291. while (1) {
  2292. var_cell_t *var_cell = NULL;
  2293. int found_var_cell = connection_or_fetch_var_cell(conn, &var_cell);
  2294. if (found_var_cell) {
  2295. if (var_cell == NULL) {
  2296. // the next cell is a var cell, but it is not yet complete
  2297. return 0;
  2298. }
  2299. // touch the channel's active timestamp if there is one
  2300. if (conn->chan) {
  2301. channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
  2302. }
  2303. circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  2304. channel_tls_handle_var_cell(var_cell, conn);
  2305. var_cell_free(var_cell);
  2306. var_cell = NULL;
  2307. } else {
  2308. char buf[CELL_MAX_NETWORK_SIZE];
  2309. int found_cell = connection_or_fetch_cell(conn, buf);
  2310. if (found_cell) {
  2311. // touch the channel's active timestamp if there is one
  2312. if (conn->chan) {
  2313. channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
  2314. }
  2315. circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  2316. // retrieve cell info from buf (create the host-order struct from the
  2317. // network-order string)
  2318. cell_t cell;
  2319. cell_unpack(&cell, buf, conn->wide_circ_ids);
  2320. channel_tls_handle_cell(&cell, conn);
  2321. } else {
  2322. // there is not yet a complete cell
  2323. return 0;
  2324. }
  2325. }
  2326. }
  2327. }
  2328. /** Array of recognized link protocol versions. */
  2329. static const uint16_t or_protocol_versions[] = { 1, 2, 3, 4, 5 };
  2330. /** Number of versions in <b>or_protocol_versions</b>. */
  2331. static const int n_or_protocol_versions =
  2332. (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
  2333. /** Return true iff <b>v</b> is a link protocol version that this Tor
  2334. * implementation believes it can support. */
  2335. int
  2336. is_or_protocol_version_known(uint16_t v)
  2337. {
  2338. int i;
  2339. for (i = 0; i < n_or_protocol_versions; ++i) {
  2340. if (or_protocol_versions[i] == v)
  2341. return 1;
  2342. }
  2343. return 0;
  2344. }
  2345. /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
  2346. * link protocol versions that this Tor can support.
  2347. *
  2348. * If <b>v3_plus</b>, this is part of a V3 protocol handshake, so only
  2349. * allow protocol version v3 or later. If not <b>v3_plus</b>, this is
  2350. * not part of a v3 protocol handshake, so don't allow protocol v3 or
  2351. * later.
  2352. **/
  2353. int
  2354. connection_or_send_versions(or_connection_t *conn, int v3_plus)
  2355. {
  2356. var_cell_t *cell;
  2357. int i;
  2358. int n_versions = 0;
  2359. const int min_version = v3_plus ? 3 : 0;
  2360. const int max_version = v3_plus ? UINT16_MAX : 2;
  2361. tor_assert(conn->handshake_state &&
  2362. !conn->handshake_state->sent_versions_at);
  2363. cell = var_cell_new(n_or_protocol_versions * 2);
  2364. cell->command = CELL_VERSIONS;
  2365. for (i = 0; i < n_or_protocol_versions; ++i) {
  2366. uint16_t v = or_protocol_versions[i];
  2367. if (v < min_version || v > max_version)
  2368. continue;
  2369. set_uint16(cell->payload+(2*n_versions), htons(v));
  2370. ++n_versions;
  2371. }
  2372. cell->payload_len = n_versions * 2;
  2373. connection_or_write_var_cell_to_buf(cell, conn);
  2374. conn->handshake_state->sent_versions_at = time(NULL);
  2375. var_cell_free(cell);
  2376. return 0;
  2377. }
  2378. static netinfo_addr_t *
  2379. netinfo_addr_from_tor_addr(const tor_addr_t *tor_addr)
  2380. {
  2381. sa_family_t addr_family = tor_addr_family(tor_addr);
  2382. if (BUG(addr_family != AF_INET && addr_family != AF_INET6))
  2383. return NULL;
  2384. netinfo_addr_t *netinfo_addr = netinfo_addr_new();
  2385. if (addr_family == AF_INET) {
  2386. netinfo_addr_set_addr_type(netinfo_addr, NETINFO_ADDR_TYPE_IPV4);
  2387. netinfo_addr_set_len(netinfo_addr, 4);
  2388. netinfo_addr_set_addr_ipv4(netinfo_addr, tor_addr_to_ipv4h(tor_addr));
  2389. } else if (addr_family == AF_INET6) {
  2390. netinfo_addr_set_addr_type(netinfo_addr, NETINFO_ADDR_TYPE_IPV6);
  2391. netinfo_addr_set_len(netinfo_addr, 16);
  2392. uint8_t *ipv6_buf = netinfo_addr_getarray_addr_ipv6(netinfo_addr);
  2393. const uint8_t *in6_addr = tor_addr_to_in6_addr8(tor_addr);
  2394. memcpy(ipv6_buf, in6_addr, 16);
  2395. }
  2396. return netinfo_addr;
  2397. }
  2398. /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
  2399. * about their address, our address, and the current time. */
  2400. MOCK_IMPL(int,
  2401. connection_or_send_netinfo,(or_connection_t *conn))
  2402. {
  2403. cell_t cell;
  2404. time_t now = time(NULL);
  2405. const routerinfo_t *me;
  2406. int r = -1;
  2407. tor_assert(conn->handshake_state);
  2408. if (conn->handshake_state->sent_netinfo) {
  2409. log_warn(LD_BUG, "Attempted to send an extra netinfo cell on a connection "
  2410. "where we already sent one.");
  2411. return 0;
  2412. }
  2413. memset(&cell, 0, sizeof(cell_t));
  2414. cell.command = CELL_NETINFO;
  2415. netinfo_cell_t *netinfo_cell = netinfo_cell_new();
  2416. /* Timestamp, if we're a relay. */
  2417. if (public_server_mode(get_options()) || ! conn->is_outgoing)
  2418. netinfo_cell_set_timestamp(netinfo_cell, (uint32_t)now);
  2419. /* Their address. */
  2420. const tor_addr_t *remote_tor_addr =
  2421. !tor_addr_is_null(&conn->real_addr) ? &conn->real_addr : &conn->base_.addr;
  2422. /* We use &conn->real_addr below, unless it hasn't yet been set. If it
  2423. * hasn't yet been set, we know that base_.addr hasn't been tampered with
  2424. * yet either. */
  2425. netinfo_addr_t *their_addr = netinfo_addr_from_tor_addr(remote_tor_addr);
  2426. netinfo_cell_set_other_addr(netinfo_cell, their_addr);
  2427. /* My address -- only include it if I'm a public relay, or if I'm a
  2428. * bridge and this is an incoming connection. If I'm a bridge and this
  2429. * is an outgoing connection, act like a normal client and omit it. */
  2430. if ((public_server_mode(get_options()) || !conn->is_outgoing) &&
  2431. (me = router_get_my_routerinfo())) {
  2432. tor_addr_t my_addr;
  2433. tor_addr_from_ipv4h(&my_addr, me->addr);
  2434. uint8_t n_my_addrs = 1 + !tor_addr_is_null(&me->ipv6_addr);
  2435. netinfo_cell_set_n_my_addrs(netinfo_cell, n_my_addrs);
  2436. netinfo_cell_add_my_addrs(netinfo_cell,
  2437. netinfo_addr_from_tor_addr(&my_addr));
  2438. if (!tor_addr_is_null(&me->ipv6_addr)) {
  2439. netinfo_cell_add_my_addrs(netinfo_cell,
  2440. netinfo_addr_from_tor_addr(&me->ipv6_addr));
  2441. }
  2442. }
  2443. const char *errmsg = NULL;
  2444. if ((errmsg = netinfo_cell_check(netinfo_cell))) {
  2445. log_warn(LD_OR, "Failed to validate NETINFO cell with error: %s",
  2446. errmsg);
  2447. goto cleanup;
  2448. }
  2449. if (netinfo_cell_encode(cell.payload, CELL_PAYLOAD_SIZE,
  2450. netinfo_cell) < 0) {
  2451. log_warn(LD_OR, "Failed generating NETINFO cell");
  2452. goto cleanup;
  2453. }
  2454. conn->handshake_state->digest_sent_data = 0;
  2455. conn->handshake_state->sent_netinfo = 1;
  2456. connection_or_write_cell_to_buf(&cell, conn);
  2457. r = 0;
  2458. cleanup:
  2459. netinfo_cell_free(netinfo_cell);
  2460. return r;
  2461. }
  2462. /** Helper used to add an encoded certs to a cert cell */
  2463. static void
  2464. add_certs_cell_cert_helper(certs_cell_t *certs_cell,
  2465. uint8_t cert_type,
  2466. const uint8_t *cert_encoded,
  2467. size_t cert_len)
  2468. {
  2469. tor_assert(cert_len <= UINT16_MAX);
  2470. certs_cell_cert_t *ccc = certs_cell_cert_new();
  2471. ccc->cert_type = cert_type;
  2472. ccc->cert_len = cert_len;
  2473. certs_cell_cert_setlen_body(ccc, cert_len);
  2474. memcpy(certs_cell_cert_getarray_body(ccc), cert_encoded, cert_len);
  2475. certs_cell_add_certs(certs_cell, ccc);
  2476. }
  2477. /** Add an encoded X509 cert (stored as <b>cert_len</b> bytes at
  2478. * <b>cert_encoded</b>) to the trunnel certs_cell_t object that we are
  2479. * building in <b>certs_cell</b>. Set its type field to <b>cert_type</b>.
  2480. * (If <b>cert</b> is NULL, take no action.) */
  2481. static void
  2482. add_x509_cert(certs_cell_t *certs_cell,
  2483. uint8_t cert_type,
  2484. const tor_x509_cert_t *cert)
  2485. {
  2486. if (NULL == cert)
  2487. return;
  2488. const uint8_t *cert_encoded = NULL;
  2489. size_t cert_len;
  2490. tor_x509_cert_get_der(cert, &cert_encoded, &cert_len);
  2491. add_certs_cell_cert_helper(certs_cell, cert_type, cert_encoded, cert_len);
  2492. }
  2493. /** Add an Ed25519 cert from <b>cert</b> to the trunnel certs_cell_t object
  2494. * that we are building in <b>certs_cell</b>. Set its type field to
  2495. * <b>cert_type</b>. (If <b>cert</b> is NULL, take no action.) */
  2496. static void
  2497. add_ed25519_cert(certs_cell_t *certs_cell,
  2498. uint8_t cert_type,
  2499. const tor_cert_t *cert)
  2500. {
  2501. if (NULL == cert)
  2502. return;
  2503. add_certs_cell_cert_helper(certs_cell, cert_type,
  2504. cert->encoded, cert->encoded_len);
  2505. }
  2506. #ifdef TOR_UNIT_TESTS
  2507. int certs_cell_ed25519_disabled_for_testing = 0;
  2508. #else
  2509. #define certs_cell_ed25519_disabled_for_testing 0
  2510. #endif
  2511. /** Send a CERTS cell on the connection <b>conn</b>. Return 0 on success, -1
  2512. * on failure. */
  2513. int
  2514. connection_or_send_certs_cell(or_connection_t *conn)
  2515. {
  2516. const tor_x509_cert_t *global_link_cert = NULL, *id_cert = NULL;
  2517. tor_x509_cert_t *own_link_cert = NULL;
  2518. var_cell_t *cell;
  2519. certs_cell_t *certs_cell = NULL;
  2520. tor_assert(conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3);
  2521. if (! conn->handshake_state)
  2522. return -1;
  2523. const int conn_in_server_mode = ! conn->handshake_state->started_here;
  2524. /* Get the encoded values of the X509 certificates */
  2525. if (tor_tls_get_my_certs(conn_in_server_mode,
  2526. &global_link_cert, &id_cert) < 0)
  2527. return -1;
  2528. if (conn_in_server_mode) {
  2529. //own_link_cert = tor_tls_get_own_cert(conn->tls);
  2530. own_link_cert = conn->tls_own_cert;
  2531. }
  2532. tor_assert(id_cert);
  2533. certs_cell = certs_cell_new();
  2534. /* Start adding certs. First the link cert or auth1024 cert. */
  2535. if (conn_in_server_mode) {
  2536. tor_assert_nonfatal(own_link_cert);
  2537. add_x509_cert(certs_cell,
  2538. OR_CERT_TYPE_TLS_LINK, own_link_cert);
  2539. } else {
  2540. tor_assert(global_link_cert);
  2541. add_x509_cert(certs_cell,
  2542. OR_CERT_TYPE_AUTH_1024, global_link_cert);
  2543. }
  2544. /* Next the RSA->RSA ID cert */
  2545. add_x509_cert(certs_cell,
  2546. OR_CERT_TYPE_ID_1024, id_cert);
  2547. /* Next the Ed25519 certs */
  2548. add_ed25519_cert(certs_cell,
  2549. CERTTYPE_ED_ID_SIGN,
  2550. get_master_signing_key_cert());
  2551. if (conn_in_server_mode) {
  2552. tor_assert_nonfatal(conn->handshake_state->own_link_cert ||
  2553. certs_cell_ed25519_disabled_for_testing);
  2554. add_ed25519_cert(certs_cell,
  2555. CERTTYPE_ED_SIGN_LINK,
  2556. conn->handshake_state->own_link_cert);
  2557. } else {
  2558. add_ed25519_cert(certs_cell,
  2559. CERTTYPE_ED_SIGN_AUTH,
  2560. get_current_auth_key_cert());
  2561. }
  2562. /* And finally the crosscert. */
  2563. {
  2564. const uint8_t *crosscert=NULL;
  2565. size_t crosscert_len;
  2566. get_master_rsa_crosscert(&crosscert, &crosscert_len);
  2567. if (crosscert) {
  2568. add_certs_cell_cert_helper(certs_cell,
  2569. CERTTYPE_RSA1024_ID_EDID,
  2570. crosscert, crosscert_len);
  2571. }
  2572. }
  2573. /* We've added all the certs; make the cell. */
  2574. certs_cell->n_certs = certs_cell_getlen_certs(certs_cell);
  2575. ssize_t alloc_len = certs_cell_encoded_len(certs_cell);
  2576. tor_assert(alloc_len >= 0 && alloc_len <= UINT16_MAX);
  2577. cell = var_cell_new(alloc_len);
  2578. cell->command = CELL_CERTS;
  2579. ssize_t enc_len = certs_cell_encode(cell->payload, alloc_len, certs_cell);
  2580. tor_assert(enc_len > 0 && enc_len <= alloc_len);
  2581. cell->payload_len = enc_len;
  2582. connection_or_write_var_cell_to_buf(cell, conn);
  2583. var_cell_free(cell);
  2584. certs_cell_free(certs_cell);
  2585. //tor_x509_cert_free(own_link_cert);
  2586. return 0;
  2587. }
  2588. #ifdef TOR_UNIT_TESTS
  2589. int testing__connection_or_pretend_TLSSECRET_is_supported = 0;
  2590. #else
  2591. #define testing__connection_or_pretend_TLSSECRET_is_supported 0
  2592. #endif
  2593. /** Return true iff <b>challenge_type</b> is an AUTHCHALLENGE type that
  2594. * we can send and receive. */
  2595. int
  2596. authchallenge_type_is_supported(uint16_t challenge_type)
  2597. {
  2598. switch (challenge_type) {
  2599. case AUTHTYPE_RSA_SHA256_TLSSECRET:
  2600. #ifdef HAVE_WORKING_TOR_TLS_GET_TLSSECRETS
  2601. return 1;
  2602. #else
  2603. return testing__connection_or_pretend_TLSSECRET_is_supported;
  2604. #endif
  2605. case AUTHTYPE_ED25519_SHA256_RFC5705:
  2606. return 1;
  2607. case AUTHTYPE_RSA_SHA256_RFC5705:
  2608. default:
  2609. return 0;
  2610. }
  2611. }
  2612. /** Return true iff <b>challenge_type_a</b> is one that we would rather
  2613. * use than <b>challenge_type_b</b>. */
  2614. int
  2615. authchallenge_type_is_better(uint16_t challenge_type_a,
  2616. uint16_t challenge_type_b)
  2617. {
  2618. /* Any supported type is better than an unsupported one;
  2619. * all unsupported types are equally bad. */
  2620. if (!authchallenge_type_is_supported(challenge_type_a))
  2621. return 0;
  2622. if (!authchallenge_type_is_supported(challenge_type_b))
  2623. return 1;
  2624. /* It happens that types are superior in numerically ascending order.
  2625. * If that ever changes, this must change too. */
  2626. return (challenge_type_a > challenge_type_b);
  2627. }
  2628. /** Send an AUTH_CHALLENGE cell on the connection <b>conn</b>. Return 0
  2629. * on success, -1 on failure. */
  2630. int
  2631. connection_or_send_auth_challenge_cell(or_connection_t *conn)
  2632. {
  2633. var_cell_t *cell = NULL;
  2634. int r = -1;
  2635. tor_assert(conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3);
  2636. if (! conn->handshake_state)
  2637. return -1;
  2638. auth_challenge_cell_t *ac = auth_challenge_cell_new();
  2639. tor_assert(sizeof(ac->challenge) == 32);
  2640. crypto_rand((char*)ac->challenge, sizeof(ac->challenge));
  2641. if (authchallenge_type_is_supported(AUTHTYPE_RSA_SHA256_TLSSECRET))
  2642. auth_challenge_cell_add_methods(ac, AUTHTYPE_RSA_SHA256_TLSSECRET);
  2643. /* Disabled, because everything that supports this method also supports
  2644. * the much-superior ED25519_SHA256_RFC5705 */
  2645. /* auth_challenge_cell_add_methods(ac, AUTHTYPE_RSA_SHA256_RFC5705); */
  2646. if (authchallenge_type_is_supported(AUTHTYPE_ED25519_SHA256_RFC5705))
  2647. auth_challenge_cell_add_methods(ac, AUTHTYPE_ED25519_SHA256_RFC5705);
  2648. auth_challenge_cell_set_n_methods(ac,
  2649. auth_challenge_cell_getlen_methods(ac));
  2650. cell = var_cell_new(auth_challenge_cell_encoded_len(ac));
  2651. ssize_t len = auth_challenge_cell_encode(cell->payload, cell->payload_len,
  2652. ac);
  2653. if (len != cell->payload_len) {
  2654. /* LCOV_EXCL_START */
  2655. log_warn(LD_BUG, "Encoded auth challenge cell length not as expected");
  2656. goto done;
  2657. /* LCOV_EXCL_STOP */
  2658. }
  2659. cell->command = CELL_AUTH_CHALLENGE;
  2660. connection_or_write_var_cell_to_buf(cell, conn);
  2661. r = 0;
  2662. done:
  2663. var_cell_free(cell);
  2664. auth_challenge_cell_free(ac);
  2665. return r;
  2666. }
  2667. /** Compute the main body of an AUTHENTICATE cell that a client can use
  2668. * to authenticate itself on a v3 handshake for <b>conn</b>. Return it
  2669. * in a var_cell_t.
  2670. *
  2671. * If <b>server</b> is true, only calculate the first
  2672. * V3_AUTH_FIXED_PART_LEN bytes -- the part of the authenticator that's
  2673. * determined by the rest of the handshake, and which match the provided value
  2674. * exactly.
  2675. *
  2676. * If <b>server</b> is false and <b>signing_key</b> is NULL, calculate the
  2677. * first V3_AUTH_BODY_LEN bytes of the authenticator (that is, everything
  2678. * that should be signed), but don't actually sign it.
  2679. *
  2680. * If <b>server</b> is false and <b>signing_key</b> is provided, calculate the
  2681. * entire authenticator, signed with <b>signing_key</b>.
  2682. *
  2683. * Return the length of the cell body on success, and -1 on failure.
  2684. */
  2685. var_cell_t *
  2686. connection_or_compute_authenticate_cell_body(or_connection_t *conn,
  2687. const int authtype,
  2688. crypto_pk_t *signing_key,
  2689. const ed25519_keypair_t *ed_signing_key,
  2690. int server)
  2691. {
  2692. auth1_t *auth = NULL;
  2693. auth_ctx_t *ctx = auth_ctx_new();
  2694. var_cell_t *result = NULL;
  2695. int old_tlssecrets_algorithm = 0;
  2696. const char *authtype_str = NULL;
  2697. int is_ed = 0;
  2698. /* assert state is reasonable XXXX */
  2699. switch (authtype) {
  2700. case AUTHTYPE_RSA_SHA256_TLSSECRET:
  2701. authtype_str = "AUTH0001";
  2702. old_tlssecrets_algorithm = 1;
  2703. break;
  2704. case AUTHTYPE_RSA_SHA256_RFC5705:
  2705. authtype_str = "AUTH0002";
  2706. break;
  2707. case AUTHTYPE_ED25519_SHA256_RFC5705:
  2708. authtype_str = "AUTH0003";
  2709. is_ed = 1;
  2710. break;
  2711. default:
  2712. tor_assert(0);
  2713. break;
  2714. }
  2715. auth = auth1_new();
  2716. ctx->is_ed = is_ed;
  2717. /* Type: 8 bytes. */
  2718. memcpy(auth1_getarray_type(auth), authtype_str, 8);
  2719. {
  2720. const tor_x509_cert_t *id_cert=NULL;
  2721. const common_digests_t *my_digests, *their_digests;
  2722. const uint8_t *my_id, *their_id, *client_id, *server_id;
  2723. if (tor_tls_get_my_certs(server, NULL, &id_cert))
  2724. goto err;
  2725. my_digests = tor_x509_cert_get_id_digests(id_cert);
  2726. their_digests =
  2727. tor_x509_cert_get_id_digests(conn->handshake_state->certs->id_cert);
  2728. tor_assert(my_digests);
  2729. tor_assert(their_digests);
  2730. my_id = (uint8_t*)my_digests->d[DIGEST_SHA256];
  2731. their_id = (uint8_t*)their_digests->d[DIGEST_SHA256];
  2732. client_id = server ? their_id : my_id;
  2733. server_id = server ? my_id : their_id;
  2734. /* Client ID digest: 32 octets. */
  2735. memcpy(auth->cid, client_id, 32);
  2736. /* Server ID digest: 32 octets. */
  2737. memcpy(auth->sid, server_id, 32);
  2738. }
  2739. if (is_ed) {
  2740. const ed25519_public_key_t *my_ed_id, *their_ed_id;
  2741. if (!conn->handshake_state->certs->ed_id_sign) {
  2742. log_warn(LD_OR, "Ed authenticate without Ed ID cert from peer.");
  2743. goto err;
  2744. }
  2745. my_ed_id = get_master_identity_key();
  2746. their_ed_id = &conn->handshake_state->certs->ed_id_sign->signing_key;
  2747. const uint8_t *cid_ed = (server ? their_ed_id : my_ed_id)->pubkey;
  2748. const uint8_t *sid_ed = (server ? my_ed_id : their_ed_id)->pubkey;
  2749. memcpy(auth->u1_cid_ed, cid_ed, ED25519_PUBKEY_LEN);
  2750. memcpy(auth->u1_sid_ed, sid_ed, ED25519_PUBKEY_LEN);
  2751. }
  2752. {
  2753. crypto_digest_t *server_d, *client_d;
  2754. if (server) {
  2755. server_d = conn->handshake_state->digest_sent;
  2756. client_d = conn->handshake_state->digest_received;
  2757. } else {
  2758. client_d = conn->handshake_state->digest_sent;
  2759. server_d = conn->handshake_state->digest_received;
  2760. }
  2761. /* Server log digest : 32 octets */
  2762. crypto_digest_get_digest(server_d, (char*)auth->slog, 32);
  2763. /* Client log digest : 32 octets */
  2764. crypto_digest_get_digest(client_d, (char*)auth->clog, 32);
  2765. }
  2766. {
  2767. /* Digest of cert used on TLS link : 32 octets. */
  2768. tor_x509_cert_t *cert = NULL;
  2769. if (server) {
  2770. //cert = tor_tls_get_own_cert(conn->tls);
  2771. cert = conn->tls_own_cert;
  2772. } else {
  2773. //cert = tor_tls_get_peer_cert(conn->tls);
  2774. cert = conn->tls_peer_cert;
  2775. }
  2776. if (!cert) {
  2777. log_warn(LD_OR, "Unable to find cert when making %s data.",
  2778. authtype_str);
  2779. goto err;
  2780. }
  2781. memcpy(auth->scert,
  2782. tor_x509_cert_get_cert_digests(cert)->d[DIGEST_SHA256], 32);
  2783. //tor_x509_cert_free(cert);
  2784. }
  2785. safe_connection_t *safe_conn = TO_CONN(conn)->safe_conn;
  2786. tor_assert(safe_conn != NULL);
  2787. /* HMAC of clientrandom and serverrandom using master key : 32 octets */
  2788. if (old_tlssecrets_algorithm) {
  2789. //if (tor_tls_get_tlssecrets(conn->tls, auth->tlssecrets) < 0) {
  2790. if (safe_or_connection_tls_secrets(TO_SAFE_OR_CONN(safe_conn),
  2791. auth->tlssecrets) < 0) {
  2792. log_fn(LOG_PROTOCOL_WARN, LD_OR, "Somebody asked us for an older TLS "
  2793. "authentication method (AUTHTYPE_RSA_SHA256_TLSSECRET) "
  2794. "which we don't support.");
  2795. }
  2796. } else {
  2797. char label[128];
  2798. tor_snprintf(label, sizeof(label),
  2799. "EXPORTER FOR TOR TLS CLIENT BINDING %s", authtype_str);
  2800. //int r = tor_tls_export_key_material(conn->tls, auth->tlssecrets,
  2801. // auth->cid, sizeof(auth->cid),
  2802. // label);
  2803. int r = safe_or_connection_key_material(TO_SAFE_OR_CONN(safe_conn),
  2804. auth->tlssecrets,
  2805. auth->cid, sizeof(auth->cid),
  2806. label);
  2807. if (r < 0) {
  2808. if (r != -2)
  2809. log_warn(LD_BUG, "TLS key export failed for unknown reason.");
  2810. // If r == -2, this was openssl bug 7712.
  2811. goto err;
  2812. }
  2813. }
  2814. /* 8 octets were reserved for the current time, but we're trying to get out
  2815. * of the habit of sending time around willynilly. Fortunately, nothing
  2816. * checks it. That's followed by 16 bytes of nonce. */
  2817. crypto_rand((char*)auth->rand, 24);
  2818. ssize_t maxlen = auth1_encoded_len(auth, ctx);
  2819. if (ed_signing_key && is_ed) {
  2820. maxlen += ED25519_SIG_LEN;
  2821. } else if (signing_key && !is_ed) {
  2822. maxlen += crypto_pk_keysize(signing_key);
  2823. }
  2824. const int AUTH_CELL_HEADER_LEN = 4; /* 2 bytes of type, 2 bytes of length */
  2825. result = var_cell_new(AUTH_CELL_HEADER_LEN + maxlen);
  2826. uint8_t *const out = result->payload + AUTH_CELL_HEADER_LEN;
  2827. const size_t outlen = maxlen;
  2828. ssize_t len;
  2829. result->command = CELL_AUTHENTICATE;
  2830. set_uint16(result->payload, htons(authtype));
  2831. if ((len = auth1_encode(out, outlen, auth, ctx)) < 0) {
  2832. /* LCOV_EXCL_START */
  2833. log_warn(LD_BUG, "Unable to encode signed part of AUTH1 data.");
  2834. goto err;
  2835. /* LCOV_EXCL_STOP */
  2836. }
  2837. if (server) {
  2838. auth1_t *tmp = NULL;
  2839. ssize_t len2 = auth1_parse(&tmp, out, len, ctx);
  2840. if (!tmp) {
  2841. /* LCOV_EXCL_START */
  2842. log_warn(LD_BUG, "Unable to parse signed part of AUTH1 data that "
  2843. "we just encoded");
  2844. goto err;
  2845. /* LCOV_EXCL_STOP */
  2846. }
  2847. result->payload_len = (tmp->end_of_signed - result->payload);
  2848. auth1_free(tmp);
  2849. if (len2 != len) {
  2850. /* LCOV_EXCL_START */
  2851. log_warn(LD_BUG, "Mismatched length when re-parsing AUTH1 data.");
  2852. goto err;
  2853. /* LCOV_EXCL_STOP */
  2854. }
  2855. goto done;
  2856. }
  2857. if (ed_signing_key && is_ed) {
  2858. ed25519_signature_t sig;
  2859. if (ed25519_sign(&sig, out, len, ed_signing_key) < 0) {
  2860. /* LCOV_EXCL_START */
  2861. log_warn(LD_BUG, "Unable to sign ed25519 authentication data");
  2862. goto err;
  2863. /* LCOV_EXCL_STOP */
  2864. }
  2865. auth1_setlen_sig(auth, ED25519_SIG_LEN);
  2866. memcpy(auth1_getarray_sig(auth), sig.sig, ED25519_SIG_LEN);
  2867. } else if (signing_key && !is_ed) {
  2868. auth1_setlen_sig(auth, crypto_pk_keysize(signing_key));
  2869. char d[32];
  2870. crypto_digest256(d, (char*)out, len, DIGEST_SHA256);
  2871. int siglen = crypto_pk_private_sign(signing_key,
  2872. (char*)auth1_getarray_sig(auth),
  2873. auth1_getlen_sig(auth),
  2874. d, 32);
  2875. if (siglen < 0) {
  2876. log_warn(LD_OR, "Unable to sign AUTH1 data.");
  2877. goto err;
  2878. }
  2879. auth1_setlen_sig(auth, siglen);
  2880. }
  2881. len = auth1_encode(out, outlen, auth, ctx);
  2882. if (len < 0) {
  2883. /* LCOV_EXCL_START */
  2884. log_warn(LD_BUG, "Unable to encode signed AUTH1 data.");
  2885. goto err;
  2886. /* LCOV_EXCL_STOP */
  2887. }
  2888. tor_assert(len + AUTH_CELL_HEADER_LEN <= result->payload_len);
  2889. result->payload_len = len + AUTH_CELL_HEADER_LEN;
  2890. set_uint16(result->payload+2, htons(len));
  2891. goto done;
  2892. err:
  2893. var_cell_free(result);
  2894. result = NULL;
  2895. done:
  2896. auth1_free(auth);
  2897. auth_ctx_free(ctx);
  2898. return result;
  2899. }
  2900. /** Send an AUTHENTICATE cell on the connection <b>conn</b>. Return 0 on
  2901. * success, -1 on failure */
  2902. MOCK_IMPL(int,
  2903. connection_or_send_authenticate_cell,(or_connection_t *conn, int authtype))
  2904. {
  2905. var_cell_t *cell;
  2906. crypto_pk_t *pk = tor_tls_get_my_client_auth_key();
  2907. /* XXXX make sure we're actually supposed to send this! */
  2908. if (!pk) {
  2909. log_warn(LD_BUG, "Can't compute authenticate cell: no client auth key");
  2910. return -1;
  2911. }
  2912. if (! authchallenge_type_is_supported(authtype)) {
  2913. log_warn(LD_BUG, "Tried to send authenticate cell with unknown "
  2914. "authentication type %d", authtype);
  2915. return -1;
  2916. }
  2917. cell = connection_or_compute_authenticate_cell_body(conn,
  2918. authtype,
  2919. pk,
  2920. get_current_auth_keypair(),
  2921. 0 /* not server */);
  2922. if (! cell) {
  2923. log_fn(LOG_PROTOCOL_WARN, LD_NET, "Unable to compute authenticate cell!");
  2924. return -1;
  2925. }
  2926. connection_or_write_var_cell_to_buf(cell, conn);
  2927. var_cell_free(cell);
  2928. return 0;
  2929. }