channeltls.c 63 KB

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