channeltls.c 80 KB

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