connection_or.c 101 KB

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