channeltls.c 65 KB

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