channeltls.c 67 KB

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