channeltls.c 64 KB

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