channeltls.c 67 KB

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