channeltls.c 84 KB

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