channeltls.c 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558
  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. return 0;
  547. }
  548. // TODO: fix this ugly locking
  549. connection_t *conn = TO_CONN(tlschan->conn);
  550. tor_assert(conn->safe_conn != NULL);
  551. tor_mutex_acquire(&(conn->safe_conn->lock));
  552. outbuf_len = buf_datalen(conn->safe_conn->outbuf);
  553. tor_mutex_release(&(conn->safe_conn->lock));
  554. //outbuf_len = (tlschan->conn != NULL) ?
  555. // connection_get_outbuf_len(TO_CONN(tlschan->conn)) :
  556. // 0;
  557. return (outbuf_len > 0);
  558. }
  559. /**
  560. * Tell the upper layer if we're canonical.
  561. *
  562. * This implements the is_canonical method for channel_tls_t; if req is zero,
  563. * it returns whether this is a canonical channel, and if it is one it returns
  564. * whether that can be relied upon.
  565. */
  566. static int
  567. channel_tls_is_canonical_method(channel_t *chan, int req)
  568. {
  569. int answer = 0;
  570. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  571. tor_assert(tlschan);
  572. if (tlschan->conn) {
  573. switch (req) {
  574. case 0:
  575. answer = tlschan->conn->is_canonical;
  576. break;
  577. case 1:
  578. /*
  579. * Is the is_canonical bit reliable? In protocols version 2 and up
  580. * we get the canonical address from a NETINFO cell, but in older
  581. * versions it might be based on an obsolete descriptor.
  582. */
  583. answer = (tlschan->conn->link_proto >= 2);
  584. break;
  585. default:
  586. /* This shouldn't happen; channel.c is broken if it does */
  587. tor_assert_nonfatal_unreached_once();
  588. }
  589. }
  590. /* else return 0 for tlschan->conn == NULL */
  591. return answer;
  592. }
  593. /**
  594. * Check if we match an extend_info_t.
  595. *
  596. * This implements the matches_extend_info method for channel_tls_t; the upper
  597. * layer wants to know if this channel matches an extend_info_t.
  598. */
  599. static int
  600. channel_tls_matches_extend_info_method(channel_t *chan,
  601. extend_info_t *extend_info)
  602. {
  603. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  604. tor_assert(tlschan);
  605. tor_assert(extend_info);
  606. /* Never match if we have no conn */
  607. if (!(tlschan->conn)) {
  608. log_info(LD_CHANNEL,
  609. "something called matches_extend_info on a tlschan "
  610. "(%p with ID %"PRIu64 " but no conn",
  611. chan, (chan->global_identifier));
  612. return 0;
  613. }
  614. return (tor_addr_eq(&(extend_info->addr),
  615. &(TO_CONN(tlschan->conn)->addr)) &&
  616. (extend_info->port == TO_CONN(tlschan->conn)->port));
  617. }
  618. /**
  619. * Check if we match a target address; return true iff we do.
  620. *
  621. * This implements the matches_target method for channel_tls t_; the upper
  622. * layer wants to know if this channel matches a target address when extending
  623. * a circuit.
  624. */
  625. static int
  626. channel_tls_matches_target_method(channel_t *chan,
  627. const tor_addr_t *target)
  628. {
  629. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  630. tor_assert(tlschan);
  631. tor_assert(target);
  632. /* Never match if we have no conn */
  633. if (!(tlschan->conn)) {
  634. log_info(LD_CHANNEL,
  635. "something called matches_target on a tlschan "
  636. "(%p with ID %"PRIu64 " but no conn",
  637. chan, (chan->global_identifier));
  638. return 0;
  639. }
  640. /* real_addr is the address this connection came from.
  641. * base_.addr is updated by connection_or_init_conn_from_address()
  642. * to be the address in the descriptor. It may be tempting to
  643. * allow either address to be allowed, but if we did so, it would
  644. * enable someone who steals a relay's keys to impersonate/MITM it
  645. * from anywhere on the Internet! (Because they could make long-lived
  646. * TLS connections from anywhere to all relays, and wait for them to
  647. * be used for extends).
  648. */
  649. return tor_addr_eq(&(tlschan->conn->real_addr), target);
  650. }
  651. /**
  652. * Tell the upper layer how many bytes we have queued and not yet
  653. * sent.
  654. */
  655. static size_t
  656. channel_tls_num_bytes_queued_method(channel_t *chan)
  657. {
  658. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  659. tor_assert(tlschan);
  660. tor_assert(tlschan->conn);
  661. return connection_get_outbuf_len(TO_CONN(tlschan->conn));
  662. }
  663. /**
  664. * Tell the upper layer how many cells we can accept to write.
  665. *
  666. * This implements the num_cells_writeable method for channel_tls_t; it
  667. * returns an estimate of the number of cells we can accept with
  668. * channel_tls_write_*_cell().
  669. */
  670. static int
  671. channel_tls_num_cells_writeable_method(channel_t *chan)
  672. {
  673. size_t outbuf_len;
  674. ssize_t n;
  675. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  676. size_t cell_network_size;
  677. tor_assert(tlschan);
  678. tor_assert(tlschan->conn);
  679. cell_network_size = get_cell_network_size(tlschan->conn->wide_circ_ids);
  680. outbuf_len = connection_get_outbuf_len(TO_CONN(tlschan->conn));
  681. /* Get the number of cells */
  682. n = CEIL_DIV(OR_CONN_HIGHWATER - outbuf_len, cell_network_size);
  683. if (n < 0) n = 0;
  684. #if SIZEOF_SIZE_T > SIZEOF_INT
  685. if (n > INT_MAX) n = INT_MAX;
  686. #endif
  687. return (int)n;
  688. }
  689. /**
  690. * Write a cell to a channel_tls_t.
  691. *
  692. * This implements the write_cell method for channel_tls_t; given a
  693. * channel_tls_t and a cell_t, transmit the cell_t.
  694. */
  695. static int
  696. channel_tls_write_cell_method(channel_t *chan, cell_t *cell)
  697. {
  698. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  699. int written = 0;
  700. tor_assert(tlschan);
  701. tor_assert(cell);
  702. if (tlschan->conn) {
  703. connection_or_write_cell_to_buf(cell, tlschan->conn);
  704. ++written;
  705. } else {
  706. log_info(LD_CHANNEL,
  707. "something called write_cell on a tlschan "
  708. "(%p with ID %"PRIu64 " but no conn",
  709. chan, (chan->global_identifier));
  710. }
  711. return written;
  712. }
  713. static void
  714. void_packed_cell_free(void *void_packed_cell)
  715. {
  716. packed_cell_free_((packed_cell_t *)void_packed_cell);
  717. }
  718. /**
  719. * Write a packed cell to a channel_tls_t.
  720. *
  721. * This implements the write_packed_cell method for channel_tls_t; given a
  722. * channel_tls_t and a packed_cell_t, transmit the packed_cell_t.
  723. *
  724. * Return 0 on success or negative value on error. The caller must not free
  725. * the packed cell.
  726. */
  727. static int
  728. channel_tls_write_packed_cell_method(channel_t *chan,
  729. packed_cell_t *packed_cell)
  730. {
  731. tor_assert(chan);
  732. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  733. //size_t cell_network_size = get_cell_network_size(chan->wide_circ_ids);
  734. tor_assert(tlschan);
  735. tor_assert(packed_cell);
  736. if (tlschan->conn) {
  737. //connection_buf_add(packed_cell->body, cell_network_size,
  738. // TO_CONN(tlschan->conn));
  739. if (connection_may_write_to_buf(TO_CONN(tlschan->conn))) {
  740. event_data_t event_data = { .ptr = packed_cell };
  741. packed_cell = NULL;
  742. event_source_publish(TO_CONN(tlschan->conn)->event_source,
  743. or_conn_outgoing_packed_cell, event_data,
  744. void_packed_cell_free);
  745. } else {
  746. packed_cell_free(packed_cell);
  747. }
  748. } else {
  749. log_info(LD_CHANNEL,
  750. "something called write_packed_cell on a tlschan "
  751. "(%p with ID %"PRIu64 " but no conn",
  752. chan, (chan->global_identifier));
  753. return -1;
  754. }
  755. return 0;
  756. }
  757. /**
  758. * Write a variable-length cell to a channel_tls_t.
  759. *
  760. * This implements the write_var_cell method for channel_tls_t; given a
  761. * channel_tls_t and a var_cell_t, transmit the var_cell_t.
  762. */
  763. static int
  764. channel_tls_write_var_cell_method(channel_t *chan, var_cell_t *var_cell)
  765. {
  766. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  767. int written = 0;
  768. tor_assert(tlschan);
  769. tor_assert(var_cell);
  770. if (tlschan->conn) {
  771. connection_or_write_var_cell_to_buf(var_cell, tlschan->conn);
  772. ++written;
  773. } else {
  774. log_info(LD_CHANNEL,
  775. "something called write_var_cell on a tlschan "
  776. "(%p with ID %"PRIu64 " but no conn",
  777. chan, (chan->global_identifier));
  778. }
  779. return written;
  780. }
  781. /*************************************************
  782. * Method implementations for channel_listener_t *
  783. ************************************************/
  784. /**
  785. * Close a channel_listener_t.
  786. *
  787. * This implements the close method for channel_listener_t.
  788. */
  789. static void
  790. channel_tls_listener_close_method(channel_listener_t *chan_l)
  791. {
  792. tor_assert(chan_l);
  793. /*
  794. * Listeners we just go ahead and change state through to CLOSED, but
  795. * make sure to check if they're channel_tls_listener to NULL it out.
  796. */
  797. if (chan_l == channel_tls_listener)
  798. channel_tls_listener = NULL;
  799. if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
  800. chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  801. chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
  802. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
  803. }
  804. if (chan_l->incoming_list) {
  805. SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
  806. channel_t *, ichan) {
  807. channel_mark_for_close(ichan);
  808. } SMARTLIST_FOREACH_END(ichan);
  809. smartlist_free(chan_l->incoming_list);
  810. chan_l->incoming_list = NULL;
  811. }
  812. if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  813. chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
  814. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSED);
  815. }
  816. }
  817. /**
  818. * Describe the transport for a channel_listener_t.
  819. *
  820. * This returns the string "TLS channel (listening)" to the upper
  821. * layer.
  822. */
  823. static const char *
  824. channel_tls_listener_describe_transport_method(channel_listener_t *chan_l)
  825. {
  826. tor_assert(chan_l);
  827. return "TLS channel (listening)";
  828. }
  829. /*******************************************************
  830. * Functions for handling events on an or_connection_t *
  831. ******************************************************/
  832. /**
  833. * Handle an orconn state change.
  834. *
  835. * This function will be called by connection_or.c when the or_connection_t
  836. * associated with this channel_tls_t changes state.
  837. */
  838. void
  839. channel_tls_handle_state_change_on_orconn(channel_tls_t *chan,
  840. or_connection_t *conn,
  841. uint8_t state)
  842. {
  843. channel_t *base_chan;
  844. tor_assert(chan);
  845. tor_assert(conn);
  846. tor_assert(conn->chan == chan);
  847. tor_assert(chan->conn == conn);
  848. base_chan = TLS_CHAN_TO_BASE(chan);
  849. /* Make sure the base connection state makes sense - shouldn't be error
  850. * or closed. */
  851. tor_assert(CHANNEL_IS_OPENING(base_chan) ||
  852. CHANNEL_IS_OPEN(base_chan) ||
  853. CHANNEL_IS_MAINT(base_chan) ||
  854. CHANNEL_IS_CLOSING(base_chan));
  855. /* Did we just go to state open? */
  856. if (state == OR_CONN_STATE_OPEN) {
  857. /*
  858. * We can go to CHANNEL_STATE_OPEN from CHANNEL_STATE_OPENING or
  859. * CHANNEL_STATE_MAINT on this.
  860. */
  861. channel_change_state_open(base_chan);
  862. /* We might have just become writeable; check and tell the scheduler */
  863. if (connection_or_num_cells_writeable(conn) > 0) {
  864. scheduler_channel_wants_writes(base_chan);
  865. }
  866. } else {
  867. /*
  868. * Not open, so from CHANNEL_STATE_OPEN we go to CHANNEL_STATE_MAINT,
  869. * otherwise no change.
  870. */
  871. if (CHANNEL_IS_OPEN(base_chan)) {
  872. channel_change_state(base_chan, CHANNEL_STATE_MAINT);
  873. }
  874. }
  875. }
  876. #ifdef KEEP_TIMING_STATS
  877. /**
  878. * Timing states wrapper.
  879. *
  880. * This is a wrapper function around the actual function that processes the
  881. * <b>cell</b> that just arrived on <b>chan</b>. Increment <b>*time</b>
  882. * by the number of microseconds used by the call to <b>*func(cell, chan)</b>.
  883. */
  884. static void
  885. channel_tls_time_process_cell(cell_t *cell, channel_tls_t *chan, int *time,
  886. void (*func)(cell_t *, channel_tls_t *))
  887. {
  888. struct timeval start, end;
  889. long time_passed;
  890. tor_gettimeofday(&start);
  891. (*func)(cell, chan);
  892. tor_gettimeofday(&end);
  893. time_passed = tv_udiff(&start, &end) ;
  894. if (time_passed > 10000) { /* more than 10ms */
  895. log_debug(LD_OR,"That call just took %ld ms.",time_passed/1000);
  896. }
  897. if (time_passed < 0) {
  898. log_info(LD_GENERAL,"That call took us back in time!");
  899. time_passed = 0;
  900. }
  901. *time += time_passed;
  902. }
  903. #endif /* defined(KEEP_TIMING_STATS) */
  904. #ifdef KEEP_TIMING_STATS
  905. #define PROCESS_CELL(tp, cl, cn) STMT_BEGIN { \
  906. ++num ## tp; \
  907. channel_tls_time_process_cell(cl, cn, & tp ## time , \
  908. channel_tls_process_ ## tp ## _cell); \
  909. } STMT_END
  910. #else /* !defined(KEEP_TIMING_STATS) */
  911. #define PROCESS_CELL(tp, cl, cn) channel_tls_process_ ## tp ## _cell(cl, cn)
  912. #endif /* defined(KEEP_TIMING_STATS) */
  913. /**
  914. * Handle an incoming cell on a channel_tls_t.
  915. *
  916. * This is called from connection_or.c to handle an arriving cell; it checks
  917. * for cell types specific to the handshake for this transport protocol and
  918. * handles them, and queues all other cells to the channel_t layer, which
  919. * eventually will hand them off to command.c.
  920. *
  921. * The channel layer itself decides whether the cell should be queued or
  922. * can be handed off immediately to the upper-layer code. It is responsible
  923. * for copying in the case that it queues; we merely pass pointers through
  924. * which we get from connection_or_process_cells_from_inbuf().
  925. */
  926. void
  927. channel_tls_handle_cell(cell_t *cell, or_connection_t *conn)
  928. {
  929. channel_tls_t *chan;
  930. int handshaking;
  931. tor_assert(cell);
  932. tor_assert(conn);
  933. chan = conn->chan;
  934. if (!chan) {
  935. log_warn(LD_CHANNEL,
  936. "Got a cell_t on an OR connection with no channel");
  937. return;
  938. }
  939. handshaking = (TO_CONN(conn)->state != OR_CONN_STATE_OPEN);
  940. if (conn->base_.marked_for_close)
  941. return;
  942. /* Reject all but VERSIONS and NETINFO when handshaking. */
  943. /* (VERSIONS actually indicates a protocol warning: it's variable-length,
  944. * so if it reaches this function, we're on a v1 connection.) */
  945. if (handshaking && cell->command != CELL_VERSIONS &&
  946. cell->command != CELL_NETINFO) {
  947. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  948. "Received unexpected cell command %d in chan state %s / "
  949. "conn state %s; closing the connection.",
  950. (int)cell->command,
  951. channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
  952. conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state));
  953. connection_or_close_for_error(conn, 0);
  954. return;
  955. }
  956. if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
  957. or_handshake_state_record_cell(conn, conn->handshake_state, cell, 1);
  958. /* We note that we're on the internet whenever we read a cell. This is
  959. * a fast operation. */
  960. entry_guards_note_internet_connectivity(get_guard_selection_info());
  961. rep_hist_padding_count_read(PADDING_TYPE_TOTAL);
  962. if (TLS_CHAN_TO_BASE(chan)->padding_enabled)
  963. rep_hist_padding_count_read(PADDING_TYPE_ENABLED_TOTAL);
  964. switch (cell->command) {
  965. case CELL_PADDING:
  966. rep_hist_padding_count_read(PADDING_TYPE_CELL);
  967. if (TLS_CHAN_TO_BASE(chan)->padding_enabled)
  968. rep_hist_padding_count_read(PADDING_TYPE_ENABLED_CELL);
  969. ++stats_n_padding_cells_processed;
  970. /* do nothing */
  971. break;
  972. case CELL_VERSIONS:
  973. /* A VERSIONS cell should always be a variable-length cell, and
  974. * so should never reach this function (which handles constant-sized
  975. * cells). But if the connection is using the (obsolete) v1 link
  976. * protocol, all cells will be treated as constant-sized, and so
  977. * it's possible we'll reach this code.
  978. */
  979. log_fn(LOG_PROTOCOL_WARN, LD_CHANNEL,
  980. "Received unexpected VERSIONS cell on a channel using link "
  981. "protocol %d; ignoring.", conn->link_proto);
  982. break;
  983. case CELL_NETINFO:
  984. ++stats_n_netinfo_cells_processed;
  985. PROCESS_CELL(netinfo, cell, chan);
  986. break;
  987. case CELL_PADDING_NEGOTIATE:
  988. ++stats_n_netinfo_cells_processed;
  989. PROCESS_CELL(padding_negotiate, cell, chan);
  990. break;
  991. case CELL_CREATE:
  992. case CELL_CREATE_FAST:
  993. case CELL_CREATED:
  994. case CELL_CREATED_FAST:
  995. case CELL_RELAY:
  996. case CELL_RELAY_EARLY:
  997. case CELL_DESTROY:
  998. case CELL_CREATE2:
  999. case CELL_CREATED2:
  1000. /*
  1001. * These are all transport independent and we pass them up through the
  1002. * channel_t mechanism. They are ultimately handled in command.c.
  1003. */
  1004. channel_process_cell(TLS_CHAN_TO_BASE(chan), cell);
  1005. break;
  1006. default:
  1007. log_fn(LOG_INFO, LD_PROTOCOL,
  1008. "Cell of unknown type (%d) received in channeltls.c. "
  1009. "Dropping.",
  1010. cell->command);
  1011. break;
  1012. }
  1013. }
  1014. /**
  1015. * Handle an incoming variable-length cell on a channel_tls_t.
  1016. *
  1017. * Process a <b>var_cell</b> that was just received on <b>conn</b>. Keep
  1018. * internal statistics about how many of each cell we've processed so far
  1019. * this second, and the total number of microseconds it took to
  1020. * process each type of cell. All the var_cell commands are handshake-
  1021. * related and live below the channel_t layer, so no variable-length
  1022. * cells ever get delivered in the current implementation, but I've left
  1023. * the mechanism in place for future use.
  1024. *
  1025. * If we were handing them off to the upper layer, the channel_t queueing
  1026. * code would be responsible for memory management, and we'd just be passing
  1027. * pointers through from connection_or_process_cells_from_inbuf(). That
  1028. * caller always frees them after this function returns, so this function
  1029. * should never free var_cell.
  1030. */
  1031. void
  1032. channel_tls_handle_var_cell(var_cell_t *var_cell, or_connection_t *conn)
  1033. {
  1034. channel_tls_t *chan;
  1035. #ifdef KEEP_TIMING_STATS
  1036. /* how many of each cell have we seen so far this second? needs better
  1037. * name. */
  1038. static int num_versions = 0, num_certs = 0;
  1039. static time_t current_second = 0; /* from previous calls to time */
  1040. time_t now = time(NULL);
  1041. if (current_second == 0) current_second = now;
  1042. if (now > current_second) { /* the second has rolled over */
  1043. /* print stats */
  1044. log_info(LD_OR,
  1045. "At end of second: %d versions (%d ms), %d certs (%d ms)",
  1046. num_versions, versions_time / ((now - current_second) * 1000),
  1047. num_certs, certs_time / ((now - current_second) * 1000));
  1048. num_versions = num_certs = 0;
  1049. versions_time = certs_time = 0;
  1050. /* remember which second it is, for next time */
  1051. current_second = now;
  1052. }
  1053. #endif /* defined(KEEP_TIMING_STATS) */
  1054. tor_assert(var_cell);
  1055. tor_assert(conn);
  1056. chan = conn->chan;
  1057. if (!chan) {
  1058. log_warn(LD_CHANNEL,
  1059. "Got a var_cell_t on an OR connection with no channel");
  1060. return;
  1061. }
  1062. if (TO_CONN(conn)->marked_for_close)
  1063. return;
  1064. switch (TO_CONN(conn)->state) {
  1065. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  1066. if (var_cell->command != CELL_VERSIONS) {
  1067. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1068. "Received a cell with command %d in unexpected "
  1069. "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
  1070. "closing the connection.",
  1071. (int)(var_cell->command),
  1072. conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
  1073. TO_CONN(conn)->state,
  1074. channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
  1075. (int)(TLS_CHAN_TO_BASE(chan)->state));
  1076. /*
  1077. * The code in connection_or.c will tell channel_t to close for
  1078. * error; it will go to CHANNEL_STATE_CLOSING, and then to
  1079. * CHANNEL_STATE_ERROR when conn is closed.
  1080. */
  1081. connection_or_close_for_error(conn, 0);
  1082. return;
  1083. }
  1084. break;
  1085. case OR_CONN_STATE_TLS_HANDSHAKING:
  1086. /* If we're using bufferevents, it's entirely possible for us to
  1087. * notice "hey, data arrived!" before we notice "hey, the handshake
  1088. * finished!" And we need to be accepting both at once to handle both
  1089. * the v2 and v3 handshakes. */
  1090. /* But that should be happening any longer've disabled bufferevents. */
  1091. tor_assert_nonfatal_unreached_once();
  1092. /* fall through */
  1093. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  1094. if (!(command_allowed_before_handshake(var_cell->command))) {
  1095. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1096. "Received a cell with command %d in unexpected "
  1097. "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
  1098. "closing the connection.",
  1099. (int)(var_cell->command),
  1100. conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
  1101. (int)(TO_CONN(conn)->state),
  1102. channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
  1103. (int)(TLS_CHAN_TO_BASE(chan)->state));
  1104. /* see above comment about CHANNEL_STATE_ERROR */
  1105. connection_or_close_for_error(conn, 0);
  1106. return;
  1107. } else {
  1108. if (enter_v3_handshake_with_cell(var_cell, chan) < 0)
  1109. return;
  1110. }
  1111. break;
  1112. case OR_CONN_STATE_OR_HANDSHAKING_V3:
  1113. if (var_cell->command != CELL_AUTHENTICATE)
  1114. or_handshake_state_record_var_cell(conn, conn->handshake_state,
  1115. var_cell, 1);
  1116. break; /* Everything is allowed */
  1117. case OR_CONN_STATE_OPEN:
  1118. if (conn->link_proto < 3) {
  1119. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1120. "Received a variable-length cell with command %d in orconn "
  1121. "state %s [%d], channel state %s [%d] with link protocol %d; "
  1122. "ignoring it.",
  1123. (int)(var_cell->command),
  1124. conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
  1125. (int)(TO_CONN(conn)->state),
  1126. channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
  1127. (int)(TLS_CHAN_TO_BASE(chan)->state),
  1128. (int)(conn->link_proto));
  1129. return;
  1130. }
  1131. break;
  1132. default:
  1133. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1134. "Received var-length cell with command %d in unexpected "
  1135. "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
  1136. "ignoring it.",
  1137. (int)(var_cell->command),
  1138. conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
  1139. (int)(TO_CONN(conn)->state),
  1140. channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
  1141. (int)(TLS_CHAN_TO_BASE(chan)->state));
  1142. return;
  1143. }
  1144. /* We note that we're on the internet whenever we read a cell. This is
  1145. * a fast operation. */
  1146. entry_guards_note_internet_connectivity(get_guard_selection_info());
  1147. /* Now handle the cell */
  1148. switch (var_cell->command) {
  1149. case CELL_VERSIONS:
  1150. ++stats_n_versions_cells_processed;
  1151. PROCESS_CELL(versions, var_cell, chan);
  1152. break;
  1153. case CELL_VPADDING:
  1154. ++stats_n_vpadding_cells_processed;
  1155. /* Do nothing */
  1156. break;
  1157. case CELL_CERTS:
  1158. ++stats_n_certs_cells_processed;
  1159. PROCESS_CELL(certs, var_cell, chan);
  1160. break;
  1161. case CELL_AUTH_CHALLENGE:
  1162. ++stats_n_auth_challenge_cells_processed;
  1163. PROCESS_CELL(auth_challenge, var_cell, chan);
  1164. break;
  1165. case CELL_AUTHENTICATE:
  1166. ++stats_n_authenticate_cells_processed;
  1167. PROCESS_CELL(authenticate, var_cell, chan);
  1168. break;
  1169. case CELL_AUTHORIZE:
  1170. ++stats_n_authorize_cells_processed;
  1171. /* Ignored so far. */
  1172. break;
  1173. default:
  1174. log_fn(LOG_INFO, LD_PROTOCOL,
  1175. "Variable-length cell of unknown type (%d) received.",
  1176. (int)(var_cell->command));
  1177. break;
  1178. }
  1179. }
  1180. #undef PROCESS_CELL
  1181. /**
  1182. * Update channel marks after connection_or.c has changed an address.
  1183. *
  1184. * This is called from connection_or_init_conn_from_address() after the
  1185. * connection's _base.addr or real_addr fields have potentially been changed
  1186. * so we can recalculate the local mark. Notably, this happens when incoming
  1187. * connections are reverse-proxied and we only learn the real address of the
  1188. * remote router by looking it up in the consensus after we finish the
  1189. * handshake and know an authenticated identity digest.
  1190. */
  1191. void
  1192. channel_tls_update_marks(or_connection_t *conn)
  1193. {
  1194. channel_t *chan = NULL;
  1195. tor_assert(conn);
  1196. tor_assert(conn->chan);
  1197. chan = TLS_CHAN_TO_BASE(conn->chan);
  1198. if (is_local_addr(&(TO_CONN(conn)->addr))) {
  1199. if (!channel_is_local(chan)) {
  1200. log_debug(LD_CHANNEL,
  1201. "Marking channel %"PRIu64 " at %p as local",
  1202. (chan->global_identifier), chan);
  1203. channel_mark_local(chan);
  1204. }
  1205. } else {
  1206. if (channel_is_local(chan)) {
  1207. log_debug(LD_CHANNEL,
  1208. "Marking channel %"PRIu64 " at %p as remote",
  1209. (chan->global_identifier), chan);
  1210. channel_mark_remote(chan);
  1211. }
  1212. }
  1213. }
  1214. /**
  1215. * Check if this cell type is allowed before the handshake is finished.
  1216. *
  1217. * Return true if <b>command</b> is a cell command that's allowed to start a
  1218. * V3 handshake.
  1219. */
  1220. static int
  1221. command_allowed_before_handshake(uint8_t command)
  1222. {
  1223. switch (command) {
  1224. case CELL_VERSIONS:
  1225. case CELL_VPADDING:
  1226. case CELL_AUTHORIZE:
  1227. return 1;
  1228. default:
  1229. return 0;
  1230. }
  1231. }
  1232. /**
  1233. * Start a V3 handshake on an incoming connection.
  1234. *
  1235. * Called when we as a server receive an appropriate cell while waiting
  1236. * either for a cell or a TLS handshake. Set the connection's state to
  1237. * "handshaking_v3', initializes the or_handshake_state field as needed,
  1238. * and add the cell to the hash of incoming cells.)
  1239. */
  1240. static int
  1241. enter_v3_handshake_with_cell(var_cell_t *cell, channel_tls_t *chan)
  1242. {
  1243. int started_here = 0;
  1244. tor_assert(cell);
  1245. tor_assert(chan);
  1246. tor_assert(chan->conn);
  1247. started_here = connection_or_nonopen_was_started_here(chan->conn);
  1248. tor_assert(TO_CONN(chan->conn)->state == OR_CONN_STATE_TLS_HANDSHAKING ||
  1249. TO_CONN(chan->conn)->state ==
  1250. OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
  1251. if (started_here) {
  1252. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1253. "Received a cell while TLS-handshaking, not in "
  1254. "OR_HANDSHAKING_V3, on a connection we originated.");
  1255. }
  1256. //connection_or_block_renegotiation(chan->conn);
  1257. chan->conn->base_.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
  1258. if (connection_init_or_handshake_state(chan->conn, started_here) < 0) {
  1259. connection_or_close_for_error(chan->conn, 0);
  1260. return -1;
  1261. }
  1262. or_handshake_state_record_var_cell(chan->conn,
  1263. chan->conn->handshake_state, cell, 1);
  1264. return 0;
  1265. }
  1266. /**
  1267. * Process a 'versions' cell.
  1268. *
  1269. * This function is called to handle an incoming VERSIONS cell; the current
  1270. * link protocol version must be 0 to indicate that no version has yet been
  1271. * negotiated. We compare the versions in the cell to the list of versions
  1272. * we support, pick the highest version we have in common, and continue the
  1273. * negotiation from there.
  1274. */
  1275. static void
  1276. channel_tls_process_versions_cell(var_cell_t *cell, channel_tls_t *chan)
  1277. {
  1278. int highest_supported_version = 0;
  1279. int started_here = 0;
  1280. tor_assert(cell);
  1281. tor_assert(chan);
  1282. tor_assert(chan->conn);
  1283. if ((cell->payload_len % 2) == 1) {
  1284. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1285. "Received a VERSION cell with odd payload length %d; "
  1286. "closing connection.",cell->payload_len);
  1287. connection_or_close_for_error(chan->conn, 0);
  1288. return;
  1289. }
  1290. started_here = connection_or_nonopen_was_started_here(chan->conn);
  1291. if (chan->conn->link_proto != 0 ||
  1292. (chan->conn->handshake_state &&
  1293. chan->conn->handshake_state->received_versions)) {
  1294. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1295. "Received a VERSIONS cell on a connection with its version "
  1296. "already set to %d; dropping",
  1297. (int)(chan->conn->link_proto));
  1298. return;
  1299. }
  1300. switch (chan->conn->base_.state)
  1301. {
  1302. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  1303. case OR_CONN_STATE_OR_HANDSHAKING_V3:
  1304. break;
  1305. case OR_CONN_STATE_TLS_HANDSHAKING:
  1306. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  1307. default:
  1308. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1309. "VERSIONS cell while in unexpected state");
  1310. return;
  1311. }
  1312. tor_assert(chan->conn->handshake_state);
  1313. {
  1314. int i;
  1315. const uint8_t *cp = cell->payload;
  1316. for (i = 0; i < cell->payload_len / 2; ++i, cp += 2) {
  1317. uint16_t v = ntohs(get_uint16(cp));
  1318. if (is_or_protocol_version_known(v) && v > highest_supported_version)
  1319. highest_supported_version = v;
  1320. }
  1321. }
  1322. if (!highest_supported_version) {
  1323. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1324. "Couldn't find a version in common between my version list and the "
  1325. "list in the VERSIONS cell; closing connection.");
  1326. connection_or_close_for_error(chan->conn, 0);
  1327. return;
  1328. } else if (highest_supported_version == 1) {
  1329. /* Negotiating version 1 makes no sense, since version 1 has no VERSIONS
  1330. * cells. */
  1331. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1332. "Used version negotiation protocol to negotiate a v1 connection. "
  1333. "That's crazily non-compliant. Closing connection.");
  1334. connection_or_close_for_error(chan->conn, 0);
  1335. return;
  1336. } else if (highest_supported_version < 3 &&
  1337. chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
  1338. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1339. "Negotiated link protocol 2 or lower after doing a v3 TLS "
  1340. "handshake. Closing connection.");
  1341. connection_or_close_for_error(chan->conn, 0);
  1342. return;
  1343. } else if (highest_supported_version != 2 &&
  1344. chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V2) {
  1345. /* XXXX This should eventually be a log_protocol_warn */
  1346. log_fn(LOG_WARN, LD_OR,
  1347. "Negotiated link with non-2 protocol after doing a v2 TLS "
  1348. "handshake with %s. Closing connection.",
  1349. fmt_addr(&chan->conn->base_.addr));
  1350. connection_or_close_for_error(chan->conn, 0);
  1351. return;
  1352. }
  1353. rep_hist_note_negotiated_link_proto(highest_supported_version, started_here);
  1354. uint16_t link_protocol = highest_supported_version;
  1355. if (link_protocol == 2) {
  1356. log_warn(LD_OR, "We don't support a link protocol of 2");
  1357. connection_or_close_for_error(chan->conn, 0);
  1358. return;
  1359. //log_info(LD_OR,
  1360. // "Negotiated version %d with %s:%d; sending NETINFO.",
  1361. // highest_supported_version,
  1362. // safe_str_client(chan->conn->base_.address),
  1363. // chan->conn->base_.port);
  1364. //if (connection_or_send_netinfo(chan->conn) < 0) {
  1365. // connection_or_close_for_error(chan->conn, 0);
  1366. // return;
  1367. //}
  1368. } else {
  1369. const int send_versions = !started_here;
  1370. /* If we want to authenticate, send a CERTS cell */
  1371. const int send_certs = !started_here || public_server_mode(get_options());
  1372. /* If we're a host that got a connection, ask for authentication. */
  1373. const int send_chall = !started_here;
  1374. /* If our certs cell will authenticate us, we can send a netinfo cell
  1375. * right now. */
  1376. const int send_netinfo = !started_here;
  1377. const int send_any =
  1378. send_versions || send_certs || send_chall || send_netinfo;
  1379. tor_assert(link_protocol >= 3);
  1380. log_info(LD_OR,
  1381. "Negotiated version %d with %s:%d; %s%s%s%s%s",
  1382. highest_supported_version,
  1383. safe_str_client(chan->conn->base_.address),
  1384. chan->conn->base_.port,
  1385. send_any ? "Sending cells:" : "Waiting for CERTS cell",
  1386. send_versions ? " VERSIONS" : "",
  1387. send_certs ? " CERTS" : "",
  1388. send_chall ? " AUTH_CHALLENGE" : "",
  1389. send_netinfo ? " NETINFO" : "");
  1390. #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
  1391. if (1) {
  1392. connection_or_close_normally(chan->conn, 1);
  1393. return;
  1394. }
  1395. #endif /* defined(DISABLE_V3_LINKPROTO_SERVERSIDE) */
  1396. if (send_versions) {
  1397. if (connection_or_send_versions(chan->conn, 1) < 0) {
  1398. log_warn(LD_OR, "Couldn't send versions cell");
  1399. connection_or_close_for_error(chan->conn, 0);
  1400. return;
  1401. }
  1402. }
  1403. chan->conn->link_proto = link_protocol;
  1404. chan->conn->handshake_state->received_versions = 1;
  1405. event_data_t event_data = { .u16 = chan->conn->link_proto };
  1406. event_source_publish(TO_CONN(chan->conn)->event_source,
  1407. or_conn_link_protocol_version_ev, event_data, NULL);
  1408. /* We set this after sending the versions cell. */
  1409. /*XXXXX symbolic const.*/
  1410. TLS_CHAN_TO_BASE(chan)->wide_circ_ids =
  1411. chan->conn->link_proto >= MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS;
  1412. chan->conn->wide_circ_ids = TLS_CHAN_TO_BASE(chan)->wide_circ_ids;
  1413. TLS_CHAN_TO_BASE(chan)->padding_enabled =
  1414. chan->conn->link_proto >= MIN_LINK_PROTO_FOR_CHANNEL_PADDING;
  1415. if (send_certs) {
  1416. if (connection_or_send_certs_cell(chan->conn) < 0) {
  1417. log_warn(LD_OR, "Couldn't send certs cell");
  1418. connection_or_close_for_error(chan->conn, 0);
  1419. return;
  1420. }
  1421. }
  1422. if (send_chall) {
  1423. if (connection_or_send_auth_challenge_cell(chan->conn) < 0) {
  1424. log_warn(LD_OR, "Couldn't send auth_challenge cell");
  1425. connection_or_close_for_error(chan->conn, 0);
  1426. return;
  1427. }
  1428. }
  1429. if (send_netinfo) {
  1430. if (connection_or_send_netinfo(chan->conn) < 0) {
  1431. log_warn(LD_OR, "Couldn't send netinfo cell");
  1432. connection_or_close_for_error(chan->conn, 0);
  1433. return;
  1434. }
  1435. }
  1436. }
  1437. }
  1438. /**
  1439. * Process a 'padding_negotiate' cell.
  1440. *
  1441. * This function is called to handle an incoming PADDING_NEGOTIATE cell;
  1442. * enable or disable padding accordingly, and read and act on its timeout
  1443. * value contents.
  1444. */
  1445. static void
  1446. channel_tls_process_padding_negotiate_cell(cell_t *cell, channel_tls_t *chan)
  1447. {
  1448. channelpadding_negotiate_t *negotiation;
  1449. tor_assert(cell);
  1450. tor_assert(chan);
  1451. tor_assert(chan->conn);
  1452. if (chan->conn->link_proto < MIN_LINK_PROTO_FOR_CHANNEL_PADDING) {
  1453. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1454. "Received a PADDING_NEGOTIATE cell on v%d connection; dropping.",
  1455. chan->conn->link_proto);
  1456. return;
  1457. }
  1458. if (channelpadding_negotiate_parse(&negotiation, cell->payload,
  1459. CELL_PAYLOAD_SIZE) < 0) {
  1460. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1461. "Received malformed PADDING_NEGOTIATE cell on v%d connection; "
  1462. "dropping.", chan->conn->link_proto);
  1463. return;
  1464. }
  1465. channelpadding_update_padding_for_channel(TLS_CHAN_TO_BASE(chan),
  1466. negotiation);
  1467. channelpadding_negotiate_free(negotiation);
  1468. }
  1469. /**
  1470. * Convert <b>netinfo_addr</b> into corresponding <b>tor_addr</b>.
  1471. * Return 0 on success; on failure, return -1 and log a warning.
  1472. */
  1473. static int
  1474. tor_addr_from_netinfo_addr(tor_addr_t *tor_addr,
  1475. const netinfo_addr_t *netinfo_addr) {
  1476. tor_assert(tor_addr);
  1477. tor_assert(netinfo_addr);
  1478. uint8_t type = netinfo_addr_get_addr_type(netinfo_addr);
  1479. uint8_t len = netinfo_addr_get_len(netinfo_addr);
  1480. if (type == NETINFO_ADDR_TYPE_IPV4 && len == 4) {
  1481. uint32_t ipv4 = netinfo_addr_get_addr_ipv4(netinfo_addr);
  1482. tor_addr_from_ipv4h(tor_addr, ipv4);
  1483. } else if (type == NETINFO_ADDR_TYPE_IPV6 && len == 16) {
  1484. const uint8_t *ipv6_bytes = netinfo_addr_getconstarray_addr_ipv6(
  1485. netinfo_addr);
  1486. tor_addr_from_ipv6_bytes(tor_addr, (const char *)ipv6_bytes);
  1487. } else {
  1488. log_fn(LOG_PROTOCOL_WARN, LD_OR, "Cannot read address from NETINFO "
  1489. "- wrong type/length.");
  1490. return -1;
  1491. }
  1492. return 0;
  1493. }
  1494. /**
  1495. * Helper: compute the absolute value of a time_t.
  1496. *
  1497. * (we need this because labs() doesn't always work for time_t, since
  1498. * long can be shorter than time_t.)
  1499. */
  1500. static inline time_t
  1501. time_abs(time_t val)
  1502. {
  1503. return (val < 0) ? -val : val;
  1504. }
  1505. /**
  1506. * Process a 'netinfo' cell
  1507. *
  1508. * This function is called to handle an incoming NETINFO cell; read and act
  1509. * on its contents, and set the connection state to "open".
  1510. */
  1511. static void
  1512. channel_tls_process_netinfo_cell(cell_t *cell, channel_tls_t *chan)
  1513. {
  1514. time_t timestamp;
  1515. uint8_t my_addr_type;
  1516. uint8_t my_addr_len;
  1517. uint8_t n_other_addrs;
  1518. time_t now = time(NULL);
  1519. const routerinfo_t *me = router_get_my_routerinfo();
  1520. time_t apparent_skew = 0;
  1521. tor_addr_t my_apparent_addr = TOR_ADDR_NULL;
  1522. int started_here = 0;
  1523. const char *identity_digest = NULL;
  1524. tor_assert(cell);
  1525. tor_assert(chan);
  1526. tor_assert(chan->conn);
  1527. if (chan->conn->link_proto < 2) {
  1528. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1529. "Received a NETINFO cell on %s connection; dropping.",
  1530. chan->conn->link_proto == 0 ? "non-versioned" : "a v1");
  1531. return;
  1532. }
  1533. if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V2 &&
  1534. chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3) {
  1535. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1536. "Received a NETINFO cell on non-handshaking connection; dropping.");
  1537. return;
  1538. }
  1539. tor_assert(chan->conn->handshake_state &&
  1540. chan->conn->handshake_state->received_versions);
  1541. started_here = connection_or_nonopen_was_started_here(chan->conn);
  1542. identity_digest = chan->conn->identity_digest;
  1543. if (chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
  1544. tor_assert(chan->conn->link_proto >= 3);
  1545. if (started_here) {
  1546. if (!(chan->conn->handshake_state->authenticated)) {
  1547. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1548. "Got a NETINFO cell from server, "
  1549. "but no authentication. Closing the connection.");
  1550. connection_or_close_for_error(chan->conn, 0);
  1551. return;
  1552. }
  1553. } else {
  1554. /* we're the server. If the client never authenticated, we have
  1555. some housekeeping to do.*/
  1556. if (!(chan->conn->handshake_state->authenticated)) {
  1557. tor_assert(tor_digest_is_zero(
  1558. (const char*)(chan->conn->handshake_state->
  1559. authenticated_rsa_peer_id)));
  1560. tor_assert(fast_mem_is_zero(
  1561. (const char*)(chan->conn->handshake_state->
  1562. authenticated_ed25519_peer_id.pubkey), 32));
  1563. /* If the client never authenticated, it's a tor client or bridge
  1564. * relay, and we must not use it for EXTEND requests (nor could we, as
  1565. * there are no authenticated peer IDs) */
  1566. channel_mark_client(TLS_CHAN_TO_BASE(chan));
  1567. channel_set_circid_type(TLS_CHAN_TO_BASE(chan), NULL,
  1568. chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
  1569. connection_or_init_conn_from_address(chan->conn,
  1570. &(chan->conn->base_.addr),
  1571. chan->conn->base_.port,
  1572. /* zero, checked above */
  1573. (const char*)(chan->conn->handshake_state->
  1574. authenticated_rsa_peer_id),
  1575. NULL, /* Ed25519 ID: Also checked as zero */
  1576. 0);
  1577. }
  1578. }
  1579. }
  1580. /* Decode the cell. */
  1581. netinfo_cell_t *netinfo_cell = NULL;
  1582. ssize_t parsed = netinfo_cell_parse(&netinfo_cell, cell->payload,
  1583. CELL_PAYLOAD_SIZE);
  1584. if (parsed < 0) {
  1585. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1586. "Failed to parse NETINFO cell - closing connection.");
  1587. connection_or_close_for_error(chan->conn, 0);
  1588. return;
  1589. }
  1590. timestamp = netinfo_cell_get_timestamp(netinfo_cell);
  1591. const netinfo_addr_t *my_addr =
  1592. netinfo_cell_getconst_other_addr(netinfo_cell);
  1593. my_addr_type = netinfo_addr_get_addr_type(my_addr);
  1594. my_addr_len = netinfo_addr_get_len(my_addr);
  1595. if ((now - chan->conn->handshake_state->sent_versions_at) < 180) {
  1596. apparent_skew = now - timestamp;
  1597. }
  1598. /* We used to check:
  1599. * if (my_addr_len >= CELL_PAYLOAD_SIZE - 6) {
  1600. *
  1601. * This is actually never going to happen, since my_addr_len is at most 255,
  1602. * and CELL_PAYLOAD_LEN - 6 is 503. So we know that cp is < end. */
  1603. if (tor_addr_from_netinfo_addr(&my_apparent_addr, my_addr) == -1) {
  1604. connection_or_close_for_error(chan->conn, 0);
  1605. netinfo_cell_free(netinfo_cell);
  1606. return;
  1607. }
  1608. if (my_addr_type == NETINFO_ADDR_TYPE_IPV4 && my_addr_len == 4) {
  1609. if (!get_options()->BridgeRelay && me &&
  1610. tor_addr_eq_ipv4h(&my_apparent_addr, me->addr)) {
  1611. TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer = 1;
  1612. }
  1613. } else if (my_addr_type == NETINFO_ADDR_TYPE_IPV6 &&
  1614. my_addr_len == 16) {
  1615. if (!get_options()->BridgeRelay && me &&
  1616. !tor_addr_is_null(&me->ipv6_addr) &&
  1617. tor_addr_eq(&my_apparent_addr, &me->ipv6_addr)) {
  1618. TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer = 1;
  1619. }
  1620. }
  1621. n_other_addrs = netinfo_cell_get_n_my_addrs(netinfo_cell);
  1622. for (uint8_t i = 0; i < n_other_addrs; i++) {
  1623. /* Consider all the other addresses; if any matches, this connection is
  1624. * "canonical." */
  1625. const netinfo_addr_t *netinfo_addr =
  1626. netinfo_cell_getconst_my_addrs(netinfo_cell, i);
  1627. tor_addr_t addr;
  1628. if (tor_addr_from_netinfo_addr(&addr, netinfo_addr) == -1) {
  1629. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1630. "Bad address in netinfo cell; Skipping.");
  1631. continue;
  1632. }
  1633. /* A relay can connect from anywhere and be canonical, so
  1634. * long as it tells you from where it came. This may sound a bit
  1635. * concerning... but that's what "canonical" means: that the
  1636. * address is one that the relay itself has claimed. The relay
  1637. * might be doing something funny, but nobody else is doing a MITM
  1638. * on the relay's TCP.
  1639. */
  1640. if (tor_addr_eq(&addr, &(chan->conn->real_addr))) {
  1641. connection_or_set_canonical(chan->conn, 1);
  1642. break;
  1643. }
  1644. }
  1645. netinfo_cell_free(netinfo_cell);
  1646. if (me && !TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer &&
  1647. channel_is_canonical(TLS_CHAN_TO_BASE(chan))) {
  1648. const char *descr =
  1649. TLS_CHAN_TO_BASE(chan)->get_remote_descr(TLS_CHAN_TO_BASE(chan), 0);
  1650. log_info(LD_OR,
  1651. "We made a connection to a relay at %s (fp=%s) but we think "
  1652. "they will not consider this connection canonical. They "
  1653. "think we are at %s, but we think its %s.",
  1654. safe_str(descr),
  1655. safe_str(hex_str(identity_digest, DIGEST_LEN)),
  1656. safe_str(tor_addr_is_null(&my_apparent_addr) ?
  1657. "<none>" : fmt_and_decorate_addr(&my_apparent_addr)),
  1658. safe_str(fmt_addr32(me->addr)));
  1659. }
  1660. /* Act on apparent skew. */
  1661. /** Warn when we get a netinfo skew with at least this value. */
  1662. #define NETINFO_NOTICE_SKEW 3600
  1663. if (time_abs(apparent_skew) > NETINFO_NOTICE_SKEW &&
  1664. (started_here ||
  1665. connection_or_digest_is_known_relay(chan->conn->identity_digest))) {
  1666. int trusted = router_digest_is_trusted_dir(chan->conn->identity_digest);
  1667. clock_skew_warning(TO_CONN(chan->conn), apparent_skew, trusted, LD_GENERAL,
  1668. "NETINFO cell", "OR");
  1669. }
  1670. /* XXX maybe act on my_apparent_addr, if the source is sufficiently
  1671. * trustworthy. */
  1672. if (! chan->conn->handshake_state->sent_netinfo) {
  1673. /* If we were prepared to authenticate, but we never got an AUTH_CHALLENGE
  1674. * cell, then we would not previously have sent a NETINFO cell. Do so
  1675. * now. */
  1676. if (connection_or_send_netinfo(chan->conn) < 0) {
  1677. connection_or_close_for_error(chan->conn, 0);
  1678. return;
  1679. }
  1680. }
  1681. if (connection_or_set_state_open(chan->conn) < 0) {
  1682. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  1683. "Got good NETINFO cell from %s:%d; but "
  1684. "was unable to make the OR connection become open.",
  1685. safe_str_client(chan->conn->base_.address),
  1686. chan->conn->base_.port);
  1687. connection_or_close_for_error(chan->conn, 0);
  1688. } else {
  1689. log_info(LD_OR,
  1690. "Got good NETINFO cell from %s:%d; OR connection is now "
  1691. "open, using protocol version %d. Its ID digest is %s. "
  1692. "Our address is apparently %s.",
  1693. safe_str_client(chan->conn->base_.address),
  1694. chan->conn->base_.port,
  1695. (int)(chan->conn->link_proto),
  1696. hex_str(identity_digest, DIGEST_LEN),
  1697. tor_addr_is_null(&my_apparent_addr) ?
  1698. "<none>" :
  1699. safe_str_client(fmt_and_decorate_addr(&my_apparent_addr)));
  1700. }
  1701. assert_connection_ok(TO_CONN(chan->conn),time(NULL));
  1702. }
  1703. /** Types of certificates that we know how to parse from CERTS cells. Each
  1704. * type corresponds to a different encoding format. */
  1705. typedef enum cert_encoding_t {
  1706. CERT_ENCODING_UNKNOWN, /**< We don't recognize this. */
  1707. CERT_ENCODING_X509, /**< It's an RSA key, signed with RSA, encoded in x509.
  1708. * (Actually, it might not be RSA. We test that later.) */
  1709. CERT_ENCODING_ED25519, /**< It's something signed with an Ed25519 key,
  1710. * encoded asa a tor_cert_t.*/
  1711. CERT_ENCODING_RSA_CROSSCERT, /**< It's an Ed key signed with an RSA key. */
  1712. } cert_encoding_t;
  1713. /**
  1714. * Given one of the certificate type codes used in a CERTS cell,
  1715. * return the corresponding cert_encoding_t that we should use to parse
  1716. * the certificate.
  1717. */
  1718. static cert_encoding_t
  1719. certs_cell_typenum_to_cert_type(int typenum)
  1720. {
  1721. switch (typenum) {
  1722. case CERTTYPE_RSA1024_ID_LINK:
  1723. case CERTTYPE_RSA1024_ID_ID:
  1724. case CERTTYPE_RSA1024_ID_AUTH:
  1725. return CERT_ENCODING_X509;
  1726. case CERTTYPE_ED_ID_SIGN:
  1727. case CERTTYPE_ED_SIGN_LINK:
  1728. case CERTTYPE_ED_SIGN_AUTH:
  1729. return CERT_ENCODING_ED25519;
  1730. case CERTTYPE_RSA1024_ID_EDID:
  1731. return CERT_ENCODING_RSA_CROSSCERT;
  1732. default:
  1733. return CERT_ENCODING_UNKNOWN;
  1734. }
  1735. }
  1736. /**
  1737. * Process a CERTS cell from a channel.
  1738. *
  1739. * This function is called to process an incoming CERTS cell on a
  1740. * channel_tls_t:
  1741. *
  1742. * If the other side should not have sent us a CERTS cell, or the cell is
  1743. * malformed, or it is supposed to authenticate the TLS key but it doesn't,
  1744. * then mark the connection.
  1745. *
  1746. * If the cell has a good cert chain and we're doing a v3 handshake, then
  1747. * store the certificates in or_handshake_state. If this is the client side
  1748. * of the connection, we then authenticate the server or mark the connection.
  1749. * If it's the server side, wait for an AUTHENTICATE cell.
  1750. */
  1751. STATIC void
  1752. channel_tls_process_certs_cell(var_cell_t *cell, channel_tls_t *chan)
  1753. {
  1754. #define MAX_CERT_TYPE_WANTED CERTTYPE_RSA1024_ID_EDID
  1755. /* These arrays will be sparse, since a cert type can be at most one
  1756. * of ed/x509 */
  1757. tor_x509_cert_t *x509_certs[MAX_CERT_TYPE_WANTED + 1];
  1758. tor_cert_t *ed_certs[MAX_CERT_TYPE_WANTED + 1];
  1759. uint8_t *rsa_ed_cc_cert = NULL;
  1760. size_t rsa_ed_cc_cert_len = 0;
  1761. int n_certs, i;
  1762. certs_cell_t *cc = NULL;
  1763. int send_netinfo = 0, started_here = 0;
  1764. memset(x509_certs, 0, sizeof(x509_certs));
  1765. memset(ed_certs, 0, sizeof(ed_certs));
  1766. tor_assert(cell);
  1767. tor_assert(chan);
  1768. tor_assert(chan->conn);
  1769. #define ERR(s) \
  1770. do { \
  1771. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
  1772. "Received a bad CERTS cell from %s:%d: %s", \
  1773. safe_str(chan->conn->base_.address), \
  1774. chan->conn->base_.port, (s)); \
  1775. connection_or_close_for_error(chan->conn, 0); \
  1776. goto err; \
  1777. } while (0)
  1778. /* Can't use connection_or_nonopen_was_started_here(); its conn->tls
  1779. * check looks like it breaks
  1780. * test_link_handshake_recv_certs_ok_server(). */
  1781. started_here = chan->conn->handshake_state->started_here;
  1782. if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
  1783. ERR("We're not doing a v3 handshake!");
  1784. if (chan->conn->link_proto < 3)
  1785. ERR("We're not using link protocol >= 3");
  1786. if (chan->conn->handshake_state->received_certs_cell)
  1787. ERR("We already got one");
  1788. if (chan->conn->handshake_state->authenticated) {
  1789. /* Should be unreachable, but let's make sure. */
  1790. ERR("We're already authenticated!");
  1791. }
  1792. if (cell->payload_len < 1)
  1793. ERR("It had no body");
  1794. if (cell->circ_id)
  1795. ERR("It had a nonzero circuit ID");
  1796. if (certs_cell_parse(&cc, cell->payload, cell->payload_len) < 0)
  1797. ERR("It couldn't be parsed.");
  1798. n_certs = cc->n_certs;
  1799. for (i = 0; i < n_certs; ++i) {
  1800. certs_cell_cert_t *c = certs_cell_get_certs(cc, i);
  1801. uint16_t cert_type = c->cert_type;
  1802. uint16_t cert_len = c->cert_len;
  1803. uint8_t *cert_body = certs_cell_cert_getarray_body(c);
  1804. if (cert_type > MAX_CERT_TYPE_WANTED)
  1805. continue;
  1806. const cert_encoding_t ct = certs_cell_typenum_to_cert_type(cert_type);
  1807. switch (ct) {
  1808. default:
  1809. case CERT_ENCODING_UNKNOWN:
  1810. break;
  1811. case CERT_ENCODING_X509: {
  1812. tor_x509_cert_t *x509_cert = tor_x509_cert_decode(cert_body, cert_len);
  1813. if (!x509_cert) {
  1814. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1815. "Received undecodable certificate in CERTS cell from %s:%d",
  1816. safe_str(chan->conn->base_.address),
  1817. chan->conn->base_.port);
  1818. } else {
  1819. if (x509_certs[cert_type]) {
  1820. tor_x509_cert_free(x509_cert);
  1821. ERR("Duplicate x509 certificate");
  1822. } else {
  1823. x509_certs[cert_type] = x509_cert;
  1824. }
  1825. }
  1826. break;
  1827. }
  1828. case CERT_ENCODING_ED25519: {
  1829. tor_cert_t *ed_cert = tor_cert_parse(cert_body, cert_len);
  1830. if (!ed_cert) {
  1831. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1832. "Received undecodable Ed certificate "
  1833. "in CERTS cell from %s:%d",
  1834. safe_str(chan->conn->base_.address),
  1835. chan->conn->base_.port);
  1836. } else {
  1837. if (ed_certs[cert_type]) {
  1838. tor_cert_free(ed_cert);
  1839. ERR("Duplicate Ed25519 certificate");
  1840. } else {
  1841. ed_certs[cert_type] = ed_cert;
  1842. }
  1843. }
  1844. break;
  1845. }
  1846. case CERT_ENCODING_RSA_CROSSCERT: {
  1847. if (rsa_ed_cc_cert) {
  1848. ERR("Duplicate RSA->Ed25519 crosscert");
  1849. } else {
  1850. rsa_ed_cc_cert = tor_memdup(cert_body, cert_len);
  1851. rsa_ed_cc_cert_len = cert_len;
  1852. }
  1853. break;
  1854. }
  1855. }
  1856. }
  1857. /* Move the certificates we (might) want into the handshake_state->certs
  1858. * structure. */
  1859. tor_x509_cert_t *id_cert = x509_certs[CERTTYPE_RSA1024_ID_ID];
  1860. tor_x509_cert_t *auth_cert = x509_certs[CERTTYPE_RSA1024_ID_AUTH];
  1861. tor_x509_cert_t *link_cert = x509_certs[CERTTYPE_RSA1024_ID_LINK];
  1862. chan->conn->handshake_state->certs->auth_cert = auth_cert;
  1863. chan->conn->handshake_state->certs->link_cert = link_cert;
  1864. chan->conn->handshake_state->certs->id_cert = id_cert;
  1865. x509_certs[CERTTYPE_RSA1024_ID_ID] =
  1866. x509_certs[CERTTYPE_RSA1024_ID_AUTH] =
  1867. x509_certs[CERTTYPE_RSA1024_ID_LINK] = NULL;
  1868. tor_cert_t *ed_id_sign = ed_certs[CERTTYPE_ED_ID_SIGN];
  1869. tor_cert_t *ed_sign_link = ed_certs[CERTTYPE_ED_SIGN_LINK];
  1870. tor_cert_t *ed_sign_auth = ed_certs[CERTTYPE_ED_SIGN_AUTH];
  1871. chan->conn->handshake_state->certs->ed_id_sign = ed_id_sign;
  1872. chan->conn->handshake_state->certs->ed_sign_link = ed_sign_link;
  1873. chan->conn->handshake_state->certs->ed_sign_auth = ed_sign_auth;
  1874. ed_certs[CERTTYPE_ED_ID_SIGN] =
  1875. ed_certs[CERTTYPE_ED_SIGN_LINK] =
  1876. ed_certs[CERTTYPE_ED_SIGN_AUTH] = NULL;
  1877. chan->conn->handshake_state->certs->ed_rsa_crosscert = rsa_ed_cc_cert;
  1878. chan->conn->handshake_state->certs->ed_rsa_crosscert_len =
  1879. rsa_ed_cc_cert_len;
  1880. rsa_ed_cc_cert = NULL;
  1881. int severity;
  1882. /* Note that this warns more loudly about time and validity if we were
  1883. * _trying_ to connect to an authority, not necessarily if we _did_ connect
  1884. * to one. */
  1885. if (started_here &&
  1886. router_digest_is_trusted_dir(TLS_CHAN_TO_BASE(chan)->identity_digest))
  1887. severity = LOG_WARN;
  1888. else
  1889. severity = LOG_PROTOCOL_WARN;
  1890. const ed25519_public_key_t *checked_ed_id = NULL;
  1891. const common_digests_t *checked_rsa_id = NULL;
  1892. or_handshake_certs_check_both(severity,
  1893. chan->conn->handshake_state->certs,
  1894. //chan->conn->tls,
  1895. chan->conn->tls_peer_cert,
  1896. time(NULL),
  1897. &checked_ed_id,
  1898. &checked_rsa_id);
  1899. if (!checked_rsa_id)
  1900. ERR("Invalid certificate chain!");
  1901. if (started_here) {
  1902. /* No more information is needed. */
  1903. chan->conn->handshake_state->authenticated = 1;
  1904. chan->conn->handshake_state->authenticated_rsa = 1;
  1905. {
  1906. const common_digests_t *id_digests = checked_rsa_id;
  1907. crypto_pk_t *identity_rcvd;
  1908. if (!id_digests)
  1909. ERR("Couldn't compute digests for key in ID cert");
  1910. identity_rcvd = tor_tls_cert_get_key(id_cert);
  1911. if (!identity_rcvd) {
  1912. ERR("Couldn't get RSA key from ID cert.");
  1913. }
  1914. memcpy(chan->conn->handshake_state->authenticated_rsa_peer_id,
  1915. id_digests->d[DIGEST_SHA1], DIGEST_LEN);
  1916. channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
  1917. chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
  1918. crypto_pk_free(identity_rcvd);
  1919. }
  1920. if (checked_ed_id) {
  1921. chan->conn->handshake_state->authenticated_ed25519 = 1;
  1922. memcpy(&chan->conn->handshake_state->authenticated_ed25519_peer_id,
  1923. checked_ed_id, sizeof(ed25519_public_key_t));
  1924. }
  1925. log_debug(LD_HANDSHAKE, "calling client_learned_peer_id from "
  1926. "process_certs_cell");
  1927. if (connection_or_client_learned_peer_id(chan->conn,
  1928. chan->conn->handshake_state->authenticated_rsa_peer_id,
  1929. checked_ed_id) < 0)
  1930. ERR("Problem setting or checking peer id");
  1931. log_info(LD_HANDSHAKE,
  1932. "Got some good certificates from %s:%d: Authenticated it with "
  1933. "RSA%s",
  1934. safe_str(chan->conn->base_.address), chan->conn->base_.port,
  1935. checked_ed_id ? " and Ed25519" : "");
  1936. if (!public_server_mode(get_options())) {
  1937. /* If we initiated the connection and we are not a public server, we
  1938. * aren't planning to authenticate at all. At this point we know who we
  1939. * are talking to, so we can just send a netinfo now. */
  1940. send_netinfo = 1;
  1941. }
  1942. } else {
  1943. /* We can't call it authenticated till we see an AUTHENTICATE cell. */
  1944. log_info(LD_OR,
  1945. "Got some good RSA%s certificates from %s:%d. "
  1946. "Waiting for AUTHENTICATE.",
  1947. checked_ed_id ? " and Ed25519" : "",
  1948. safe_str(chan->conn->base_.address),
  1949. chan->conn->base_.port);
  1950. /* XXXX check more stuff? */
  1951. }
  1952. chan->conn->handshake_state->received_certs_cell = 1;
  1953. if (send_netinfo) {
  1954. if (connection_or_send_netinfo(chan->conn) < 0) {
  1955. log_warn(LD_OR, "Couldn't send netinfo cell");
  1956. connection_or_close_for_error(chan->conn, 0);
  1957. goto err;
  1958. }
  1959. }
  1960. err:
  1961. for (unsigned u = 0; u < ARRAY_LENGTH(x509_certs); ++u) {
  1962. tor_x509_cert_free(x509_certs[u]);
  1963. }
  1964. for (unsigned u = 0; u < ARRAY_LENGTH(ed_certs); ++u) {
  1965. tor_cert_free(ed_certs[u]);
  1966. }
  1967. tor_free(rsa_ed_cc_cert);
  1968. certs_cell_free(cc);
  1969. #undef ERR
  1970. }
  1971. /**
  1972. * Process an AUTH_CHALLENGE cell from a channel_tls_t.
  1973. *
  1974. * This function is called to handle an incoming AUTH_CHALLENGE cell on a
  1975. * channel_tls_t; if we weren't supposed to get one (for example, because we're
  1976. * not the originator of the channel), or it's ill-formed, or we aren't doing
  1977. * a v3 handshake, mark the channel. If the cell is well-formed but we don't
  1978. * want to authenticate, just drop it. If the cell is well-formed *and* we
  1979. * want to authenticate, send an AUTHENTICATE cell and then a NETINFO cell.
  1980. */
  1981. STATIC void
  1982. channel_tls_process_auth_challenge_cell(var_cell_t *cell, channel_tls_t *chan)
  1983. {
  1984. int n_types, i, use_type = -1;
  1985. auth_challenge_cell_t *ac = NULL;
  1986. tor_assert(cell);
  1987. tor_assert(chan);
  1988. tor_assert(chan->conn);
  1989. #define ERR(s) \
  1990. do { \
  1991. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
  1992. "Received a bad AUTH_CHALLENGE cell from %s:%d: %s", \
  1993. safe_str(chan->conn->base_.address), \
  1994. chan->conn->base_.port, (s)); \
  1995. connection_or_close_for_error(chan->conn, 0); \
  1996. goto done; \
  1997. } while (0)
  1998. if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
  1999. ERR("We're not currently doing a v3 handshake");
  2000. if (chan->conn->link_proto < 3)
  2001. ERR("We're not using link protocol >= 3");
  2002. if (!(chan->conn->handshake_state->started_here))
  2003. ERR("We didn't originate this connection");
  2004. if (chan->conn->handshake_state->received_auth_challenge)
  2005. ERR("We already received one");
  2006. if (!(chan->conn->handshake_state->received_certs_cell))
  2007. ERR("We haven't gotten a CERTS cell yet");
  2008. if (cell->circ_id)
  2009. ERR("It had a nonzero circuit ID");
  2010. if (auth_challenge_cell_parse(&ac, cell->payload, cell->payload_len) < 0)
  2011. ERR("It was not well-formed.");
  2012. n_types = ac->n_methods;
  2013. /* Now see if there is an authentication type we can use */
  2014. for (i = 0; i < n_types; ++i) {
  2015. uint16_t authtype = auth_challenge_cell_get_methods(ac, i);
  2016. if (authchallenge_type_is_supported(authtype)) {
  2017. if (use_type == -1 ||
  2018. authchallenge_type_is_better(authtype, use_type)) {
  2019. use_type = authtype;
  2020. }
  2021. }
  2022. }
  2023. chan->conn->handshake_state->received_auth_challenge = 1;
  2024. if (! public_server_mode(get_options())) {
  2025. /* If we're not a public server then we don't want to authenticate on a
  2026. connection we originated, and we already sent a NETINFO cell when we
  2027. got the CERTS cell. We have nothing more to do. */
  2028. goto done;
  2029. }
  2030. if (use_type >= 0) {
  2031. log_info(LD_OR,
  2032. "Got an AUTH_CHALLENGE cell from %s:%d: Sending "
  2033. "authentication type %d",
  2034. safe_str(chan->conn->base_.address),
  2035. chan->conn->base_.port,
  2036. use_type);
  2037. if (connection_or_send_authenticate_cell(chan->conn, use_type) < 0) {
  2038. log_warn(LD_OR,
  2039. "Couldn't send authenticate cell");
  2040. connection_or_close_for_error(chan->conn, 0);
  2041. goto done;
  2042. }
  2043. } else {
  2044. log_info(LD_OR,
  2045. "Got an AUTH_CHALLENGE cell from %s:%d, but we don't "
  2046. "know any of its authentication types. Not authenticating.",
  2047. safe_str(chan->conn->base_.address),
  2048. chan->conn->base_.port);
  2049. }
  2050. if (connection_or_send_netinfo(chan->conn) < 0) {
  2051. log_warn(LD_OR, "Couldn't send netinfo cell");
  2052. connection_or_close_for_error(chan->conn, 0);
  2053. goto done;
  2054. }
  2055. done:
  2056. auth_challenge_cell_free(ac);
  2057. #undef ERR
  2058. }
  2059. /**
  2060. * Process an AUTHENTICATE cell from a channel_tls_t.
  2061. *
  2062. * If it's ill-formed or we weren't supposed to get one or we're not doing a
  2063. * v3 handshake, then mark the connection. If it does not authenticate the
  2064. * other side of the connection successfully (because it isn't signed right,
  2065. * we didn't get a CERTS cell, etc) mark the connection. Otherwise, accept
  2066. * the identity of the router on the other side of the connection.
  2067. */
  2068. STATIC void
  2069. channel_tls_process_authenticate_cell(var_cell_t *cell, channel_tls_t *chan)
  2070. {
  2071. var_cell_t *expected_cell = NULL;
  2072. const uint8_t *auth;
  2073. int authlen;
  2074. int authtype;
  2075. int bodylen;
  2076. tor_assert(cell);
  2077. tor_assert(chan);
  2078. tor_assert(chan->conn);
  2079. #define ERR(s) \
  2080. do { \
  2081. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
  2082. "Received a bad AUTHENTICATE cell from %s:%d: %s", \
  2083. safe_str(chan->conn->base_.address), \
  2084. chan->conn->base_.port, (s)); \
  2085. connection_or_close_for_error(chan->conn, 0); \
  2086. var_cell_free(expected_cell); \
  2087. return; \
  2088. } while (0)
  2089. if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
  2090. ERR("We're not doing a v3 handshake");
  2091. if (chan->conn->link_proto < 3)
  2092. ERR("We're not using link protocol >= 3");
  2093. if (chan->conn->handshake_state->started_here)
  2094. ERR("We originated this connection");
  2095. if (chan->conn->handshake_state->received_authenticate)
  2096. ERR("We already got one!");
  2097. if (chan->conn->handshake_state->authenticated) {
  2098. /* Should be impossible given other checks */
  2099. ERR("The peer is already authenticated");
  2100. }
  2101. if (!(chan->conn->handshake_state->received_certs_cell))
  2102. ERR("We never got a certs cell");
  2103. if (chan->conn->handshake_state->certs->id_cert == NULL)
  2104. ERR("We never got an identity certificate");
  2105. if (cell->payload_len < 4)
  2106. ERR("Cell was way too short");
  2107. auth = cell->payload;
  2108. {
  2109. uint16_t type = ntohs(get_uint16(auth));
  2110. uint16_t len = ntohs(get_uint16(auth+2));
  2111. if (4 + len > cell->payload_len)
  2112. ERR("Authenticator was truncated");
  2113. if (! authchallenge_type_is_supported(type))
  2114. ERR("Authenticator type was not recognized");
  2115. authtype = type;
  2116. auth += 4;
  2117. authlen = len;
  2118. }
  2119. if (authlen < V3_AUTH_BODY_LEN + 1)
  2120. ERR("Authenticator was too short");
  2121. expected_cell = connection_or_compute_authenticate_cell_body(
  2122. chan->conn, authtype, NULL, NULL, 1);
  2123. if (! expected_cell)
  2124. ERR("Couldn't compute expected AUTHENTICATE cell body");
  2125. int sig_is_rsa;
  2126. if (authtype == AUTHTYPE_RSA_SHA256_TLSSECRET ||
  2127. authtype == AUTHTYPE_RSA_SHA256_RFC5705) {
  2128. bodylen = V3_AUTH_BODY_LEN;
  2129. sig_is_rsa = 1;
  2130. } else {
  2131. tor_assert(authtype == AUTHTYPE_ED25519_SHA256_RFC5705);
  2132. /* Our earlier check had better have made sure we had room
  2133. * for an ed25519 sig (inadvertently) */
  2134. tor_assert(V3_AUTH_BODY_LEN > ED25519_SIG_LEN);
  2135. bodylen = authlen - ED25519_SIG_LEN;
  2136. sig_is_rsa = 0;
  2137. }
  2138. if (expected_cell->payload_len != bodylen+4) {
  2139. ERR("Expected AUTHENTICATE cell body len not as expected.");
  2140. }
  2141. /* Length of random part. */
  2142. if (BUG(bodylen < 24)) {
  2143. // LCOV_EXCL_START
  2144. ERR("Bodylen is somehow less than 24, which should really be impossible");
  2145. // LCOV_EXCL_STOP
  2146. }
  2147. if (tor_memneq(expected_cell->payload+4, auth, bodylen-24))
  2148. ERR("Some field in the AUTHENTICATE cell body was not as expected");
  2149. if (sig_is_rsa) {
  2150. if (chan->conn->handshake_state->certs->ed_id_sign != NULL)
  2151. ERR("RSA-signed AUTHENTICATE response provided with an ED25519 cert");
  2152. if (chan->conn->handshake_state->certs->auth_cert == NULL)
  2153. ERR("We never got an RSA authentication certificate");
  2154. crypto_pk_t *pk = tor_tls_cert_get_key(
  2155. chan->conn->handshake_state->certs->auth_cert);
  2156. char d[DIGEST256_LEN];
  2157. char *signed_data;
  2158. size_t keysize;
  2159. int signed_len;
  2160. if (! pk) {
  2161. ERR("Couldn't get RSA key from AUTH cert.");
  2162. }
  2163. crypto_digest256(d, (char*)auth, V3_AUTH_BODY_LEN, DIGEST_SHA256);
  2164. keysize = crypto_pk_keysize(pk);
  2165. signed_data = tor_malloc(keysize);
  2166. signed_len = crypto_pk_public_checksig(pk, signed_data, keysize,
  2167. (char*)auth + V3_AUTH_BODY_LEN,
  2168. authlen - V3_AUTH_BODY_LEN);
  2169. crypto_pk_free(pk);
  2170. if (signed_len < 0) {
  2171. tor_free(signed_data);
  2172. ERR("RSA signature wasn't valid");
  2173. }
  2174. if (signed_len < DIGEST256_LEN) {
  2175. tor_free(signed_data);
  2176. ERR("Not enough data was signed");
  2177. }
  2178. /* Note that we deliberately allow *more* than DIGEST256_LEN bytes here,
  2179. * in case they're later used to hold a SHA3 digest or something. */
  2180. if (tor_memneq(signed_data, d, DIGEST256_LEN)) {
  2181. tor_free(signed_data);
  2182. ERR("Signature did not match data to be signed.");
  2183. }
  2184. tor_free(signed_data);
  2185. } else {
  2186. if (chan->conn->handshake_state->certs->ed_id_sign == NULL)
  2187. ERR("We never got an Ed25519 identity certificate.");
  2188. if (chan->conn->handshake_state->certs->ed_sign_auth == NULL)
  2189. ERR("We never got an Ed25519 authentication certificate.");
  2190. const ed25519_public_key_t *authkey =
  2191. &chan->conn->handshake_state->certs->ed_sign_auth->signed_key;
  2192. ed25519_signature_t sig;
  2193. tor_assert(authlen > ED25519_SIG_LEN);
  2194. memcpy(&sig.sig, auth + authlen - ED25519_SIG_LEN, ED25519_SIG_LEN);
  2195. if (ed25519_checksig(&sig, auth, authlen - ED25519_SIG_LEN, authkey)<0) {
  2196. ERR("Ed25519 signature wasn't valid.");
  2197. }
  2198. }
  2199. /* Okay, we are authenticated. */
  2200. chan->conn->handshake_state->received_authenticate = 1;
  2201. chan->conn->handshake_state->authenticated = 1;
  2202. chan->conn->handshake_state->authenticated_rsa = 1;
  2203. chan->conn->handshake_state->digest_received_data = 0;
  2204. {
  2205. tor_x509_cert_t *id_cert = chan->conn->handshake_state->certs->id_cert;
  2206. crypto_pk_t *identity_rcvd = tor_tls_cert_get_key(id_cert);
  2207. const common_digests_t *id_digests = tor_x509_cert_get_id_digests(id_cert);
  2208. const ed25519_public_key_t *ed_identity_received = NULL;
  2209. if (! sig_is_rsa) {
  2210. chan->conn->handshake_state->authenticated_ed25519 = 1;
  2211. ed_identity_received =
  2212. &chan->conn->handshake_state->certs->ed_id_sign->signing_key;
  2213. memcpy(&chan->conn->handshake_state->authenticated_ed25519_peer_id,
  2214. ed_identity_received, sizeof(ed25519_public_key_t));
  2215. }
  2216. /* This must exist; we checked key type when reading the cert. */
  2217. tor_assert(id_digests);
  2218. memcpy(chan->conn->handshake_state->authenticated_rsa_peer_id,
  2219. id_digests->d[DIGEST_SHA1], DIGEST_LEN);
  2220. channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
  2221. chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
  2222. crypto_pk_free(identity_rcvd);
  2223. log_debug(LD_HANDSHAKE,
  2224. "Calling connection_or_init_conn_from_address for %s "
  2225. " from %s, with%s ed25519 id.",
  2226. safe_str(chan->conn->base_.address),
  2227. __func__,
  2228. ed_identity_received ? "" : "out");
  2229. connection_or_init_conn_from_address(chan->conn,
  2230. &(chan->conn->base_.addr),
  2231. chan->conn->base_.port,
  2232. (const char*)(chan->conn->handshake_state->
  2233. authenticated_rsa_peer_id),
  2234. ed_identity_received,
  2235. 0);
  2236. log_debug(LD_HANDSHAKE,
  2237. "Got an AUTHENTICATE cell from %s:%d, type %d: Looks good.",
  2238. safe_str(chan->conn->base_.address),
  2239. chan->conn->base_.port,
  2240. authtype);
  2241. }
  2242. var_cell_free(expected_cell);
  2243. #undef ERR
  2244. }