channeltls.c 80 KB

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