channeltls.c 80 KB

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