connection_or.c 102 KB

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