channeltls.c 72 KB

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