connection_or.c 104 KB

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