channeltls.c 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502
  1. /* * Copyright (c) 2012-2019, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file channeltls.c
  5. *
  6. * \brief A concrete subclass of channel_t using or_connection_t to transfer
  7. * cells between Tor instances.
  8. *
  9. * This module fills in the various function pointers in channel_t, to
  10. * implement the channel_tls_t channels as used in Tor today. These channels
  11. * are created from channel_tls_connect() and
  12. * channel_tls_handle_incoming(). Each corresponds 1:1 to or_connection_t
  13. * object, as implemented in connection_or.c. These channels transmit cells
  14. * to the underlying or_connection_t by calling
  15. * connection_or_write_*_cell_to_buf(), and receive cells from the underlying
  16. * or_connection_t when connection_or_process_cells_from_inbuf() calls
  17. * channel_tls_handle_*_cell().
  18. *
  19. * Here we also implement the server (responder) side of the v3+ Tor link
  20. * handshake, which uses CERTS and AUTHENTICATE cell to negotiate versions,
  21. * exchange expected and observed IP and time information, and bootstrap a
  22. * level of authentication higher than we have gotten on the raw TLS
  23. * handshake.
  24. *
  25. * NOTE: Since there is currently only one type of channel, there are probably
  26. * more than a few cases where functionality that is currently in
  27. * channeltls.c, connection_or.c, and channel.c ought to be divided up
  28. * differently. The right time to do this is probably whenever we introduce
  29. * our next channel type.
  30. **/
  31. /*
  32. * Define this so channel.h gives us things only channel_t subclasses
  33. * should touch.
  34. */
  35. #define TOR_CHANNEL_INTERNAL_
  36. #define CHANNELTLS_PRIVATE
  37. #include "core/or/or.h"
  38. #include "core/or/channel.h"
  39. #include "core/or/channeltls.h"
  40. #include "core/or/circuitmux.h"
  41. #include "core/or/circuitmux_ewma.h"
  42. #include "core/or/command.h"
  43. #include "app/config/config.h"
  44. #include "core/mainloop/connection.h"
  45. #include "core/or/connection_or.h"
  46. #include "feature/control/control.h"
  47. #include "feature/client/entrynodes.h"
  48. #include "trunnel/link_handshake.h"
  49. #include "core/or/relay.h"
  50. #include "feature/stats/rephist.h"
  51. #include "feature/relay/router.h"
  52. #include "feature/relay/routermode.h"
  53. #include "feature/nodelist/dirlist.h"
  54. #include "core/or/scheduler.h"
  55. #include "feature/nodelist/torcert.h"
  56. #include "feature/nodelist/networkstatus.h"
  57. #include "trunnel/channelpadding_negotiation.h"
  58. #include "trunnel/netinfo.h"
  59. #include "core/or/channelpadding.h"
  60. #include "core/or/cell_st.h"
  61. #include "core/or/cell_queue_st.h"
  62. #include "core/or/extend_info_st.h"
  63. #include "core/or/or_connection_st.h"
  64. #include "core/or/or_handshake_certs_st.h"
  65. #include "core/or/or_handshake_state_st.h"
  66. #include "feature/nodelist/routerinfo_st.h"
  67. #include "core/or/var_cell_st.h"
  68. #include "lib/tls/tortls.h"
  69. #include "lib/tls/x509.h"
  70. /** How many CELL_PADDING cells have we received, ever? */
  71. uint64_t stats_n_padding_cells_processed = 0;
  72. /** How many CELL_VERSIONS cells have we received, ever? */
  73. uint64_t stats_n_versions_cells_processed = 0;
  74. /** How many CELL_NETINFO cells have we received, ever? */
  75. uint64_t stats_n_netinfo_cells_processed = 0;
  76. /** How many CELL_VPADDING cells have we received, ever? */
  77. uint64_t stats_n_vpadding_cells_processed = 0;
  78. /** How many CELL_CERTS cells have we received, ever? */
  79. uint64_t stats_n_certs_cells_processed = 0;
  80. /** How many CELL_AUTH_CHALLENGE cells have we received, ever? */
  81. uint64_t stats_n_auth_challenge_cells_processed = 0;
  82. /** How many CELL_AUTHENTICATE cells have we received, ever? */
  83. uint64_t stats_n_authenticate_cells_processed = 0;
  84. /** How many CELL_AUTHORIZE cells have we received, ever? */
  85. uint64_t stats_n_authorize_cells_processed = 0;
  86. /** Active listener, if any */
  87. static channel_listener_t *channel_tls_listener = NULL;
  88. /* channel_tls_t method declarations */
  89. static void channel_tls_close_method(channel_t *chan);
  90. static const char * channel_tls_describe_transport_method(channel_t *chan);
  91. static void channel_tls_free_method(channel_t *chan);
  92. static double channel_tls_get_overhead_estimate_method(channel_t *chan);
  93. static int
  94. channel_tls_get_remote_addr_method(channel_t *chan, tor_addr_t *addr_out);
  95. static int
  96. channel_tls_get_transport_name_method(channel_t *chan, char **transport_out);
  97. static const char *
  98. channel_tls_get_remote_descr_method(channel_t *chan, int flags);
  99. static int channel_tls_has_queued_writes_method(channel_t *chan);
  100. static int channel_tls_is_canonical_method(channel_t *chan, int req);
  101. static int
  102. channel_tls_matches_extend_info_method(channel_t *chan,
  103. extend_info_t *extend_info);
  104. static int channel_tls_matches_target_method(channel_t *chan,
  105. const tor_addr_t *target);
  106. static int channel_tls_num_cells_writeable_method(channel_t *chan);
  107. static size_t channel_tls_num_bytes_queued_method(channel_t *chan);
  108. static int channel_tls_write_cell_method(channel_t *chan,
  109. cell_t *cell);
  110. static int channel_tls_write_packed_cell_method(channel_t *chan,
  111. packed_cell_t *packed_cell);
  112. static int channel_tls_write_var_cell_method(channel_t *chan,
  113. var_cell_t *var_cell);
  114. /* channel_listener_tls_t method declarations */
  115. static void channel_tls_listener_close_method(channel_listener_t *chan_l);
  116. static const char *
  117. channel_tls_listener_describe_transport_method(channel_listener_t *chan_l);
  118. /** Handle incoming cells for the handshake stuff here rather than
  119. * passing them on up. */
  120. static void channel_tls_process_versions_cell(var_cell_t *cell,
  121. channel_tls_t *tlschan);
  122. static void channel_tls_process_netinfo_cell(cell_t *cell,
  123. channel_tls_t *tlschan);
  124. static int command_allowed_before_handshake(uint8_t command);
  125. static int enter_v3_handshake_with_cell(var_cell_t *cell,
  126. channel_tls_t *tlschan);
  127. static void channel_tls_process_padding_negotiate_cell(cell_t *cell,
  128. channel_tls_t *chan);
  129. /**
  130. * Do parts of channel_tls_t initialization common to channel_tls_connect()
  131. * and channel_tls_handle_incoming().
  132. */
  133. STATIC void
  134. channel_tls_common_init(channel_tls_t *tlschan)
  135. {
  136. channel_t *chan;
  137. tor_assert(tlschan);
  138. chan = &(tlschan->base_);
  139. channel_init(chan);
  140. chan->magic = TLS_CHAN_MAGIC;
  141. chan->state = CHANNEL_STATE_OPENING;
  142. chan->close = channel_tls_close_method;
  143. chan->describe_transport = channel_tls_describe_transport_method;
  144. chan->free_fn = channel_tls_free_method;
  145. chan->get_overhead_estimate = channel_tls_get_overhead_estimate_method;
  146. chan->get_remote_addr = channel_tls_get_remote_addr_method;
  147. chan->get_remote_descr = channel_tls_get_remote_descr_method;
  148. chan->get_transport_name = channel_tls_get_transport_name_method;
  149. chan->has_queued_writes = channel_tls_has_queued_writes_method;
  150. chan->is_canonical = channel_tls_is_canonical_method;
  151. chan->matches_extend_info = channel_tls_matches_extend_info_method;
  152. chan->matches_target = channel_tls_matches_target_method;
  153. chan->num_bytes_queued = channel_tls_num_bytes_queued_method;
  154. chan->num_cells_writeable = channel_tls_num_cells_writeable_method;
  155. chan->write_cell = channel_tls_write_cell_method;
  156. chan->write_packed_cell = channel_tls_write_packed_cell_method;
  157. chan->write_var_cell = channel_tls_write_var_cell_method;
  158. chan->cmux = circuitmux_alloc();
  159. /* We only have one policy for now so always set it to EWMA. */
  160. circuitmux_set_policy(chan->cmux, &ewma_policy);
  161. }
  162. /**
  163. * Start a new TLS channel.
  164. *
  165. * Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
  166. * handshake with an OR with identity digest <b>id_digest</b>, and wrap
  167. * it in a channel_tls_t.
  168. */
  169. channel_t *
  170. channel_tls_connect(const tor_addr_t *addr, uint16_t port,
  171. const char *id_digest,
  172. const ed25519_public_key_t *ed_id)
  173. {
  174. channel_tls_t *tlschan = tor_malloc_zero(sizeof(*tlschan));
  175. channel_t *chan = &(tlschan->base_);
  176. channel_tls_common_init(tlschan);
  177. log_debug(LD_CHANNEL,
  178. "In channel_tls_connect() for channel %p "
  179. "(global id %"PRIu64 ")",
  180. tlschan,
  181. (chan->global_identifier));
  182. if (is_local_addr(addr)) {
  183. log_debug(LD_CHANNEL,
  184. "Marking new outgoing channel %"PRIu64 " at %p as local",
  185. (chan->global_identifier), chan);
  186. channel_mark_local(chan);
  187. } else {
  188. log_debug(LD_CHANNEL,
  189. "Marking new outgoing channel %"PRIu64 " at %p as remote",
  190. (chan->global_identifier), chan);
  191. channel_mark_remote(chan);
  192. }
  193. channel_mark_outgoing(chan);
  194. /* Set up or_connection stuff */
  195. tlschan->conn = connection_or_connect(addr, port, id_digest, ed_id, tlschan);
  196. /* connection_or_connect() will fill in tlschan->conn */
  197. if (!(tlschan->conn)) {
  198. chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
  199. channel_change_state(chan, CHANNEL_STATE_ERROR);
  200. goto err;
  201. }
  202. log_debug(LD_CHANNEL,
  203. "Got orconn %p for channel with global id %"PRIu64,
  204. tlschan->conn, (chan->global_identifier));
  205. goto done;
  206. err:
  207. circuitmux_free(chan->cmux);
  208. tor_free(tlschan);
  209. chan = NULL;
  210. done:
  211. /* If we got one, we should register it */
  212. if (chan) channel_register(chan);
  213. return chan;
  214. }
  215. /**
  216. * Return the current channel_tls_t listener.
  217. *
  218. * Returns the current channel listener for incoming TLS connections, or
  219. * NULL if none has been established
  220. */
  221. channel_listener_t *
  222. channel_tls_get_listener(void)
  223. {
  224. return channel_tls_listener;
  225. }
  226. /**
  227. * Start a channel_tls_t listener if necessary.
  228. *
  229. * Return the current channel_tls_t listener, or start one if we haven't yet,
  230. * and return that.
  231. */
  232. channel_listener_t *
  233. channel_tls_start_listener(void)
  234. {
  235. channel_listener_t *listener;
  236. if (!channel_tls_listener) {
  237. listener = tor_malloc_zero(sizeof(*listener));
  238. channel_init_listener(listener);
  239. listener->state = CHANNEL_LISTENER_STATE_LISTENING;
  240. listener->close = channel_tls_listener_close_method;
  241. listener->describe_transport =
  242. channel_tls_listener_describe_transport_method;
  243. channel_tls_listener = listener;
  244. log_debug(LD_CHANNEL,
  245. "Starting TLS channel listener %p with global id %"PRIu64,
  246. listener, (listener->global_identifier));
  247. channel_listener_register(listener);
  248. } else listener = channel_tls_listener;
  249. return listener;
  250. }
  251. /**
  252. * Free everything on shutdown.
  253. *
  254. * Not much to do here, since channel_free_all() takes care of a lot, but let's
  255. * get rid of the listener.
  256. */
  257. void
  258. channel_tls_free_all(void)
  259. {
  260. channel_listener_t *old_listener = NULL;
  261. log_debug(LD_CHANNEL,
  262. "Shutting down TLS channels...");
  263. if (channel_tls_listener) {
  264. /*
  265. * When we close it, channel_tls_listener will get nulled out, so save
  266. * a pointer so we can free it.
  267. */
  268. old_listener = channel_tls_listener;
  269. log_debug(LD_CHANNEL,
  270. "Closing channel_tls_listener with ID %"PRIu64
  271. " at %p.",
  272. (old_listener->global_identifier),
  273. old_listener);
  274. channel_listener_unregister(old_listener);
  275. channel_listener_mark_for_close(old_listener);
  276. channel_listener_free(old_listener);
  277. tor_assert(channel_tls_listener == NULL);
  278. }
  279. log_debug(LD_CHANNEL,
  280. "Done shutting down TLS channels");
  281. }
  282. /**
  283. * Create a new channel around an incoming or_connection_t.
  284. */
  285. channel_t *
  286. channel_tls_handle_incoming(or_connection_t *orconn)
  287. {
  288. channel_tls_t *tlschan = tor_malloc_zero(sizeof(*tlschan));
  289. channel_t *chan = &(tlschan->base_);
  290. tor_assert(orconn);
  291. tor_assert(!(orconn->chan));
  292. channel_tls_common_init(tlschan);
  293. /* Link the channel and orconn to each other */
  294. tlschan->conn = orconn;
  295. orconn->chan = tlschan;
  296. if (is_local_addr(&(TO_CONN(orconn)->addr))) {
  297. log_debug(LD_CHANNEL,
  298. "Marking new incoming channel %"PRIu64 " at %p as local",
  299. (chan->global_identifier), chan);
  300. channel_mark_local(chan);
  301. } else {
  302. log_debug(LD_CHANNEL,
  303. "Marking new incoming channel %"PRIu64 " at %p as remote",
  304. (chan->global_identifier), chan);
  305. channel_mark_remote(chan);
  306. }
  307. channel_mark_incoming(chan);
  308. /* Register it */
  309. channel_register(chan);
  310. return chan;
  311. }
  312. /*********
  313. * Casts *
  314. ********/
  315. /**
  316. * Cast a channel_tls_t to a channel_t.
  317. */
  318. channel_t *
  319. channel_tls_to_base(channel_tls_t *tlschan)
  320. {
  321. if (!tlschan) return NULL;
  322. return &(tlschan->base_);
  323. }
  324. /**
  325. * Cast a channel_t to a channel_tls_t, with appropriate type-checking
  326. * asserts.
  327. */
  328. channel_tls_t *
  329. channel_tls_from_base(channel_t *chan)
  330. {
  331. if (!chan) return NULL;
  332. tor_assert(chan->magic == TLS_CHAN_MAGIC);
  333. return (channel_tls_t *)(chan);
  334. }
  335. /********************************************
  336. * Method implementations for channel_tls_t *
  337. *******************************************/
  338. /**
  339. * Close a channel_tls_t.
  340. *
  341. * This implements the close method for channel_tls_t.
  342. */
  343. static void
  344. channel_tls_close_method(channel_t *chan)
  345. {
  346. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  347. tor_assert(tlschan);
  348. if (tlschan->conn) connection_or_close_normally(tlschan->conn, 1);
  349. else {
  350. /* Weird - we'll have to change the state ourselves, I guess */
  351. log_info(LD_CHANNEL,
  352. "Tried to close channel_tls_t %p with NULL conn",
  353. tlschan);
  354. channel_change_state(chan, CHANNEL_STATE_ERROR);
  355. }
  356. }
  357. /**
  358. * Describe the transport for a channel_tls_t.
  359. *
  360. * This returns the string "TLS channel on connection <id>" to the upper
  361. * layer.
  362. */
  363. static const char *
  364. channel_tls_describe_transport_method(channel_t *chan)
  365. {
  366. static char *buf = NULL;
  367. uint64_t id;
  368. channel_tls_t *tlschan;
  369. const char *rv = NULL;
  370. tor_assert(chan);
  371. tlschan = BASE_CHAN_TO_TLS(chan);
  372. if (tlschan->conn) {
  373. id = TO_CONN(tlschan->conn)->global_identifier;
  374. if (buf) tor_free(buf);
  375. tor_asprintf(&buf,
  376. "TLS channel (connection %"PRIu64 ")",
  377. (id));
  378. rv = buf;
  379. } else {
  380. rv = "TLS channel (no connection)";
  381. }
  382. return rv;
  383. }
  384. /**
  385. * Free a channel_tls_t.
  386. *
  387. * This is called by the generic channel layer when freeing a channel_tls_t;
  388. * this happens either on a channel which has already reached
  389. * CHANNEL_STATE_CLOSED or CHANNEL_STATE_ERROR from channel_run_cleanup() or
  390. * on shutdown from channel_free_all(). In the latter case we might still
  391. * have an orconn active (which connection_free_all() will get to later),
  392. * so we should null out its channel pointer now.
  393. */
  394. static void
  395. channel_tls_free_method(channel_t *chan)
  396. {
  397. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  398. tor_assert(tlschan);
  399. if (tlschan->conn) {
  400. tlschan->conn->chan = NULL;
  401. tlschan->conn = NULL;
  402. }
  403. }
  404. /**
  405. * Get an estimate of the average TLS overhead for the upper layer.
  406. */
  407. static double
  408. channel_tls_get_overhead_estimate_method(channel_t *chan)
  409. {
  410. double overhead = 1.0;
  411. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  412. tor_assert(tlschan);
  413. tor_assert(tlschan->conn);
  414. /* Just return 1.0f if we don't have sensible data */
  415. if (tlschan->conn->bytes_xmitted > 0 &&
  416. tlschan->conn->bytes_xmitted_by_tls >=
  417. tlschan->conn->bytes_xmitted) {
  418. overhead = ((double)(tlschan->conn->bytes_xmitted_by_tls)) /
  419. ((double)(tlschan->conn->bytes_xmitted));
  420. /*
  421. * Never estimate more than 2.0; otherwise we get silly large estimates
  422. * at the very start of a new TLS connection.
  423. */
  424. if (overhead > 2.0)
  425. overhead = 2.0;
  426. }
  427. log_debug(LD_CHANNEL,
  428. "Estimated overhead ratio for TLS chan %"PRIu64 " is %f",
  429. (chan->global_identifier), overhead);
  430. return overhead;
  431. }
  432. /**
  433. * Get the remote address of a channel_tls_t.
  434. *
  435. * This implements the get_remote_addr method for channel_tls_t; copy the
  436. * remote endpoint of the channel to addr_out and return 1 (always
  437. * succeeds for this transport).
  438. */
  439. static int
  440. channel_tls_get_remote_addr_method(channel_t *chan, tor_addr_t *addr_out)
  441. {
  442. int rv = 0;
  443. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  444. tor_assert(tlschan);
  445. tor_assert(addr_out);
  446. if (tlschan->conn) {
  447. tor_addr_copy(addr_out, &(tlschan->conn->real_addr));
  448. rv = 1;
  449. } else tor_addr_make_unspec(addr_out);
  450. return rv;
  451. }
  452. /**
  453. * Get the name of the pluggable transport used by a channel_tls_t.
  454. *
  455. * This implements the get_transport_name for channel_tls_t. If the
  456. * channel uses a pluggable transport, copy its name to
  457. * <b>transport_out</b> and return 0. If the channel did not use a
  458. * pluggable transport, return -1.
  459. */
  460. static int
  461. channel_tls_get_transport_name_method(channel_t *chan, char **transport_out)
  462. {
  463. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  464. tor_assert(tlschan);
  465. tor_assert(transport_out);
  466. tor_assert(tlschan->conn);
  467. if (!tlschan->conn->ext_or_transport)
  468. return -1;
  469. *transport_out = tor_strdup(tlschan->conn->ext_or_transport);
  470. return 0;
  471. }
  472. /**
  473. * Get endpoint description of a channel_tls_t.
  474. *
  475. * This implements the get_remote_descr method for channel_tls_t; it returns
  476. * a text description of the remote endpoint of the channel suitable for use
  477. * in log messages. The req parameter is 0 for the canonical address or 1 for
  478. * the actual address seen.
  479. */
  480. static const char *
  481. channel_tls_get_remote_descr_method(channel_t *chan, int flags)
  482. {
  483. #define MAX_DESCR_LEN 32
  484. static char buf[MAX_DESCR_LEN + 1];
  485. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  486. connection_t *conn;
  487. const char *answer = NULL;
  488. char *addr_str;
  489. tor_assert(tlschan);
  490. if (tlschan->conn) {
  491. conn = TO_CONN(tlschan->conn);
  492. switch (flags) {
  493. case 0:
  494. /* Canonical address with port*/
  495. tor_snprintf(buf, MAX_DESCR_LEN + 1,
  496. "%s:%u", conn->address, conn->port);
  497. answer = buf;
  498. break;
  499. case GRD_FLAG_ORIGINAL:
  500. /* Actual address with port */
  501. addr_str = tor_addr_to_str_dup(&(tlschan->conn->real_addr));
  502. tor_snprintf(buf, MAX_DESCR_LEN + 1,
  503. "%s:%u", addr_str, conn->port);
  504. tor_free(addr_str);
  505. answer = buf;
  506. break;
  507. case GRD_FLAG_ADDR_ONLY:
  508. /* Canonical address, no port */
  509. strlcpy(buf, conn->address, sizeof(buf));
  510. answer = buf;
  511. break;
  512. case GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY:
  513. /* Actual address, no port */
  514. addr_str = tor_addr_to_str_dup(&(tlschan->conn->real_addr));
  515. strlcpy(buf, addr_str, sizeof(buf));
  516. tor_free(addr_str);
  517. answer = buf;
  518. break;
  519. default:
  520. /* Something's broken in channel.c */
  521. tor_assert_nonfatal_unreached_once();
  522. }
  523. } else {
  524. strlcpy(buf, "(No connection)", sizeof(buf));
  525. answer = buf;
  526. }
  527. return answer;
  528. }
  529. /**
  530. * Tell the upper layer if we have queued writes.
  531. *
  532. * This implements the has_queued_writes method for channel_tls t_; it returns
  533. * 1 iff we have queued writes on the outbuf of the underlying or_connection_t.
  534. */
  535. static int
  536. channel_tls_has_queued_writes_method(channel_t *chan)
  537. {
  538. size_t outbuf_len;
  539. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  540. tor_assert(tlschan);
  541. if (!(tlschan->conn)) {
  542. log_info(LD_CHANNEL,
  543. "something called has_queued_writes on a tlschan "
  544. "(%p with ID %"PRIu64 " but no conn",
  545. chan, (chan->global_identifier));
  546. }
  547. outbuf_len = (tlschan->conn != NULL) ?
  548. connection_get_outbuf_len(TO_CONN(tlschan->conn)) :
  549. 0;
  550. return (outbuf_len > 0);
  551. }
  552. /**
  553. * Tell the upper layer if we're canonical.
  554. *
  555. * This implements the is_canonical method for channel_tls_t; if req is zero,
  556. * it returns whether this is a canonical channel, and if it is one it returns
  557. * whether that can be relied upon.
  558. */
  559. static int
  560. channel_tls_is_canonical_method(channel_t *chan, int req)
  561. {
  562. int answer = 0;
  563. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  564. tor_assert(tlschan);
  565. if (tlschan->conn) {
  566. switch (req) {
  567. case 0:
  568. answer = tlschan->conn->is_canonical;
  569. break;
  570. case 1:
  571. /*
  572. * Is the is_canonical bit reliable? In protocols version 2 and up
  573. * we get the canonical address from a NETINFO cell, but in older
  574. * versions it might be based on an obsolete descriptor.
  575. */
  576. answer = (tlschan->conn->link_proto >= 2);
  577. break;
  578. default:
  579. /* This shouldn't happen; channel.c is broken if it does */
  580. tor_assert_nonfatal_unreached_once();
  581. }
  582. }
  583. /* else return 0 for tlschan->conn == NULL */
  584. return answer;
  585. }
  586. /**
  587. * Check if we match an extend_info_t.
  588. *
  589. * This implements the matches_extend_info method for channel_tls_t; the upper
  590. * layer wants to know if this channel matches an extend_info_t.
  591. */
  592. static int
  593. channel_tls_matches_extend_info_method(channel_t *chan,
  594. extend_info_t *extend_info)
  595. {
  596. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  597. tor_assert(tlschan);
  598. tor_assert(extend_info);
  599. /* Never match if we have no conn */
  600. if (!(tlschan->conn)) {
  601. log_info(LD_CHANNEL,
  602. "something called matches_extend_info on a tlschan "
  603. "(%p with ID %"PRIu64 " but no conn",
  604. chan, (chan->global_identifier));
  605. return 0;
  606. }
  607. return (tor_addr_eq(&(extend_info->addr),
  608. &(TO_CONN(tlschan->conn)->addr)) &&
  609. (extend_info->port == TO_CONN(tlschan->conn)->port));
  610. }
  611. /**
  612. * Check if we match a target address; return true iff we do.
  613. *
  614. * This implements the matches_target method for channel_tls t_; the upper
  615. * layer wants to know if this channel matches a target address when extending
  616. * a circuit.
  617. */
  618. static int
  619. channel_tls_matches_target_method(channel_t *chan,
  620. const tor_addr_t *target)
  621. {
  622. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  623. tor_assert(tlschan);
  624. tor_assert(target);
  625. /* Never match if we have no conn */
  626. if (!(tlschan->conn)) {
  627. log_info(LD_CHANNEL,
  628. "something called matches_target on a tlschan "
  629. "(%p with ID %"PRIu64 " but no conn",
  630. chan, (chan->global_identifier));
  631. return 0;
  632. }
  633. /* real_addr is the address this connection came from.
  634. * base_.addr is updated by connection_or_init_conn_from_address()
  635. * to be the address in the descriptor. It may be tempting to
  636. * allow either address to be allowed, but if we did so, it would
  637. * enable someone who steals a relay's keys to impersonate/MITM it
  638. * from anywhere on the Internet! (Because they could make long-lived
  639. * TLS connections from anywhere to all relays, and wait for them to
  640. * be used for extends).
  641. */
  642. return tor_addr_eq(&(tlschan->conn->real_addr), target);
  643. }
  644. /**
  645. * Tell the upper layer how many bytes we have queued and not yet
  646. * sent.
  647. */
  648. static size_t
  649. channel_tls_num_bytes_queued_method(channel_t *chan)
  650. {
  651. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  652. tor_assert(tlschan);
  653. tor_assert(tlschan->conn);
  654. return connection_get_outbuf_len(TO_CONN(tlschan->conn));
  655. }
  656. /**
  657. * Tell the upper layer how many cells we can accept to write.
  658. *
  659. * This implements the num_cells_writeable method for channel_tls_t; it
  660. * returns an estimate of the number of cells we can accept with
  661. * channel_tls_write_*_cell().
  662. */
  663. static int
  664. channel_tls_num_cells_writeable_method(channel_t *chan)
  665. {
  666. size_t outbuf_len;
  667. ssize_t n;
  668. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  669. size_t cell_network_size;
  670. tor_assert(tlschan);
  671. tor_assert(tlschan->conn);
  672. cell_network_size = get_cell_network_size(tlschan->conn->wide_circ_ids);
  673. outbuf_len = connection_get_outbuf_len(TO_CONN(tlschan->conn));
  674. /* Get the number of cells */
  675. n = CEIL_DIV(OR_CONN_HIGHWATER - outbuf_len, cell_network_size);
  676. if (n < 0) n = 0;
  677. #if SIZEOF_SIZE_T > SIZEOF_INT
  678. if (n > INT_MAX) n = INT_MAX;
  679. #endif
  680. return (int)n;
  681. }
  682. /**
  683. * Write a cell to a channel_tls_t.
  684. *
  685. * This implements the write_cell method for channel_tls_t; given a
  686. * channel_tls_t and a cell_t, transmit the cell_t.
  687. */
  688. static int
  689. channel_tls_write_cell_method(channel_t *chan, cell_t *cell)
  690. {
  691. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  692. int written = 0;
  693. tor_assert(tlschan);
  694. tor_assert(cell);
  695. if (tlschan->conn) {
  696. connection_or_write_cell_to_buf(cell, tlschan->conn);
  697. ++written;
  698. } else {
  699. log_info(LD_CHANNEL,
  700. "something called write_cell on a tlschan "
  701. "(%p with ID %"PRIu64 " but no conn",
  702. chan, (chan->global_identifier));
  703. }
  704. return written;
  705. }
  706. /**
  707. * Write a packed cell to a channel_tls_t.
  708. *
  709. * This implements the write_packed_cell method for channel_tls_t; given a
  710. * channel_tls_t and a packed_cell_t, transmit the packed_cell_t.
  711. *
  712. * Return 0 on success or negative value on error. The caller must free the
  713. * packed cell.
  714. */
  715. static int
  716. channel_tls_write_packed_cell_method(channel_t *chan,
  717. packed_cell_t *packed_cell)
  718. {
  719. tor_assert(chan);
  720. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  721. size_t cell_network_size = get_cell_network_size(chan->wide_circ_ids);
  722. tor_assert(tlschan);
  723. tor_assert(packed_cell);
  724. if (tlschan->conn) {
  725. connection_buf_add(packed_cell->body, cell_network_size,
  726. TO_CONN(tlschan->conn));
  727. } else {
  728. log_info(LD_CHANNEL,
  729. "something called write_packed_cell on a tlschan "
  730. "(%p with ID %"PRIu64 " but no conn",
  731. chan, (chan->global_identifier));
  732. return -1;
  733. }
  734. return 0;
  735. }
  736. /**
  737. * Write a variable-length cell to a channel_tls_t.
  738. *
  739. * This implements the write_var_cell method for channel_tls_t; given a
  740. * channel_tls_t and a var_cell_t, transmit the var_cell_t.
  741. */
  742. static int
  743. channel_tls_write_var_cell_method(channel_t *chan, var_cell_t *var_cell)
  744. {
  745. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  746. int written = 0;
  747. tor_assert(tlschan);
  748. tor_assert(var_cell);
  749. if (tlschan->conn) {
  750. connection_or_write_var_cell_to_buf(var_cell, tlschan->conn);
  751. ++written;
  752. } else {
  753. log_info(LD_CHANNEL,
  754. "something called write_var_cell on a tlschan "
  755. "(%p with ID %"PRIu64 " but no conn",
  756. chan, (chan->global_identifier));
  757. }
  758. return written;
  759. }
  760. /*************************************************
  761. * Method implementations for channel_listener_t *
  762. ************************************************/
  763. /**
  764. * Close a channel_listener_t.
  765. *
  766. * This implements the close method for channel_listener_t.
  767. */
  768. static void
  769. channel_tls_listener_close_method(channel_listener_t *chan_l)
  770. {
  771. tor_assert(chan_l);
  772. /*
  773. * Listeners we just go ahead and change state through to CLOSED, but
  774. * make sure to check if they're channel_tls_listener to NULL it out.
  775. */
  776. if (chan_l == channel_tls_listener)
  777. channel_tls_listener = NULL;
  778. if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
  779. chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  780. chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
  781. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
  782. }
  783. if (chan_l->incoming_list) {
  784. SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
  785. channel_t *, ichan) {
  786. channel_mark_for_close(ichan);
  787. } SMARTLIST_FOREACH_END(ichan);
  788. smartlist_free(chan_l->incoming_list);
  789. chan_l->incoming_list = NULL;
  790. }
  791. if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  792. chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
  793. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSED);
  794. }
  795. }
  796. /**
  797. * Describe the transport for a channel_listener_t.
  798. *
  799. * This returns the string "TLS channel (listening)" to the upper
  800. * layer.
  801. */
  802. static const char *
  803. channel_tls_listener_describe_transport_method(channel_listener_t *chan_l)
  804. {
  805. tor_assert(chan_l);
  806. return "TLS channel (listening)";
  807. }
  808. /*******************************************************
  809. * Functions for handling events on an or_connection_t *
  810. ******************************************************/
  811. /**
  812. * Handle an orconn state change.
  813. *
  814. * This function will be called by connection_or.c when the or_connection_t
  815. * associated with this channel_tls_t changes state.
  816. */
  817. void
  818. channel_tls_handle_state_change_on_orconn(channel_tls_t *chan,
  819. or_connection_t *conn,
  820. uint8_t state)
  821. {
  822. channel_t *base_chan;
  823. tor_assert(chan);
  824. tor_assert(conn);
  825. tor_assert(conn->chan == chan);
  826. tor_assert(chan->conn == conn);
  827. base_chan = TLS_CHAN_TO_BASE(chan);
  828. /* Make sure the base connection state makes sense - shouldn't be error
  829. * or closed. */
  830. tor_assert(CHANNEL_IS_OPENING(base_chan) ||
  831. CHANNEL_IS_OPEN(base_chan) ||
  832. CHANNEL_IS_MAINT(base_chan) ||
  833. CHANNEL_IS_CLOSING(base_chan));
  834. /* Did we just go to state open? */
  835. if (state == OR_CONN_STATE_OPEN) {
  836. /*
  837. * We can go to CHANNEL_STATE_OPEN from CHANNEL_STATE_OPENING or
  838. * CHANNEL_STATE_MAINT on this.
  839. */
  840. channel_change_state_open(base_chan);
  841. /* We might have just become writeable; check and tell the scheduler */
  842. if (connection_or_num_cells_writeable(conn) > 0) {
  843. scheduler_channel_wants_writes(base_chan);
  844. }
  845. } else {
  846. /*
  847. * Not open, so from CHANNEL_STATE_OPEN we go to CHANNEL_STATE_MAINT,
  848. * otherwise no change.
  849. */
  850. if (CHANNEL_IS_OPEN(base_chan)) {
  851. channel_change_state(base_chan, CHANNEL_STATE_MAINT);
  852. }
  853. }
  854. }
  855. #ifdef KEEP_TIMING_STATS
  856. /**
  857. * Timing states wrapper.
  858. *
  859. * This is a wrapper function around the actual function that processes the
  860. * <b>cell</b> that just arrived on <b>chan</b>. Increment <b>*time</b>
  861. * by the number of microseconds used by the call to <b>*func(cell, chan)</b>.
  862. */
  863. static void
  864. channel_tls_time_process_cell(cell_t *cell, channel_tls_t *chan, int *time,
  865. void (*func)(cell_t *, channel_tls_t *))
  866. {
  867. struct timeval start, end;
  868. long time_passed;
  869. tor_gettimeofday(&start);
  870. (*func)(cell, chan);
  871. tor_gettimeofday(&end);
  872. time_passed = tv_udiff(&start, &end) ;
  873. if (time_passed > 10000) { /* more than 10ms */
  874. log_debug(LD_OR,"That call just took %ld ms.",time_passed/1000);
  875. }
  876. if (time_passed < 0) {
  877. log_info(LD_GENERAL,"That call took us back in time!");
  878. time_passed = 0;
  879. }
  880. *time += time_passed;
  881. }
  882. #endif /* defined(KEEP_TIMING_STATS) */
  883. /**
  884. * Handle an incoming cell on a channel_tls_t.
  885. *
  886. * This is called from connection_or.c to handle an arriving cell; it checks
  887. * for cell types specific to the handshake for this transport protocol and
  888. * handles them, and queues all other cells to the channel_t layer, which
  889. * eventually will hand them off to command.c.
  890. *
  891. * The channel layer itself decides whether the cell should be queued or
  892. * can be handed off immediately to the upper-layer code. It is responsible
  893. * for copying in the case that it queues; we merely pass pointers through
  894. * which we get from connection_or_process_cells_from_inbuf().
  895. */
  896. void
  897. channel_tls_handle_cell(cell_t *cell, or_connection_t *conn)
  898. {
  899. channel_tls_t *chan;
  900. int handshaking;
  901. #ifdef KEEP_TIMING_STATS
  902. #define PROCESS_CELL(tp, cl, cn) STMT_BEGIN { \
  903. ++num ## tp; \
  904. channel_tls_time_process_cell(cl, cn, & tp ## time , \
  905. channel_tls_process_ ## tp ## _cell); \
  906. } STMT_END
  907. #else /* !(defined(KEEP_TIMING_STATS)) */
  908. #define PROCESS_CELL(tp, cl, cn) channel_tls_process_ ## tp ## _cell(cl, cn)
  909. #endif /* defined(KEEP_TIMING_STATS) */
  910. tor_assert(cell);
  911. tor_assert(conn);
  912. chan = conn->chan;
  913. if (!chan) {
  914. log_warn(LD_CHANNEL,
  915. "Got a cell_t on an OR connection with no channel");
  916. return;
  917. }
  918. handshaking = (TO_CONN(conn)->state != OR_CONN_STATE_OPEN);
  919. if (conn->base_.marked_for_close)
  920. return;
  921. /* Reject all but VERSIONS and NETINFO when handshaking. */
  922. /* (VERSIONS should actually be impossible; it's variable-length.) */
  923. if (handshaking && cell->command != CELL_VERSIONS &&
  924. cell->command != CELL_NETINFO) {
  925. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  926. "Received unexpected cell command %d in chan state %s / "
  927. "conn state %s; closing the connection.",
  928. (int)cell->command,
  929. channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
  930. conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state));
  931. connection_or_close_for_error(conn, 0);
  932. return;
  933. }
  934. if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
  935. or_handshake_state_record_cell(conn, conn->handshake_state, cell, 1);
  936. /* We note that we're on the internet whenever we read a cell. This is
  937. * a fast operation. */
  938. entry_guards_note_internet_connectivity(get_guard_selection_info());
  939. rep_hist_padding_count_read(PADDING_TYPE_TOTAL);
  940. if (TLS_CHAN_TO_BASE(chan)->currently_padding)
  941. rep_hist_padding_count_read(PADDING_TYPE_ENABLED_TOTAL);
  942. switch (cell->command) {
  943. case CELL_PADDING:
  944. rep_hist_padding_count_read(PADDING_TYPE_CELL);
  945. if (TLS_CHAN_TO_BASE(chan)->currently_padding)
  946. rep_hist_padding_count_read(PADDING_TYPE_ENABLED_CELL);
  947. ++stats_n_padding_cells_processed;
  948. /* do nothing */
  949. break;
  950. case CELL_VERSIONS:
  951. tor_fragile_assert();
  952. break;
  953. case CELL_NETINFO:
  954. ++stats_n_netinfo_cells_processed;
  955. PROCESS_CELL(netinfo, cell, chan);
  956. break;
  957. case CELL_PADDING_NEGOTIATE:
  958. ++stats_n_netinfo_cells_processed;
  959. PROCESS_CELL(padding_negotiate, cell, chan);
  960. break;
  961. case CELL_CREATE:
  962. case CELL_CREATE_FAST:
  963. case CELL_CREATED:
  964. case CELL_CREATED_FAST:
  965. case CELL_RELAY:
  966. case CELL_RELAY_EARLY:
  967. case CELL_DESTROY:
  968. case CELL_CREATE2:
  969. case CELL_CREATED2:
  970. /*
  971. * These are all transport independent and we pass them up through the
  972. * channel_t mechanism. They are ultimately handled in command.c.
  973. */
  974. channel_process_cell(TLS_CHAN_TO_BASE(chan), cell);
  975. break;
  976. default:
  977. log_fn(LOG_INFO, LD_PROTOCOL,
  978. "Cell of unknown type (%d) received in channeltls.c. "
  979. "Dropping.",
  980. cell->command);
  981. break;
  982. }
  983. }
  984. /**
  985. * Handle an incoming variable-length cell on a channel_tls_t.
  986. *
  987. * Process a <b>var_cell</b> that was just received on <b>conn</b>. Keep
  988. * internal statistics about how many of each cell we've processed so far
  989. * this second, and the total number of microseconds it took to
  990. * process each type of cell. All the var_cell commands are handshake-
  991. * related and live below the channel_t layer, so no variable-length
  992. * cells ever get delivered in the current implementation, but I've left
  993. * the mechanism in place for future use.
  994. *
  995. * If we were handing them off to the upper layer, the channel_t queueing
  996. * code would be responsible for memory management, and we'd just be passing
  997. * pointers through from connection_or_process_cells_from_inbuf(). That
  998. * caller always frees them after this function returns, so this function
  999. * should never free var_cell.
  1000. */
  1001. void
  1002. channel_tls_handle_var_cell(var_cell_t *var_cell, or_connection_t *conn)
  1003. {
  1004. channel_tls_t *chan;
  1005. #ifdef KEEP_TIMING_STATS
  1006. /* how many of each cell have we seen so far this second? needs better
  1007. * name. */
  1008. static int num_versions = 0, num_certs = 0;
  1009. static time_t current_second = 0; /* from previous calls to time */
  1010. time_t now = time(NULL);
  1011. if (current_second == 0) current_second = now;
  1012. if (now > current_second) { /* the second has rolled over */
  1013. /* print stats */
  1014. log_info(LD_OR,
  1015. "At end of second: %d versions (%d ms), %d certs (%d ms)",
  1016. num_versions, versions_time / ((now - current_second) * 1000),
  1017. num_certs, certs_time / ((now - current_second) * 1000));
  1018. num_versions = num_certs = 0;
  1019. versions_time = certs_time = 0;
  1020. /* remember which second it is, for next time */
  1021. current_second = now;
  1022. }
  1023. #endif /* defined(KEEP_TIMING_STATS) */
  1024. tor_assert(var_cell);
  1025. tor_assert(conn);
  1026. chan = conn->chan;
  1027. if (!chan) {
  1028. log_warn(LD_CHANNEL,
  1029. "Got a var_cell_t on an OR connection with no channel");
  1030. return;
  1031. }
  1032. if (TO_CONN(conn)->marked_for_close)
  1033. return;
  1034. switch (TO_CONN(conn)->state) {
  1035. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  1036. if (var_cell->command != CELL_VERSIONS) {
  1037. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1038. "Received a cell with command %d in unexpected "
  1039. "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
  1040. "closing the connection.",
  1041. (int)(var_cell->command),
  1042. conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
  1043. TO_CONN(conn)->state,
  1044. channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
  1045. (int)(TLS_CHAN_TO_BASE(chan)->state));
  1046. /*
  1047. * The code in connection_or.c will tell channel_t to close for
  1048. * error; it will go to CHANNEL_STATE_CLOSING, and then to
  1049. * CHANNEL_STATE_ERROR when conn is closed.
  1050. */
  1051. connection_or_close_for_error(conn, 0);
  1052. return;
  1053. }
  1054. break;
  1055. case OR_CONN_STATE_TLS_HANDSHAKING:
  1056. /* If we're using bufferevents, it's entirely possible for us to
  1057. * notice "hey, data arrived!" before we notice "hey, the handshake
  1058. * finished!" And we need to be accepting both at once to handle both
  1059. * the v2 and v3 handshakes. */
  1060. /* But that should be happening any longer've disabled bufferevents. */
  1061. tor_assert_nonfatal_unreached_once();
  1062. /* fall through */
  1063. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  1064. if (!(command_allowed_before_handshake(var_cell->command))) {
  1065. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1066. "Received a cell with command %d in unexpected "
  1067. "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
  1068. "closing the connection.",
  1069. (int)(var_cell->command),
  1070. conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
  1071. (int)(TO_CONN(conn)->state),
  1072. channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
  1073. (int)(TLS_CHAN_TO_BASE(chan)->state));
  1074. /* see above comment about CHANNEL_STATE_ERROR */
  1075. connection_or_close_for_error(conn, 0);
  1076. return;
  1077. } else {
  1078. if (enter_v3_handshake_with_cell(var_cell, chan) < 0)
  1079. return;
  1080. }
  1081. break;
  1082. case OR_CONN_STATE_OR_HANDSHAKING_V3:
  1083. if (var_cell->command != CELL_AUTHENTICATE)
  1084. or_handshake_state_record_var_cell(conn, conn->handshake_state,
  1085. var_cell, 1);
  1086. break; /* Everything is allowed */
  1087. case OR_CONN_STATE_OPEN:
  1088. if (conn->link_proto < 3) {
  1089. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1090. "Received a variable-length cell with command %d in orconn "
  1091. "state %s [%d], channel state %s [%d] with link protocol %d; "
  1092. "ignoring it.",
  1093. (int)(var_cell->command),
  1094. conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
  1095. (int)(TO_CONN(conn)->state),
  1096. channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
  1097. (int)(TLS_CHAN_TO_BASE(chan)->state),
  1098. (int)(conn->link_proto));
  1099. return;
  1100. }
  1101. break;
  1102. default:
  1103. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1104. "Received var-length cell with command %d in unexpected "
  1105. "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
  1106. "ignoring it.",
  1107. (int)(var_cell->command),
  1108. conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
  1109. (int)(TO_CONN(conn)->state),
  1110. channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
  1111. (int)(TLS_CHAN_TO_BASE(chan)->state));
  1112. return;
  1113. }
  1114. /* We note that we're on the internet whenever we read a cell. This is
  1115. * a fast operation. */
  1116. entry_guards_note_internet_connectivity(get_guard_selection_info());
  1117. /* Now handle the cell */
  1118. switch (var_cell->command) {
  1119. case CELL_VERSIONS:
  1120. ++stats_n_versions_cells_processed;
  1121. PROCESS_CELL(versions, var_cell, chan);
  1122. break;
  1123. case CELL_VPADDING:
  1124. ++stats_n_vpadding_cells_processed;
  1125. /* Do nothing */
  1126. break;
  1127. case CELL_CERTS:
  1128. ++stats_n_certs_cells_processed;
  1129. PROCESS_CELL(certs, var_cell, chan);
  1130. break;
  1131. case CELL_AUTH_CHALLENGE:
  1132. ++stats_n_auth_challenge_cells_processed;
  1133. PROCESS_CELL(auth_challenge, var_cell, chan);
  1134. break;
  1135. case CELL_AUTHENTICATE:
  1136. ++stats_n_authenticate_cells_processed;
  1137. PROCESS_CELL(authenticate, var_cell, chan);
  1138. break;
  1139. case CELL_AUTHORIZE:
  1140. ++stats_n_authorize_cells_processed;
  1141. /* Ignored so far. */
  1142. break;
  1143. default:
  1144. log_fn(LOG_INFO, LD_PROTOCOL,
  1145. "Variable-length cell of unknown type (%d) received.",
  1146. (int)(var_cell->command));
  1147. break;
  1148. }
  1149. }
  1150. /**
  1151. * Update channel marks after connection_or.c has changed an address.
  1152. *
  1153. * This is called from connection_or_init_conn_from_address() after the
  1154. * connection's _base.addr or real_addr fields have potentially been changed
  1155. * so we can recalculate the local mark. Notably, this happens when incoming
  1156. * connections are reverse-proxied and we only learn the real address of the
  1157. * remote router by looking it up in the consensus after we finish the
  1158. * handshake and know an authenticated identity digest.
  1159. */
  1160. void
  1161. channel_tls_update_marks(or_connection_t *conn)
  1162. {
  1163. channel_t *chan = NULL;
  1164. tor_assert(conn);
  1165. tor_assert(conn->chan);
  1166. chan = TLS_CHAN_TO_BASE(conn->chan);
  1167. if (is_local_addr(&(TO_CONN(conn)->addr))) {
  1168. if (!channel_is_local(chan)) {
  1169. log_debug(LD_CHANNEL,
  1170. "Marking channel %"PRIu64 " at %p as local",
  1171. (chan->global_identifier), chan);
  1172. channel_mark_local(chan);
  1173. }
  1174. } else {
  1175. if (channel_is_local(chan)) {
  1176. log_debug(LD_CHANNEL,
  1177. "Marking channel %"PRIu64 " at %p as remote",
  1178. (chan->global_identifier), chan);
  1179. channel_mark_remote(chan);
  1180. }
  1181. }
  1182. }
  1183. /**
  1184. * Check if this cell type is allowed before the handshake is finished.
  1185. *
  1186. * Return true if <b>command</b> is a cell command that's allowed to start a
  1187. * V3 handshake.
  1188. */
  1189. static int
  1190. command_allowed_before_handshake(uint8_t command)
  1191. {
  1192. switch (command) {
  1193. case CELL_VERSIONS:
  1194. case CELL_VPADDING:
  1195. case CELL_AUTHORIZE:
  1196. return 1;
  1197. default:
  1198. return 0;
  1199. }
  1200. }
  1201. /**
  1202. * Start a V3 handshake on an incoming connection.
  1203. *
  1204. * Called when we as a server receive an appropriate cell while waiting
  1205. * either for a cell or a TLS handshake. Set the connection's state to
  1206. * "handshaking_v3', initializes the or_handshake_state field as needed,
  1207. * and add the cell to the hash of incoming cells.)
  1208. */
  1209. static int
  1210. enter_v3_handshake_with_cell(var_cell_t *cell, channel_tls_t *chan)
  1211. {
  1212. int started_here = 0;
  1213. tor_assert(cell);
  1214. tor_assert(chan);
  1215. tor_assert(chan->conn);
  1216. started_here = connection_or_nonopen_was_started_here(chan->conn);
  1217. tor_assert(TO_CONN(chan->conn)->state == OR_CONN_STATE_TLS_HANDSHAKING ||
  1218. TO_CONN(chan->conn)->state ==
  1219. OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
  1220. if (started_here) {
  1221. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1222. "Received a cell while TLS-handshaking, not in "
  1223. "OR_HANDSHAKING_V3, on a connection we originated.");
  1224. }
  1225. connection_or_block_renegotiation(chan->conn);
  1226. chan->conn->base_.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
  1227. if (connection_init_or_handshake_state(chan->conn, started_here) < 0) {
  1228. connection_or_close_for_error(chan->conn, 0);
  1229. return -1;
  1230. }
  1231. or_handshake_state_record_var_cell(chan->conn,
  1232. chan->conn->handshake_state, cell, 1);
  1233. return 0;
  1234. }
  1235. /**
  1236. * Process a 'versions' cell.
  1237. *
  1238. * This function is called to handle an incoming VERSIONS cell; the current
  1239. * link protocol version must be 0 to indicate that no version has yet been
  1240. * negotiated. We compare the versions in the cell to the list of versions
  1241. * we support, pick the highest version we have in common, and continue the
  1242. * negotiation from there.
  1243. */
  1244. static void
  1245. channel_tls_process_versions_cell(var_cell_t *cell, channel_tls_t *chan)
  1246. {
  1247. int highest_supported_version = 0;
  1248. int started_here = 0;
  1249. tor_assert(cell);
  1250. tor_assert(chan);
  1251. tor_assert(chan->conn);
  1252. if ((cell->payload_len % 2) == 1) {
  1253. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1254. "Received a VERSION cell with odd payload length %d; "
  1255. "closing connection.",cell->payload_len);
  1256. connection_or_close_for_error(chan->conn, 0);
  1257. return;
  1258. }
  1259. started_here = connection_or_nonopen_was_started_here(chan->conn);
  1260. if (chan->conn->link_proto != 0 ||
  1261. (chan->conn->handshake_state &&
  1262. chan->conn->handshake_state->received_versions)) {
  1263. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1264. "Received a VERSIONS cell on a connection with its version "
  1265. "already set to %d; dropping",
  1266. (int)(chan->conn->link_proto));
  1267. return;
  1268. }
  1269. switch (chan->conn->base_.state)
  1270. {
  1271. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  1272. case OR_CONN_STATE_OR_HANDSHAKING_V3:
  1273. break;
  1274. case OR_CONN_STATE_TLS_HANDSHAKING:
  1275. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  1276. default:
  1277. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1278. "VERSIONS cell while in unexpected state");
  1279. return;
  1280. }
  1281. tor_assert(chan->conn->handshake_state);
  1282. {
  1283. int i;
  1284. const uint8_t *cp = cell->payload;
  1285. for (i = 0; i < cell->payload_len / 2; ++i, cp += 2) {
  1286. uint16_t v = ntohs(get_uint16(cp));
  1287. if (is_or_protocol_version_known(v) && v > highest_supported_version)
  1288. highest_supported_version = v;
  1289. }
  1290. }
  1291. if (!highest_supported_version) {
  1292. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1293. "Couldn't find a version in common between my version list and the "
  1294. "list in the VERSIONS cell; closing connection.");
  1295. connection_or_close_for_error(chan->conn, 0);
  1296. return;
  1297. } else if (highest_supported_version == 1) {
  1298. /* Negotiating version 1 makes no sense, since version 1 has no VERSIONS
  1299. * cells. */
  1300. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1301. "Used version negotiation protocol to negotiate a v1 connection. "
  1302. "That's crazily non-compliant. Closing connection.");
  1303. connection_or_close_for_error(chan->conn, 0);
  1304. return;
  1305. } else if (highest_supported_version < 3 &&
  1306. chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
  1307. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1308. "Negotiated link protocol 2 or lower after doing a v3 TLS "
  1309. "handshake. Closing connection.");
  1310. connection_or_close_for_error(chan->conn, 0);
  1311. return;
  1312. } else if (highest_supported_version != 2 &&
  1313. chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V2) {
  1314. /* XXXX This should eventually be a log_protocol_warn */
  1315. log_fn(LOG_WARN, LD_OR,
  1316. "Negotiated link with non-2 protocol after doing a v2 TLS "
  1317. "handshake with %s. Closing connection.",
  1318. fmt_addr(&chan->conn->base_.addr));
  1319. connection_or_close_for_error(chan->conn, 0);
  1320. return;
  1321. }
  1322. rep_hist_note_negotiated_link_proto(highest_supported_version, started_here);
  1323. chan->conn->link_proto = highest_supported_version;
  1324. chan->conn->handshake_state->received_versions = 1;
  1325. if (chan->conn->link_proto == 2) {
  1326. log_info(LD_OR,
  1327. "Negotiated version %d with %s:%d; sending NETINFO.",
  1328. highest_supported_version,
  1329. safe_str_client(chan->conn->base_.address),
  1330. chan->conn->base_.port);
  1331. if (connection_or_send_netinfo(chan->conn) < 0) {
  1332. connection_or_close_for_error(chan->conn, 0);
  1333. return;
  1334. }
  1335. } else {
  1336. const int send_versions = !started_here;
  1337. /* If we want to authenticate, send a CERTS cell */
  1338. const int send_certs = !started_here || public_server_mode(get_options());
  1339. /* If we're a host that got a connection, ask for authentication. */
  1340. const int send_chall = !started_here;
  1341. /* If our certs cell will authenticate us, we can send a netinfo cell
  1342. * right now. */
  1343. const int send_netinfo = !started_here;
  1344. const int send_any =
  1345. send_versions || send_certs || send_chall || send_netinfo;
  1346. tor_assert(chan->conn->link_proto >= 3);
  1347. log_info(LD_OR,
  1348. "Negotiated version %d with %s:%d; %s%s%s%s%s",
  1349. highest_supported_version,
  1350. safe_str_client(chan->conn->base_.address),
  1351. chan->conn->base_.port,
  1352. send_any ? "Sending cells:" : "Waiting for CERTS cell",
  1353. send_versions ? " VERSIONS" : "",
  1354. send_certs ? " CERTS" : "",
  1355. send_chall ? " AUTH_CHALLENGE" : "",
  1356. send_netinfo ? " NETINFO" : "");
  1357. #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
  1358. if (1) {
  1359. connection_or_close_normally(chan->conn, 1);
  1360. return;
  1361. }
  1362. #endif /* defined(DISABLE_V3_LINKPROTO_SERVERSIDE) */
  1363. if (send_versions) {
  1364. if (connection_or_send_versions(chan->conn, 1) < 0) {
  1365. log_warn(LD_OR, "Couldn't send versions cell");
  1366. connection_or_close_for_error(chan->conn, 0);
  1367. return;
  1368. }
  1369. }
  1370. /* We set this after sending the versions cell. */
  1371. /*XXXXX symbolic const.*/
  1372. TLS_CHAN_TO_BASE(chan)->wide_circ_ids =
  1373. chan->conn->link_proto >= MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS;
  1374. chan->conn->wide_circ_ids = TLS_CHAN_TO_BASE(chan)->wide_circ_ids;
  1375. TLS_CHAN_TO_BASE(chan)->padding_enabled =
  1376. chan->conn->link_proto >= MIN_LINK_PROTO_FOR_CHANNEL_PADDING;
  1377. if (send_certs) {
  1378. if (connection_or_send_certs_cell(chan->conn) < 0) {
  1379. log_warn(LD_OR, "Couldn't send certs cell");
  1380. connection_or_close_for_error(chan->conn, 0);
  1381. return;
  1382. }
  1383. }
  1384. if (send_chall) {
  1385. if (connection_or_send_auth_challenge_cell(chan->conn) < 0) {
  1386. log_warn(LD_OR, "Couldn't send auth_challenge cell");
  1387. connection_or_close_for_error(chan->conn, 0);
  1388. return;
  1389. }
  1390. }
  1391. if (send_netinfo) {
  1392. if (connection_or_send_netinfo(chan->conn) < 0) {
  1393. log_warn(LD_OR, "Couldn't send netinfo cell");
  1394. connection_or_close_for_error(chan->conn, 0);
  1395. return;
  1396. }
  1397. }
  1398. }
  1399. }
  1400. /**
  1401. * Process a 'padding_negotiate' cell.
  1402. *
  1403. * This function is called to handle an incoming PADDING_NEGOTIATE cell;
  1404. * enable or disable padding accordingly, and read and act on its timeout
  1405. * value contents.
  1406. */
  1407. static void
  1408. channel_tls_process_padding_negotiate_cell(cell_t *cell, channel_tls_t *chan)
  1409. {
  1410. channelpadding_negotiate_t *negotiation;
  1411. tor_assert(cell);
  1412. tor_assert(chan);
  1413. tor_assert(chan->conn);
  1414. if (chan->conn->link_proto < MIN_LINK_PROTO_FOR_CHANNEL_PADDING) {
  1415. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1416. "Received a PADDING_NEGOTIATE cell on v%d connection; dropping.",
  1417. chan->conn->link_proto);
  1418. return;
  1419. }
  1420. if (channelpadding_negotiate_parse(&negotiation, cell->payload,
  1421. CELL_PAYLOAD_SIZE) < 0) {
  1422. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1423. "Received malformed PADDING_NEGOTIATE cell on v%d connection; "
  1424. "dropping.", chan->conn->link_proto);
  1425. return;
  1426. }
  1427. channelpadding_update_padding_for_channel(TLS_CHAN_TO_BASE(chan),
  1428. negotiation);
  1429. channelpadding_negotiate_free(negotiation);
  1430. }
  1431. /**
  1432. * Convert <b>netinfo_addr</b> into corresponding <b>tor_addr</b>.
  1433. * Return 0 on success; on failure, return -1 and log a warning.
  1434. */
  1435. static int
  1436. tor_addr_from_netinfo_addr(tor_addr_t *tor_addr,
  1437. const netinfo_addr_t *netinfo_addr) {
  1438. tor_assert(tor_addr);
  1439. tor_assert(netinfo_addr);
  1440. uint8_t type = netinfo_addr_get_addr_type(netinfo_addr);
  1441. uint8_t len = netinfo_addr_get_len(netinfo_addr);
  1442. if (type == NETINFO_ADDR_TYPE_IPV4 && len == 4) {
  1443. uint32_t ipv4 = netinfo_addr_get_addr_ipv4(netinfo_addr);
  1444. tor_addr_from_ipv4h(tor_addr, ipv4);
  1445. } else if (type == NETINFO_ADDR_TYPE_IPV6 && len == 16) {
  1446. const uint8_t *ipv6_bytes = netinfo_addr_getconstarray_addr_ipv6(
  1447. netinfo_addr);
  1448. tor_addr_from_ipv6_bytes(tor_addr, (const char *)ipv6_bytes);
  1449. } else {
  1450. log_fn(LOG_PROTOCOL_WARN, LD_OR, "Cannot read address from NETINFO "
  1451. "- wrong type/length.");
  1452. return -1;
  1453. }
  1454. return 0;
  1455. }
  1456. /**
  1457. * Process a 'netinfo' cell.
  1458. *
  1459. * This function is called to handle an incoming NETINFO cell; read and act
  1460. * on its contents, and set the connection state to "open".
  1461. */
  1462. static void
  1463. channel_tls_process_netinfo_cell(cell_t *cell, channel_tls_t *chan)
  1464. {
  1465. time_t timestamp;
  1466. uint8_t my_addr_type;
  1467. uint8_t my_addr_len;
  1468. uint8_t n_other_addrs;
  1469. time_t now = time(NULL);
  1470. const routerinfo_t *me = router_get_my_routerinfo();
  1471. long apparent_skew = 0;
  1472. tor_addr_t my_apparent_addr = TOR_ADDR_NULL;
  1473. int started_here = 0;
  1474. const char *identity_digest = NULL;
  1475. tor_assert(cell);
  1476. tor_assert(chan);
  1477. tor_assert(chan->conn);
  1478. if (chan->conn->link_proto < 2) {
  1479. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1480. "Received a NETINFO cell on %s connection; dropping.",
  1481. chan->conn->link_proto == 0 ? "non-versioned" : "a v1");
  1482. return;
  1483. }
  1484. if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V2 &&
  1485. chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3) {
  1486. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1487. "Received a NETINFO cell on non-handshaking connection; dropping.");
  1488. return;
  1489. }
  1490. tor_assert(chan->conn->handshake_state &&
  1491. chan->conn->handshake_state->received_versions);
  1492. started_here = connection_or_nonopen_was_started_here(chan->conn);
  1493. identity_digest = chan->conn->identity_digest;
  1494. if (chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
  1495. tor_assert(chan->conn->link_proto >= 3);
  1496. if (started_here) {
  1497. if (!(chan->conn->handshake_state->authenticated)) {
  1498. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1499. "Got a NETINFO cell from server, "
  1500. "but no authentication. Closing the connection.");
  1501. connection_or_close_for_error(chan->conn, 0);
  1502. return;
  1503. }
  1504. } else {
  1505. /* we're the server. If the client never authenticated, we have
  1506. some housekeeping to do.*/
  1507. if (!(chan->conn->handshake_state->authenticated)) {
  1508. tor_assert(tor_digest_is_zero(
  1509. (const char*)(chan->conn->handshake_state->
  1510. authenticated_rsa_peer_id)));
  1511. tor_assert(tor_mem_is_zero(
  1512. (const char*)(chan->conn->handshake_state->
  1513. authenticated_ed25519_peer_id.pubkey), 32));
  1514. /* If the client never authenticated, it's a tor client or bridge
  1515. * relay, and we must not use it for EXTEND requests (nor could we, as
  1516. * there are no authenticated peer IDs) */
  1517. channel_mark_client(TLS_CHAN_TO_BASE(chan));
  1518. channel_set_circid_type(TLS_CHAN_TO_BASE(chan), NULL,
  1519. chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
  1520. connection_or_init_conn_from_address(chan->conn,
  1521. &(chan->conn->base_.addr),
  1522. chan->conn->base_.port,
  1523. /* zero, checked above */
  1524. (const char*)(chan->conn->handshake_state->
  1525. authenticated_rsa_peer_id),
  1526. NULL, /* Ed25519 ID: Also checked as zero */
  1527. 0);
  1528. }
  1529. }
  1530. }
  1531. /* Decode the cell. */
  1532. netinfo_cell_t *netinfo_cell = NULL;
  1533. ssize_t parsed = netinfo_cell_parse(&netinfo_cell, cell->payload,
  1534. CELL_PAYLOAD_SIZE);
  1535. if (parsed < 0) {
  1536. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1537. "Failed to parse NETINFO cell - closing connection.");
  1538. connection_or_close_for_error(chan->conn, 0);
  1539. return;
  1540. }
  1541. timestamp = netinfo_cell_get_timestamp(netinfo_cell);
  1542. const netinfo_addr_t *my_addr =
  1543. netinfo_cell_getconst_other_addr(netinfo_cell);
  1544. my_addr_type = netinfo_addr_get_addr_type(my_addr);
  1545. my_addr_len = netinfo_addr_get_len(my_addr);
  1546. if (labs(now - chan->conn->handshake_state->sent_versions_at) < 180) {
  1547. apparent_skew = now - timestamp;
  1548. }
  1549. /* We used to check:
  1550. * if (my_addr_len >= CELL_PAYLOAD_SIZE - 6) {
  1551. *
  1552. * This is actually never going to happen, since my_addr_len is at most 255,
  1553. * and CELL_PAYLOAD_LEN - 6 is 503. So we know that cp is < end. */
  1554. if (tor_addr_from_netinfo_addr(&my_apparent_addr, my_addr) == -1) {
  1555. connection_or_close_for_error(chan->conn, 0);
  1556. netinfo_cell_free(netinfo_cell);
  1557. return;
  1558. }
  1559. if (my_addr_type == NETINFO_ADDR_TYPE_IPV4 && my_addr_len == 4) {
  1560. if (!get_options()->BridgeRelay && me &&
  1561. tor_addr_eq_ipv4h(&my_apparent_addr, me->addr)) {
  1562. TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer = 1;
  1563. }
  1564. } else if (my_addr_type == NETINFO_ADDR_TYPE_IPV6 &&
  1565. my_addr_len == 16) {
  1566. if (!get_options()->BridgeRelay && me &&
  1567. !tor_addr_is_null(&me->ipv6_addr) &&
  1568. tor_addr_eq(&my_apparent_addr, &me->ipv6_addr)) {
  1569. TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer = 1;
  1570. }
  1571. }
  1572. n_other_addrs = netinfo_cell_get_n_my_addrs(netinfo_cell);
  1573. for (uint8_t i = 0; i < n_other_addrs; i++) {
  1574. /* Consider all the other addresses; if any matches, this connection is
  1575. * "canonical." */
  1576. const netinfo_addr_t *netinfo_addr =
  1577. netinfo_cell_getconst_my_addrs(netinfo_cell, i);
  1578. tor_addr_t addr;
  1579. if (tor_addr_from_netinfo_addr(&addr, netinfo_addr) == -1) {
  1580. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1581. "Bad address in netinfo cell; Skipping.");
  1582. continue;
  1583. }
  1584. /* A relay can connect from anywhere and be canonical, so
  1585. * long as it tells you from where it came. This may sound a bit
  1586. * concerning... but that's what "canonical" means: that the
  1587. * address is one that the relay itself has claimed. The relay
  1588. * might be doing something funny, but nobody else is doing a MITM
  1589. * on the relay's TCP.
  1590. */
  1591. if (tor_addr_eq(&addr, &(chan->conn->real_addr))) {
  1592. connection_or_set_canonical(chan->conn, 1);
  1593. break;
  1594. }
  1595. }
  1596. netinfo_cell_free(netinfo_cell);
  1597. if (me && !TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer &&
  1598. channel_is_canonical(TLS_CHAN_TO_BASE(chan))) {
  1599. const char *descr =
  1600. TLS_CHAN_TO_BASE(chan)->get_remote_descr(TLS_CHAN_TO_BASE(chan), 0);
  1601. log_info(LD_OR,
  1602. "We made a connection to a relay at %s (fp=%s) but we think "
  1603. "they will not consider this connection canonical. They "
  1604. "think we are at %s, but we think its %s.",
  1605. safe_str(descr),
  1606. safe_str(hex_str(identity_digest, DIGEST_LEN)),
  1607. safe_str(tor_addr_is_null(&my_apparent_addr) ?
  1608. "<none>" : fmt_and_decorate_addr(&my_apparent_addr)),
  1609. safe_str(fmt_addr32(me->addr)));
  1610. }
  1611. /* Act on apparent skew. */
  1612. /** Warn when we get a netinfo skew with at least this value. */
  1613. #define NETINFO_NOTICE_SKEW 3600
  1614. if (labs(apparent_skew) > NETINFO_NOTICE_SKEW &&
  1615. (started_here ||
  1616. connection_or_digest_is_known_relay(chan->conn->identity_digest))) {
  1617. int trusted = router_digest_is_trusted_dir(chan->conn->identity_digest);
  1618. clock_skew_warning(TO_CONN(chan->conn), apparent_skew, trusted, LD_GENERAL,
  1619. "NETINFO cell", "OR");
  1620. }
  1621. /* XXX maybe act on my_apparent_addr, if the source is sufficiently
  1622. * trustworthy. */
  1623. if (! chan->conn->handshake_state->sent_netinfo) {
  1624. /* If we were prepared to authenticate, but we never got an AUTH_CHALLENGE
  1625. * cell, then we would not previously have sent a NETINFO cell. Do so
  1626. * now. */
  1627. if (connection_or_send_netinfo(chan->conn) < 0) {
  1628. connection_or_close_for_error(chan->conn, 0);
  1629. return;
  1630. }
  1631. }
  1632. if (connection_or_set_state_open(chan->conn) < 0) {
  1633. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1634. "Got good NETINFO cell from %s:%d; but "
  1635. "was unable to make the OR connection become open.",
  1636. safe_str_client(chan->conn->base_.address),
  1637. chan->conn->base_.port);
  1638. connection_or_close_for_error(chan->conn, 0);
  1639. } else {
  1640. log_info(LD_OR,
  1641. "Got good NETINFO cell from %s:%d; OR connection is now "
  1642. "open, using protocol version %d. Its ID digest is %s. "
  1643. "Our address is apparently %s.",
  1644. safe_str_client(chan->conn->base_.address),
  1645. chan->conn->base_.port,
  1646. (int)(chan->conn->link_proto),
  1647. hex_str(identity_digest, DIGEST_LEN),
  1648. tor_addr_is_null(&my_apparent_addr) ?
  1649. "<none>" :
  1650. safe_str_client(fmt_and_decorate_addr(&my_apparent_addr)));
  1651. }
  1652. assert_connection_ok(TO_CONN(chan->conn),time(NULL));
  1653. }
  1654. /** Types of certificates that we know how to parse from CERTS cells. Each
  1655. * type corresponds to a different encoding format. */
  1656. typedef enum cert_encoding_t {
  1657. CERT_ENCODING_UNKNOWN, /**< We don't recognize this. */
  1658. CERT_ENCODING_X509, /**< It's an RSA key, signed with RSA, encoded in x509.
  1659. * (Actually, it might not be RSA. We test that later.) */
  1660. CERT_ENCODING_ED25519, /**< It's something signed with an Ed25519 key,
  1661. * encoded asa a tor_cert_t.*/
  1662. CERT_ENCODING_RSA_CROSSCERT, /**< It's an Ed key signed with an RSA key. */
  1663. } cert_encoding_t;
  1664. /**
  1665. * Given one of the certificate type codes used in a CERTS cell,
  1666. * return the corresponding cert_encoding_t that we should use to parse
  1667. * the certificate.
  1668. */
  1669. static cert_encoding_t
  1670. certs_cell_typenum_to_cert_type(int typenum)
  1671. {
  1672. switch (typenum) {
  1673. case CERTTYPE_RSA1024_ID_LINK:
  1674. case CERTTYPE_RSA1024_ID_ID:
  1675. case CERTTYPE_RSA1024_ID_AUTH:
  1676. return CERT_ENCODING_X509;
  1677. case CERTTYPE_ED_ID_SIGN:
  1678. case CERTTYPE_ED_SIGN_LINK:
  1679. case CERTTYPE_ED_SIGN_AUTH:
  1680. return CERT_ENCODING_ED25519;
  1681. case CERTTYPE_RSA1024_ID_EDID:
  1682. return CERT_ENCODING_RSA_CROSSCERT;
  1683. default:
  1684. return CERT_ENCODING_UNKNOWN;
  1685. }
  1686. }
  1687. /**
  1688. * Process a CERTS cell from a channel.
  1689. *
  1690. * This function is called to process an incoming CERTS cell on a
  1691. * channel_tls_t:
  1692. *
  1693. * If the other side should not have sent us a CERTS cell, or the cell is
  1694. * malformed, or it is supposed to authenticate the TLS key but it doesn't,
  1695. * then mark the connection.
  1696. *
  1697. * If the cell has a good cert chain and we're doing a v3 handshake, then
  1698. * store the certificates in or_handshake_state. If this is the client side
  1699. * of the connection, we then authenticate the server or mark the connection.
  1700. * If it's the server side, wait for an AUTHENTICATE cell.
  1701. */
  1702. STATIC void
  1703. channel_tls_process_certs_cell(var_cell_t *cell, channel_tls_t *chan)
  1704. {
  1705. #define MAX_CERT_TYPE_WANTED CERTTYPE_RSA1024_ID_EDID
  1706. /* These arrays will be sparse, since a cert type can be at most one
  1707. * of ed/x509 */
  1708. tor_x509_cert_t *x509_certs[MAX_CERT_TYPE_WANTED + 1];
  1709. tor_cert_t *ed_certs[MAX_CERT_TYPE_WANTED + 1];
  1710. uint8_t *rsa_ed_cc_cert = NULL;
  1711. size_t rsa_ed_cc_cert_len = 0;
  1712. int n_certs, i;
  1713. certs_cell_t *cc = NULL;
  1714. int send_netinfo = 0, started_here = 0;
  1715. memset(x509_certs, 0, sizeof(x509_certs));
  1716. memset(ed_certs, 0, sizeof(ed_certs));
  1717. tor_assert(cell);
  1718. tor_assert(chan);
  1719. tor_assert(chan->conn);
  1720. #define ERR(s) \
  1721. do { \
  1722. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
  1723. "Received a bad CERTS cell from %s:%d: %s", \
  1724. safe_str(chan->conn->base_.address), \
  1725. chan->conn->base_.port, (s)); \
  1726. connection_or_close_for_error(chan->conn, 0); \
  1727. goto err; \
  1728. } while (0)
  1729. /* Can't use connection_or_nonopen_was_started_here(); its conn->tls
  1730. * check looks like it breaks
  1731. * test_link_handshake_recv_certs_ok_server(). */
  1732. started_here = chan->conn->handshake_state->started_here;
  1733. if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
  1734. ERR("We're not doing a v3 handshake!");
  1735. if (chan->conn->link_proto < 3)
  1736. ERR("We're not using link protocol >= 3");
  1737. if (chan->conn->handshake_state->received_certs_cell)
  1738. ERR("We already got one");
  1739. if (chan->conn->handshake_state->authenticated) {
  1740. /* Should be unreachable, but let's make sure. */
  1741. ERR("We're already authenticated!");
  1742. }
  1743. if (cell->payload_len < 1)
  1744. ERR("It had no body");
  1745. if (cell->circ_id)
  1746. ERR("It had a nonzero circuit ID");
  1747. if (certs_cell_parse(&cc, cell->payload, cell->payload_len) < 0)
  1748. ERR("It couldn't be parsed.");
  1749. n_certs = cc->n_certs;
  1750. for (i = 0; i < n_certs; ++i) {
  1751. certs_cell_cert_t *c = certs_cell_get_certs(cc, i);
  1752. uint16_t cert_type = c->cert_type;
  1753. uint16_t cert_len = c->cert_len;
  1754. uint8_t *cert_body = certs_cell_cert_getarray_body(c);
  1755. if (cert_type > MAX_CERT_TYPE_WANTED)
  1756. continue;
  1757. const cert_encoding_t ct = certs_cell_typenum_to_cert_type(cert_type);
  1758. switch (ct) {
  1759. default:
  1760. case CERT_ENCODING_UNKNOWN:
  1761. break;
  1762. case CERT_ENCODING_X509: {
  1763. tor_x509_cert_t *x509_cert = tor_x509_cert_decode(cert_body, cert_len);
  1764. if (!x509_cert) {
  1765. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1766. "Received undecodable certificate in CERTS cell from %s:%d",
  1767. safe_str(chan->conn->base_.address),
  1768. chan->conn->base_.port);
  1769. } else {
  1770. if (x509_certs[cert_type]) {
  1771. tor_x509_cert_free(x509_cert);
  1772. ERR("Duplicate x509 certificate");
  1773. } else {
  1774. x509_certs[cert_type] = x509_cert;
  1775. }
  1776. }
  1777. break;
  1778. }
  1779. case CERT_ENCODING_ED25519: {
  1780. tor_cert_t *ed_cert = tor_cert_parse(cert_body, cert_len);
  1781. if (!ed_cert) {
  1782. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1783. "Received undecodable Ed certificate "
  1784. "in CERTS cell from %s:%d",
  1785. safe_str(chan->conn->base_.address),
  1786. chan->conn->base_.port);
  1787. } else {
  1788. if (ed_certs[cert_type]) {
  1789. tor_cert_free(ed_cert);
  1790. ERR("Duplicate Ed25519 certificate");
  1791. } else {
  1792. ed_certs[cert_type] = ed_cert;
  1793. }
  1794. }
  1795. break;
  1796. }
  1797. case CERT_ENCODING_RSA_CROSSCERT: {
  1798. if (rsa_ed_cc_cert) {
  1799. ERR("Duplicate RSA->Ed25519 crosscert");
  1800. } else {
  1801. rsa_ed_cc_cert = tor_memdup(cert_body, cert_len);
  1802. rsa_ed_cc_cert_len = cert_len;
  1803. }
  1804. break;
  1805. }
  1806. }
  1807. }
  1808. /* Move the certificates we (might) want into the handshake_state->certs
  1809. * structure. */
  1810. tor_x509_cert_t *id_cert = x509_certs[CERTTYPE_RSA1024_ID_ID];
  1811. tor_x509_cert_t *auth_cert = x509_certs[CERTTYPE_RSA1024_ID_AUTH];
  1812. tor_x509_cert_t *link_cert = x509_certs[CERTTYPE_RSA1024_ID_LINK];
  1813. chan->conn->handshake_state->certs->auth_cert = auth_cert;
  1814. chan->conn->handshake_state->certs->link_cert = link_cert;
  1815. chan->conn->handshake_state->certs->id_cert = id_cert;
  1816. x509_certs[CERTTYPE_RSA1024_ID_ID] =
  1817. x509_certs[CERTTYPE_RSA1024_ID_AUTH] =
  1818. x509_certs[CERTTYPE_RSA1024_ID_LINK] = NULL;
  1819. tor_cert_t *ed_id_sign = ed_certs[CERTTYPE_ED_ID_SIGN];
  1820. tor_cert_t *ed_sign_link = ed_certs[CERTTYPE_ED_SIGN_LINK];
  1821. tor_cert_t *ed_sign_auth = ed_certs[CERTTYPE_ED_SIGN_AUTH];
  1822. chan->conn->handshake_state->certs->ed_id_sign = ed_id_sign;
  1823. chan->conn->handshake_state->certs->ed_sign_link = ed_sign_link;
  1824. chan->conn->handshake_state->certs->ed_sign_auth = ed_sign_auth;
  1825. ed_certs[CERTTYPE_ED_ID_SIGN] =
  1826. ed_certs[CERTTYPE_ED_SIGN_LINK] =
  1827. ed_certs[CERTTYPE_ED_SIGN_AUTH] = NULL;
  1828. chan->conn->handshake_state->certs->ed_rsa_crosscert = rsa_ed_cc_cert;
  1829. chan->conn->handshake_state->certs->ed_rsa_crosscert_len =
  1830. rsa_ed_cc_cert_len;
  1831. rsa_ed_cc_cert = NULL;
  1832. int severity;
  1833. /* Note that this warns more loudly about time and validity if we were
  1834. * _trying_ to connect to an authority, not necessarily if we _did_ connect
  1835. * to one. */
  1836. if (started_here &&
  1837. router_digest_is_trusted_dir(TLS_CHAN_TO_BASE(chan)->identity_digest))
  1838. severity = LOG_WARN;
  1839. else
  1840. severity = LOG_PROTOCOL_WARN;
  1841. const ed25519_public_key_t *checked_ed_id = NULL;
  1842. const common_digests_t *checked_rsa_id = NULL;
  1843. or_handshake_certs_check_both(severity,
  1844. chan->conn->handshake_state->certs,
  1845. chan->conn->tls,
  1846. time(NULL),
  1847. &checked_ed_id,
  1848. &checked_rsa_id);
  1849. if (!checked_rsa_id)
  1850. ERR("Invalid certificate chain!");
  1851. if (started_here) {
  1852. /* No more information is needed. */
  1853. chan->conn->handshake_state->authenticated = 1;
  1854. chan->conn->handshake_state->authenticated_rsa = 1;
  1855. {
  1856. const common_digests_t *id_digests = checked_rsa_id;
  1857. crypto_pk_t *identity_rcvd;
  1858. if (!id_digests)
  1859. ERR("Couldn't compute digests for key in ID cert");
  1860. identity_rcvd = tor_tls_cert_get_key(id_cert);
  1861. if (!identity_rcvd) {
  1862. ERR("Couldn't get RSA key from ID cert.");
  1863. }
  1864. memcpy(chan->conn->handshake_state->authenticated_rsa_peer_id,
  1865. id_digests->d[DIGEST_SHA1], DIGEST_LEN);
  1866. channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
  1867. chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
  1868. crypto_pk_free(identity_rcvd);
  1869. }
  1870. if (checked_ed_id) {
  1871. chan->conn->handshake_state->authenticated_ed25519 = 1;
  1872. memcpy(&chan->conn->handshake_state->authenticated_ed25519_peer_id,
  1873. checked_ed_id, sizeof(ed25519_public_key_t));
  1874. }
  1875. log_debug(LD_HANDSHAKE, "calling client_learned_peer_id from "
  1876. "process_certs_cell");
  1877. if (connection_or_client_learned_peer_id(chan->conn,
  1878. chan->conn->handshake_state->authenticated_rsa_peer_id,
  1879. checked_ed_id) < 0)
  1880. ERR("Problem setting or checking peer id");
  1881. log_info(LD_HANDSHAKE,
  1882. "Got some good certificates from %s:%d: Authenticated it with "
  1883. "RSA%s",
  1884. safe_str(chan->conn->base_.address), chan->conn->base_.port,
  1885. checked_ed_id ? " and Ed25519" : "");
  1886. if (!public_server_mode(get_options())) {
  1887. /* If we initiated the connection and we are not a public server, we
  1888. * aren't planning to authenticate at all. At this point we know who we
  1889. * are talking to, so we can just send a netinfo now. */
  1890. send_netinfo = 1;
  1891. }
  1892. } else {
  1893. /* We can't call it authenticated till we see an AUTHENTICATE cell. */
  1894. log_info(LD_OR,
  1895. "Got some good RSA%s certificates from %s:%d. "
  1896. "Waiting for AUTHENTICATE.",
  1897. checked_ed_id ? " and Ed25519" : "",
  1898. safe_str(chan->conn->base_.address),
  1899. chan->conn->base_.port);
  1900. /* XXXX check more stuff? */
  1901. }
  1902. chan->conn->handshake_state->received_certs_cell = 1;
  1903. if (send_netinfo) {
  1904. if (connection_or_send_netinfo(chan->conn) < 0) {
  1905. log_warn(LD_OR, "Couldn't send netinfo cell");
  1906. connection_or_close_for_error(chan->conn, 0);
  1907. goto err;
  1908. }
  1909. }
  1910. err:
  1911. for (unsigned u = 0; u < ARRAY_LENGTH(x509_certs); ++u) {
  1912. tor_x509_cert_free(x509_certs[u]);
  1913. }
  1914. for (unsigned u = 0; u < ARRAY_LENGTH(ed_certs); ++u) {
  1915. tor_cert_free(ed_certs[u]);
  1916. }
  1917. tor_free(rsa_ed_cc_cert);
  1918. certs_cell_free(cc);
  1919. #undef ERR
  1920. }
  1921. /**
  1922. * Process an AUTH_CHALLENGE cell from a channel_tls_t.
  1923. *
  1924. * This function is called to handle an incoming AUTH_CHALLENGE cell on a
  1925. * channel_tls_t; if we weren't supposed to get one (for example, because we're
  1926. * not the originator of the channel), or it's ill-formed, or we aren't doing
  1927. * a v3 handshake, mark the channel. If the cell is well-formed but we don't
  1928. * want to authenticate, just drop it. If the cell is well-formed *and* we
  1929. * want to authenticate, send an AUTHENTICATE cell and then a NETINFO cell.
  1930. */
  1931. STATIC void
  1932. channel_tls_process_auth_challenge_cell(var_cell_t *cell, channel_tls_t *chan)
  1933. {
  1934. int n_types, i, use_type = -1;
  1935. auth_challenge_cell_t *ac = NULL;
  1936. tor_assert(cell);
  1937. tor_assert(chan);
  1938. tor_assert(chan->conn);
  1939. #define ERR(s) \
  1940. do { \
  1941. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
  1942. "Received a bad AUTH_CHALLENGE cell from %s:%d: %s", \
  1943. safe_str(chan->conn->base_.address), \
  1944. chan->conn->base_.port, (s)); \
  1945. connection_or_close_for_error(chan->conn, 0); \
  1946. goto done; \
  1947. } while (0)
  1948. if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
  1949. ERR("We're not currently doing a v3 handshake");
  1950. if (chan->conn->link_proto < 3)
  1951. ERR("We're not using link protocol >= 3");
  1952. if (!(chan->conn->handshake_state->started_here))
  1953. ERR("We didn't originate this connection");
  1954. if (chan->conn->handshake_state->received_auth_challenge)
  1955. ERR("We already received one");
  1956. if (!(chan->conn->handshake_state->received_certs_cell))
  1957. ERR("We haven't gotten a CERTS cell yet");
  1958. if (cell->circ_id)
  1959. ERR("It had a nonzero circuit ID");
  1960. if (auth_challenge_cell_parse(&ac, cell->payload, cell->payload_len) < 0)
  1961. ERR("It was not well-formed.");
  1962. n_types = ac->n_methods;
  1963. /* Now see if there is an authentication type we can use */
  1964. for (i = 0; i < n_types; ++i) {
  1965. uint16_t authtype = auth_challenge_cell_get_methods(ac, i);
  1966. if (authchallenge_type_is_supported(authtype)) {
  1967. if (use_type == -1 ||
  1968. authchallenge_type_is_better(authtype, use_type)) {
  1969. use_type = authtype;
  1970. }
  1971. }
  1972. }
  1973. chan->conn->handshake_state->received_auth_challenge = 1;
  1974. if (! public_server_mode(get_options())) {
  1975. /* If we're not a public server then we don't want to authenticate on a
  1976. connection we originated, and we already sent a NETINFO cell when we
  1977. got the CERTS cell. We have nothing more to do. */
  1978. goto done;
  1979. }
  1980. if (use_type >= 0) {
  1981. log_info(LD_OR,
  1982. "Got an AUTH_CHALLENGE cell from %s:%d: Sending "
  1983. "authentication type %d",
  1984. safe_str(chan->conn->base_.address),
  1985. chan->conn->base_.port,
  1986. use_type);
  1987. if (connection_or_send_authenticate_cell(chan->conn, use_type) < 0) {
  1988. log_warn(LD_OR,
  1989. "Couldn't send authenticate cell");
  1990. connection_or_close_for_error(chan->conn, 0);
  1991. goto done;
  1992. }
  1993. } else {
  1994. log_info(LD_OR,
  1995. "Got an AUTH_CHALLENGE cell from %s:%d, but we don't "
  1996. "know any of its authentication types. Not authenticating.",
  1997. safe_str(chan->conn->base_.address),
  1998. chan->conn->base_.port);
  1999. }
  2000. if (connection_or_send_netinfo(chan->conn) < 0) {
  2001. log_warn(LD_OR, "Couldn't send netinfo cell");
  2002. connection_or_close_for_error(chan->conn, 0);
  2003. goto done;
  2004. }
  2005. done:
  2006. auth_challenge_cell_free(ac);
  2007. #undef ERR
  2008. }
  2009. /**
  2010. * Process an AUTHENTICATE cell from a channel_tls_t.
  2011. *
  2012. * If it's ill-formed or we weren't supposed to get one or we're not doing a
  2013. * v3 handshake, then mark the connection. If it does not authenticate the
  2014. * other side of the connection successfully (because it isn't signed right,
  2015. * we didn't get a CERTS cell, etc) mark the connection. Otherwise, accept
  2016. * the identity of the router on the other side of the connection.
  2017. */
  2018. STATIC void
  2019. channel_tls_process_authenticate_cell(var_cell_t *cell, channel_tls_t *chan)
  2020. {
  2021. var_cell_t *expected_cell = NULL;
  2022. const uint8_t *auth;
  2023. int authlen;
  2024. int authtype;
  2025. int bodylen;
  2026. tor_assert(cell);
  2027. tor_assert(chan);
  2028. tor_assert(chan->conn);
  2029. #define ERR(s) \
  2030. do { \
  2031. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
  2032. "Received a bad AUTHENTICATE cell from %s:%d: %s", \
  2033. safe_str(chan->conn->base_.address), \
  2034. chan->conn->base_.port, (s)); \
  2035. connection_or_close_for_error(chan->conn, 0); \
  2036. var_cell_free(expected_cell); \
  2037. return; \
  2038. } while (0)
  2039. if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
  2040. ERR("We're not doing a v3 handshake");
  2041. if (chan->conn->link_proto < 3)
  2042. ERR("We're not using link protocol >= 3");
  2043. if (chan->conn->handshake_state->started_here)
  2044. ERR("We originated this connection");
  2045. if (chan->conn->handshake_state->received_authenticate)
  2046. ERR("We already got one!");
  2047. if (chan->conn->handshake_state->authenticated) {
  2048. /* Should be impossible given other checks */
  2049. ERR("The peer is already authenticated");
  2050. }
  2051. if (!(chan->conn->handshake_state->received_certs_cell))
  2052. ERR("We never got a certs cell");
  2053. if (chan->conn->handshake_state->certs->id_cert == NULL)
  2054. ERR("We never got an identity certificate");
  2055. if (cell->payload_len < 4)
  2056. ERR("Cell was way too short");
  2057. auth = cell->payload;
  2058. {
  2059. uint16_t type = ntohs(get_uint16(auth));
  2060. uint16_t len = ntohs(get_uint16(auth+2));
  2061. if (4 + len > cell->payload_len)
  2062. ERR("Authenticator was truncated");
  2063. if (! authchallenge_type_is_supported(type))
  2064. ERR("Authenticator type was not recognized");
  2065. authtype = type;
  2066. auth += 4;
  2067. authlen = len;
  2068. }
  2069. if (authlen < V3_AUTH_BODY_LEN + 1)
  2070. ERR("Authenticator was too short");
  2071. expected_cell = connection_or_compute_authenticate_cell_body(
  2072. chan->conn, authtype, NULL, NULL, 1);
  2073. if (! expected_cell)
  2074. ERR("Couldn't compute expected AUTHENTICATE cell body");
  2075. int sig_is_rsa;
  2076. if (authtype == AUTHTYPE_RSA_SHA256_TLSSECRET ||
  2077. authtype == AUTHTYPE_RSA_SHA256_RFC5705) {
  2078. bodylen = V3_AUTH_BODY_LEN;
  2079. sig_is_rsa = 1;
  2080. } else {
  2081. tor_assert(authtype == AUTHTYPE_ED25519_SHA256_RFC5705);
  2082. /* Our earlier check had better have made sure we had room
  2083. * for an ed25519 sig (inadvertently) */
  2084. tor_assert(V3_AUTH_BODY_LEN > ED25519_SIG_LEN);
  2085. bodylen = authlen - ED25519_SIG_LEN;
  2086. sig_is_rsa = 0;
  2087. }
  2088. if (expected_cell->payload_len != bodylen+4) {
  2089. ERR("Expected AUTHENTICATE cell body len not as expected.");
  2090. }
  2091. /* Length of random part. */
  2092. if (BUG(bodylen < 24)) {
  2093. // LCOV_EXCL_START
  2094. ERR("Bodylen is somehow less than 24, which should really be impossible");
  2095. // LCOV_EXCL_STOP
  2096. }
  2097. if (tor_memneq(expected_cell->payload+4, auth, bodylen-24))
  2098. ERR("Some field in the AUTHENTICATE cell body was not as expected");
  2099. if (sig_is_rsa) {
  2100. if (chan->conn->handshake_state->certs->ed_id_sign != NULL)
  2101. ERR("RSA-signed AUTHENTICATE response provided with an ED25519 cert");
  2102. if (chan->conn->handshake_state->certs->auth_cert == NULL)
  2103. ERR("We never got an RSA authentication certificate");
  2104. crypto_pk_t *pk = tor_tls_cert_get_key(
  2105. chan->conn->handshake_state->certs->auth_cert);
  2106. char d[DIGEST256_LEN];
  2107. char *signed_data;
  2108. size_t keysize;
  2109. int signed_len;
  2110. if (! pk) {
  2111. ERR("Couldn't get RSA key from AUTH cert.");
  2112. }
  2113. crypto_digest256(d, (char*)auth, V3_AUTH_BODY_LEN, DIGEST_SHA256);
  2114. keysize = crypto_pk_keysize(pk);
  2115. signed_data = tor_malloc(keysize);
  2116. signed_len = crypto_pk_public_checksig(pk, signed_data, keysize,
  2117. (char*)auth + V3_AUTH_BODY_LEN,
  2118. authlen - V3_AUTH_BODY_LEN);
  2119. crypto_pk_free(pk);
  2120. if (signed_len < 0) {
  2121. tor_free(signed_data);
  2122. ERR("RSA signature wasn't valid");
  2123. }
  2124. if (signed_len < DIGEST256_LEN) {
  2125. tor_free(signed_data);
  2126. ERR("Not enough data was signed");
  2127. }
  2128. /* Note that we deliberately allow *more* than DIGEST256_LEN bytes here,
  2129. * in case they're later used to hold a SHA3 digest or something. */
  2130. if (tor_memneq(signed_data, d, DIGEST256_LEN)) {
  2131. tor_free(signed_data);
  2132. ERR("Signature did not match data to be signed.");
  2133. }
  2134. tor_free(signed_data);
  2135. } else {
  2136. if (chan->conn->handshake_state->certs->ed_id_sign == NULL)
  2137. ERR("We never got an Ed25519 identity certificate.");
  2138. if (chan->conn->handshake_state->certs->ed_sign_auth == NULL)
  2139. ERR("We never got an Ed25519 authentication certificate.");
  2140. const ed25519_public_key_t *authkey =
  2141. &chan->conn->handshake_state->certs->ed_sign_auth->signed_key;
  2142. ed25519_signature_t sig;
  2143. tor_assert(authlen > ED25519_SIG_LEN);
  2144. memcpy(&sig.sig, auth + authlen - ED25519_SIG_LEN, ED25519_SIG_LEN);
  2145. if (ed25519_checksig(&sig, auth, authlen - ED25519_SIG_LEN, authkey)<0) {
  2146. ERR("Ed25519 signature wasn't valid.");
  2147. }
  2148. }
  2149. /* Okay, we are authenticated. */
  2150. chan->conn->handshake_state->received_authenticate = 1;
  2151. chan->conn->handshake_state->authenticated = 1;
  2152. chan->conn->handshake_state->authenticated_rsa = 1;
  2153. chan->conn->handshake_state->digest_received_data = 0;
  2154. {
  2155. tor_x509_cert_t *id_cert = chan->conn->handshake_state->certs->id_cert;
  2156. crypto_pk_t *identity_rcvd = tor_tls_cert_get_key(id_cert);
  2157. const common_digests_t *id_digests = tor_x509_cert_get_id_digests(id_cert);
  2158. const ed25519_public_key_t *ed_identity_received = NULL;
  2159. if (! sig_is_rsa) {
  2160. chan->conn->handshake_state->authenticated_ed25519 = 1;
  2161. ed_identity_received =
  2162. &chan->conn->handshake_state->certs->ed_id_sign->signing_key;
  2163. memcpy(&chan->conn->handshake_state->authenticated_ed25519_peer_id,
  2164. ed_identity_received, sizeof(ed25519_public_key_t));
  2165. }
  2166. /* This must exist; we checked key type when reading the cert. */
  2167. tor_assert(id_digests);
  2168. memcpy(chan->conn->handshake_state->authenticated_rsa_peer_id,
  2169. id_digests->d[DIGEST_SHA1], DIGEST_LEN);
  2170. channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
  2171. chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
  2172. crypto_pk_free(identity_rcvd);
  2173. log_debug(LD_HANDSHAKE,
  2174. "Calling connection_or_init_conn_from_address for %s "
  2175. " from %s, with%s ed25519 id.",
  2176. safe_str(chan->conn->base_.address),
  2177. __func__,
  2178. ed_identity_received ? "" : "out");
  2179. connection_or_init_conn_from_address(chan->conn,
  2180. &(chan->conn->base_.addr),
  2181. chan->conn->base_.port,
  2182. (const char*)(chan->conn->handshake_state->
  2183. authenticated_rsa_peer_id),
  2184. ed_identity_received,
  2185. 0);
  2186. log_debug(LD_HANDSHAKE,
  2187. "Got an AUTHENTICATE cell from %s:%d, type %d: Looks good.",
  2188. safe_str(chan->conn->base_.address),
  2189. chan->conn->base_.port,
  2190. authtype);
  2191. }
  2192. var_cell_free(expected_cell);
  2193. #undef ERR
  2194. }