channeltls.c 70 KB

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