channeltls.c 67 KB

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