channeltls.c 67 KB

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