channeltls.c 60 KB

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