channeltls.c 80 KB

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