channeltls.c 66 KB

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