channeltls.c 82 KB

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