channeltls.c 68 KB

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