channeltls.c 80 KB

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