channeltls.c 69 KB

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