channeltls.c 77 KB

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