channeltls.c 66 KB

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