connection_or.c 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2016, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file connection_or.c
  8. * \brief Functions to handle OR connections, TLS handshaking, and
  9. * cells on the network.
  10. *
  11. * An or_connection_t is a subtype of connection_t (as implemented in
  12. * connection.c) that uses a TLS connection to send and receive cells on the
  13. * Tor network. (By sending and receiving cells connection_or.c, it cooperates
  14. * with channeltls.c to implement a the channel interface of channel.c.)
  15. *
  16. * Every OR connection has an underlying tortls_t object (as implemented in
  17. * tortls.c) which it uses as its TLS stream. It is responsible for
  18. * sending and receiving cells over that TLS.
  19. *
  20. * This module also implements the client side of the v3 Tor link handshake,
  21. **/
  22. #include "or.h"
  23. #include "bridges.h"
  24. #include "buffers.h"
  25. /*
  26. * Define this so we get channel internal functions, since we're implementing
  27. * part of a subclass (channel_tls_t).
  28. */
  29. #define TOR_CHANNEL_INTERNAL_
  30. #include "channel.h"
  31. #include "channeltls.h"
  32. #include "circuitbuild.h"
  33. #include "circuitlist.h"
  34. #include "circuitstats.h"
  35. #include "command.h"
  36. #include "config.h"
  37. #include "connection.h"
  38. #include "connection_or.h"
  39. #include "control.h"
  40. #include "dirserv.h"
  41. #include "entrynodes.h"
  42. #include "geoip.h"
  43. #include "main.h"
  44. #include "link_handshake.h"
  45. #include "microdesc.h"
  46. #include "networkstatus.h"
  47. #include "nodelist.h"
  48. #include "reasons.h"
  49. #include "relay.h"
  50. #include "rephist.h"
  51. #include "router.h"
  52. #include "routerkeys.h"
  53. #include "routerlist.h"
  54. #include "ext_orport.h"
  55. #include "scheduler.h"
  56. #include "torcert.h"
  57. static int connection_tls_finish_handshake(or_connection_t *conn);
  58. static int connection_or_launch_v3_or_handshake(or_connection_t *conn);
  59. static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
  60. static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
  61. int started_here,
  62. char *digest_rcvd_out);
  63. static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn);
  64. static unsigned int
  65. connection_or_is_bad_for_new_circs(or_connection_t *or_conn);
  66. static void connection_or_mark_bad_for_new_circs(or_connection_t *or_conn);
  67. /*
  68. * Call this when changing connection state, so notifications to the owning
  69. * channel can be handled.
  70. */
  71. static void connection_or_change_state(or_connection_t *conn, uint8_t state);
  72. /**************************************************************/
  73. /** Map from identity digest of connected OR or desired OR to a connection_t
  74. * with that identity digest. If there is more than one such connection_t,
  75. * they form a linked list, with next_with_same_id as the next pointer. */
  76. static digestmap_t *orconn_identity_map = NULL;
  77. /** Global map between Extended ORPort identifiers and OR
  78. * connections. */
  79. static digestmap_t *orconn_ext_or_id_map = NULL;
  80. /** If conn is listed in orconn_identity_map, remove it, and clear
  81. * conn->identity_digest. Otherwise do nothing. */
  82. void
  83. connection_or_remove_from_identity_map(or_connection_t *conn)
  84. {
  85. or_connection_t *tmp;
  86. tor_assert(conn);
  87. if (!orconn_identity_map)
  88. return;
  89. tmp = digestmap_get(orconn_identity_map, conn->identity_digest);
  90. if (!tmp) {
  91. if (!tor_digest_is_zero(conn->identity_digest)) {
  92. log_warn(LD_BUG, "Didn't find connection '%s' on identity map when "
  93. "trying to remove it.",
  94. conn->nickname ? conn->nickname : "NULL");
  95. }
  96. return;
  97. }
  98. if (conn == tmp) {
  99. if (conn->next_with_same_id)
  100. digestmap_set(orconn_identity_map, conn->identity_digest,
  101. conn->next_with_same_id);
  102. else
  103. digestmap_remove(orconn_identity_map, conn->identity_digest);
  104. } else {
  105. while (tmp->next_with_same_id) {
  106. if (tmp->next_with_same_id == conn) {
  107. tmp->next_with_same_id = conn->next_with_same_id;
  108. break;
  109. }
  110. tmp = tmp->next_with_same_id;
  111. }
  112. }
  113. memset(conn->identity_digest, 0, DIGEST_LEN);
  114. conn->next_with_same_id = NULL;
  115. }
  116. /** Remove all entries from the identity-to-orconn map, and clear
  117. * all identities in OR conns.*/
  118. void
  119. connection_or_clear_identity_map(void)
  120. {
  121. smartlist_t *conns = get_connection_array();
  122. SMARTLIST_FOREACH(conns, connection_t *, conn,
  123. {
  124. if (conn->type == CONN_TYPE_OR) {
  125. or_connection_t *or_conn = TO_OR_CONN(conn);
  126. memset(or_conn->identity_digest, 0, DIGEST_LEN);
  127. or_conn->next_with_same_id = NULL;
  128. }
  129. });
  130. digestmap_free(orconn_identity_map, NULL);
  131. orconn_identity_map = NULL;
  132. }
  133. /** Change conn->identity_digest to digest, and add conn into
  134. * orconn_digest_map. */
  135. static void
  136. connection_or_set_identity_digest(or_connection_t *conn,
  137. const char *rsa_digest,
  138. const ed25519_public_key_t *ed_id)
  139. {
  140. (void) ed_id; // DOCDOC // XXXX not implemented yet.
  141. or_connection_t *tmp;
  142. tor_assert(conn);
  143. tor_assert(rsa_digest);
  144. if (!orconn_identity_map)
  145. orconn_identity_map = digestmap_new();
  146. if (tor_memeq(conn->identity_digest, rsa_digest, DIGEST_LEN))
  147. return;
  148. /* If the identity was set previously, remove the old mapping. */
  149. if (! tor_digest_is_zero(conn->identity_digest)) {
  150. connection_or_remove_from_identity_map(conn);
  151. if (conn->chan)
  152. channel_clear_identity_digest(TLS_CHAN_TO_BASE(conn->chan));
  153. }
  154. memcpy(conn->identity_digest, rsa_digest, DIGEST_LEN);
  155. /* If we're setting the ID to zero, don't add a mapping. */
  156. if (tor_digest_is_zero(rsa_digest))
  157. return;
  158. tmp = digestmap_set(orconn_identity_map, rsa_digest, conn);
  159. conn->next_with_same_id = tmp;
  160. /* Deal with channels */
  161. if (conn->chan)
  162. channel_set_identity_digest(TLS_CHAN_TO_BASE(conn->chan), rsa_digest);
  163. #if 1
  164. /* Testing code to check for bugs in representation. */
  165. for (; tmp; tmp = tmp->next_with_same_id) {
  166. tor_assert(tor_memeq(tmp->identity_digest, rsa_digest, DIGEST_LEN));
  167. tor_assert(tmp != conn);
  168. }
  169. #endif
  170. }
  171. /** Remove the Extended ORPort identifier of <b>conn</b> from the
  172. * global identifier list. Also, clear the identifier from the
  173. * connection itself. */
  174. void
  175. connection_or_remove_from_ext_or_id_map(or_connection_t *conn)
  176. {
  177. or_connection_t *tmp;
  178. if (!orconn_ext_or_id_map)
  179. return;
  180. if (!conn->ext_or_conn_id)
  181. return;
  182. tmp = digestmap_remove(orconn_ext_or_id_map, conn->ext_or_conn_id);
  183. if (!tor_digest_is_zero(conn->ext_or_conn_id))
  184. tor_assert(tmp == conn);
  185. memset(conn->ext_or_conn_id, 0, EXT_OR_CONN_ID_LEN);
  186. }
  187. /** Return the connection whose ext_or_id is <b>id</b>. Return NULL if no such
  188. * connection is found. */
  189. or_connection_t *
  190. connection_or_get_by_ext_or_id(const char *id)
  191. {
  192. if (!orconn_ext_or_id_map)
  193. return NULL;
  194. return digestmap_get(orconn_ext_or_id_map, id);
  195. }
  196. /** Deallocate the global Extended ORPort identifier list */
  197. void
  198. connection_or_clear_ext_or_id_map(void)
  199. {
  200. digestmap_free(orconn_ext_or_id_map, NULL);
  201. orconn_ext_or_id_map = NULL;
  202. }
  203. /** Creates an Extended ORPort identifier for <b>conn</b> and deposits
  204. * it into the global list of identifiers. */
  205. void
  206. connection_or_set_ext_or_identifier(or_connection_t *conn)
  207. {
  208. char random_id[EXT_OR_CONN_ID_LEN];
  209. or_connection_t *tmp;
  210. if (!orconn_ext_or_id_map)
  211. orconn_ext_or_id_map = digestmap_new();
  212. /* Remove any previous identifiers: */
  213. if (conn->ext_or_conn_id && !tor_digest_is_zero(conn->ext_or_conn_id))
  214. connection_or_remove_from_ext_or_id_map(conn);
  215. do {
  216. crypto_rand(random_id, sizeof(random_id));
  217. } while (digestmap_get(orconn_ext_or_id_map, random_id));
  218. if (!conn->ext_or_conn_id)
  219. conn->ext_or_conn_id = tor_malloc_zero(EXT_OR_CONN_ID_LEN);
  220. memcpy(conn->ext_or_conn_id, random_id, EXT_OR_CONN_ID_LEN);
  221. tmp = digestmap_set(orconn_ext_or_id_map, random_id, conn);
  222. tor_assert(!tmp);
  223. }
  224. /**************************************************************/
  225. /** Map from a string describing what a non-open OR connection was doing when
  226. * failed, to an intptr_t describing the count of connections that failed that
  227. * way. Note that the count is stored _as_ the pointer.
  228. */
  229. static strmap_t *broken_connection_counts;
  230. /** If true, do not record information in <b>broken_connection_counts</b>. */
  231. static int disable_broken_connection_counts = 0;
  232. /** Record that an OR connection failed in <b>state</b>. */
  233. static void
  234. note_broken_connection(const char *state)
  235. {
  236. void *ptr;
  237. intptr_t val;
  238. if (disable_broken_connection_counts)
  239. return;
  240. if (!broken_connection_counts)
  241. broken_connection_counts = strmap_new();
  242. ptr = strmap_get(broken_connection_counts, state);
  243. val = (intptr_t)ptr;
  244. val++;
  245. ptr = (void*)val;
  246. strmap_set(broken_connection_counts, state, ptr);
  247. }
  248. /** Forget all recorded states for failed connections. If
  249. * <b>stop_recording</b> is true, don't record any more. */
  250. void
  251. clear_broken_connection_map(int stop_recording)
  252. {
  253. if (broken_connection_counts)
  254. strmap_free(broken_connection_counts, NULL);
  255. broken_connection_counts = NULL;
  256. if (stop_recording)
  257. disable_broken_connection_counts = 1;
  258. }
  259. /** Write a detailed description the state of <b>orconn</b> into the
  260. * <b>buflen</b>-byte buffer at <b>buf</b>. This description includes not
  261. * only the OR-conn level state but also the TLS state. It's useful for
  262. * diagnosing broken handshakes. */
  263. static void
  264. connection_or_get_state_description(or_connection_t *orconn,
  265. char *buf, size_t buflen)
  266. {
  267. connection_t *conn = TO_CONN(orconn);
  268. const char *conn_state;
  269. char tls_state[256];
  270. tor_assert(conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR);
  271. conn_state = conn_state_to_string(conn->type, conn->state);
  272. tor_tls_get_state_description(orconn->tls, tls_state, sizeof(tls_state));
  273. tor_snprintf(buf, buflen, "%s with SSL state %s", conn_state, tls_state);
  274. }
  275. /** Record the current state of <b>orconn</b> as the state of a broken
  276. * connection. */
  277. static void
  278. connection_or_note_state_when_broken(or_connection_t *orconn)
  279. {
  280. char buf[256];
  281. if (disable_broken_connection_counts)
  282. return;
  283. connection_or_get_state_description(orconn, buf, sizeof(buf));
  284. log_info(LD_HANDSHAKE,"Connection died in state '%s'", buf);
  285. note_broken_connection(buf);
  286. }
  287. /** Helper type used to sort connection states and find the most frequent. */
  288. typedef struct broken_state_count_t {
  289. intptr_t count;
  290. const char *state;
  291. } broken_state_count_t;
  292. /** Helper function used to sort broken_state_count_t by frequency. */
  293. static int
  294. broken_state_count_compare(const void **a_ptr, const void **b_ptr)
  295. {
  296. const broken_state_count_t *a = *a_ptr, *b = *b_ptr;
  297. if (b->count < a->count)
  298. return -1;
  299. else if (b->count == a->count)
  300. return 0;
  301. else
  302. return 1;
  303. }
  304. /** Upper limit on the number of different states to report for connection
  305. * failure. */
  306. #define MAX_REASONS_TO_REPORT 10
  307. /** Report a list of the top states for failed OR connections at log level
  308. * <b>severity</b>, in log domain <b>domain</b>. */
  309. void
  310. connection_or_report_broken_states(int severity, int domain)
  311. {
  312. int total = 0;
  313. smartlist_t *items;
  314. if (!broken_connection_counts || disable_broken_connection_counts)
  315. return;
  316. items = smartlist_new();
  317. STRMAP_FOREACH(broken_connection_counts, state, void *, countptr) {
  318. broken_state_count_t *c = tor_malloc(sizeof(broken_state_count_t));
  319. c->count = (intptr_t)countptr;
  320. total += (int)c->count;
  321. c->state = state;
  322. smartlist_add(items, c);
  323. } STRMAP_FOREACH_END;
  324. smartlist_sort(items, broken_state_count_compare);
  325. tor_log(severity, domain, "%d connections have failed%s", total,
  326. smartlist_len(items) > MAX_REASONS_TO_REPORT ? ". Top reasons:" : ":");
  327. SMARTLIST_FOREACH_BEGIN(items, const broken_state_count_t *, c) {
  328. if (c_sl_idx > MAX_REASONS_TO_REPORT)
  329. break;
  330. tor_log(severity, domain,
  331. " %d connections died in state %s", (int)c->count, c->state);
  332. } SMARTLIST_FOREACH_END(c);
  333. SMARTLIST_FOREACH(items, broken_state_count_t *, c, tor_free(c));
  334. smartlist_free(items);
  335. }
  336. /** Call this to change or_connection_t states, so the owning channel_tls_t can
  337. * be notified.
  338. */
  339. static void
  340. connection_or_change_state(or_connection_t *conn, uint8_t state)
  341. {
  342. uint8_t old_state;
  343. tor_assert(conn);
  344. old_state = conn->base_.state;
  345. conn->base_.state = state;
  346. if (conn->chan)
  347. channel_tls_handle_state_change_on_orconn(conn->chan, conn,
  348. old_state, state);
  349. }
  350. /** Return the number of circuits using an or_connection_t; this used to
  351. * be an or_connection_t field, but it got moved to channel_t and we
  352. * shouldn't maintain two copies. */
  353. MOCK_IMPL(int,
  354. connection_or_get_num_circuits, (or_connection_t *conn))
  355. {
  356. tor_assert(conn);
  357. if (conn->chan) {
  358. return channel_num_circuits(TLS_CHAN_TO_BASE(conn->chan));
  359. } else return 0;
  360. }
  361. /**************************************************************/
  362. /** Pack the cell_t host-order structure <b>src</b> into network-order
  363. * in the buffer <b>dest</b>. See tor-spec.txt for details about the
  364. * wire format.
  365. *
  366. * Note that this function doesn't touch <b>dst</b>-\>next: the caller
  367. * should set it or clear it as appropriate.
  368. */
  369. void
  370. cell_pack(packed_cell_t *dst, const cell_t *src, int wide_circ_ids)
  371. {
  372. char *dest = dst->body;
  373. if (wide_circ_ids) {
  374. set_uint32(dest, htonl(src->circ_id));
  375. dest += 4;
  376. } else {
  377. set_uint16(dest, htons(src->circ_id));
  378. dest += 2;
  379. memset(dest+CELL_MAX_NETWORK_SIZE-2, 0, 2); /*make sure it's clear */
  380. }
  381. set_uint8(dest, src->command);
  382. memcpy(dest+1, src->payload, CELL_PAYLOAD_SIZE);
  383. }
  384. /** Unpack the network-order buffer <b>src</b> into a host-order
  385. * cell_t structure <b>dest</b>.
  386. */
  387. static void
  388. cell_unpack(cell_t *dest, const char *src, int wide_circ_ids)
  389. {
  390. if (wide_circ_ids) {
  391. dest->circ_id = ntohl(get_uint32(src));
  392. src += 4;
  393. } else {
  394. dest->circ_id = ntohs(get_uint16(src));
  395. src += 2;
  396. }
  397. dest->command = get_uint8(src);
  398. memcpy(dest->payload, src+1, CELL_PAYLOAD_SIZE);
  399. }
  400. /** Write the header of <b>cell</b> into the first VAR_CELL_MAX_HEADER_SIZE
  401. * bytes of <b>hdr_out</b>. Returns number of bytes used. */
  402. int
  403. var_cell_pack_header(const var_cell_t *cell, char *hdr_out, int wide_circ_ids)
  404. {
  405. int r;
  406. if (wide_circ_ids) {
  407. set_uint32(hdr_out, htonl(cell->circ_id));
  408. hdr_out += 4;
  409. r = VAR_CELL_MAX_HEADER_SIZE;
  410. } else {
  411. set_uint16(hdr_out, htons(cell->circ_id));
  412. hdr_out += 2;
  413. r = VAR_CELL_MAX_HEADER_SIZE - 2;
  414. }
  415. set_uint8(hdr_out, cell->command);
  416. set_uint16(hdr_out+1, htons(cell->payload_len));
  417. return r;
  418. }
  419. /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
  420. * payload space. */
  421. var_cell_t *
  422. var_cell_new(uint16_t payload_len)
  423. {
  424. size_t size = STRUCT_OFFSET(var_cell_t, payload) + payload_len;
  425. var_cell_t *cell = tor_malloc_zero(size);
  426. cell->payload_len = payload_len;
  427. cell->command = 0;
  428. cell->circ_id = 0;
  429. return cell;
  430. }
  431. /**
  432. * Copy a var_cell_t
  433. */
  434. var_cell_t *
  435. var_cell_copy(const var_cell_t *src)
  436. {
  437. var_cell_t *copy = NULL;
  438. size_t size = 0;
  439. if (src != NULL) {
  440. size = STRUCT_OFFSET(var_cell_t, payload) + src->payload_len;
  441. copy = tor_malloc_zero(size);
  442. copy->payload_len = src->payload_len;
  443. copy->command = src->command;
  444. copy->circ_id = src->circ_id;
  445. memcpy(copy->payload, src->payload, copy->payload_len);
  446. }
  447. return copy;
  448. }
  449. /** Release all space held by <b>cell</b>. */
  450. void
  451. var_cell_free(var_cell_t *cell)
  452. {
  453. tor_free(cell);
  454. }
  455. /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
  456. int
  457. connection_or_reached_eof(or_connection_t *conn)
  458. {
  459. tor_assert(conn);
  460. log_info(LD_OR,"OR connection reached EOF. Closing.");
  461. connection_or_close_normally(conn, 1);
  462. return 0;
  463. }
  464. /** Handle any new bytes that have come in on connection <b>conn</b>.
  465. * If conn is in 'open' state, hand it to
  466. * connection_or_process_cells_from_inbuf()
  467. * (else do nothing).
  468. */
  469. int
  470. connection_or_process_inbuf(or_connection_t *conn)
  471. {
  472. /** Don't let the inbuf of a nonopen OR connection grow beyond this many
  473. * bytes: it's either a broken client, a non-Tor client, or a DOS
  474. * attempt. */
  475. #define MAX_OR_INBUF_WHEN_NONOPEN 0
  476. int ret = 0;
  477. tor_assert(conn);
  478. switch (conn->base_.state) {
  479. case OR_CONN_STATE_PROXY_HANDSHAKING:
  480. ret = connection_read_proxy_handshake(TO_CONN(conn));
  481. /* start TLS after handshake completion, or deal with error */
  482. if (ret == 1) {
  483. tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
  484. if (connection_tls_start_handshake(conn, 0) < 0)
  485. ret = -1;
  486. /* Touch the channel's active timestamp if there is one */
  487. if (conn->chan)
  488. channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
  489. }
  490. if (ret < 0) {
  491. connection_or_close_for_error(conn, 0);
  492. }
  493. return ret;
  494. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  495. case OR_CONN_STATE_OPEN:
  496. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  497. case OR_CONN_STATE_OR_HANDSHAKING_V3:
  498. return connection_or_process_cells_from_inbuf(conn);
  499. default:
  500. break; /* don't do anything */
  501. }
  502. /* This check was necessary with 0.2.2, when the TLS_SERVER_RENEGOTIATING
  503. * check would otherwise just let data accumulate. It serves no purpose
  504. * in 0.2.3.
  505. *
  506. * XXXX Remove this check once we verify that the above paragraph is
  507. * 100% true. */
  508. if (buf_datalen(conn->base_.inbuf) > MAX_OR_INBUF_WHEN_NONOPEN) {
  509. log_fn(LOG_PROTOCOL_WARN, LD_NET, "Accumulated too much data (%d bytes) "
  510. "on nonopen OR connection %s %s:%u in state %s; closing.",
  511. (int)buf_datalen(conn->base_.inbuf),
  512. connection_or_nonopen_was_started_here(conn) ? "to" : "from",
  513. conn->base_.address, conn->base_.port,
  514. conn_state_to_string(conn->base_.type, conn->base_.state));
  515. connection_or_close_for_error(conn, 0);
  516. ret = -1;
  517. }
  518. return ret;
  519. }
  520. /** Called whenever we have flushed some data on an or_conn: add more data
  521. * from active circuits. */
  522. int
  523. connection_or_flushed_some(or_connection_t *conn)
  524. {
  525. size_t datalen;
  526. /* The channel will want to update its estimated queue size */
  527. channel_update_xmit_queue_size(TLS_CHAN_TO_BASE(conn->chan));
  528. /* If we're under the low water mark, add cells until we're just over the
  529. * high water mark. */
  530. datalen = connection_get_outbuf_len(TO_CONN(conn));
  531. if (datalen < OR_CONN_LOWWATER) {
  532. /* Let the scheduler know */
  533. scheduler_channel_wants_writes(TLS_CHAN_TO_BASE(conn->chan));
  534. }
  535. return 0;
  536. }
  537. /** This is for channeltls.c to ask how many cells we could accept if
  538. * they were available. */
  539. ssize_t
  540. connection_or_num_cells_writeable(or_connection_t *conn)
  541. {
  542. size_t datalen, cell_network_size;
  543. ssize_t n = 0;
  544. tor_assert(conn);
  545. /*
  546. * If we're under the high water mark, we're potentially
  547. * writeable; note this is different from the calculation above
  548. * used to trigger when to start writing after we've stopped.
  549. */
  550. datalen = connection_get_outbuf_len(TO_CONN(conn));
  551. if (datalen < OR_CONN_HIGHWATER) {
  552. cell_network_size = get_cell_network_size(conn->wide_circ_ids);
  553. n = CEIL_DIV(OR_CONN_HIGHWATER - datalen, cell_network_size);
  554. }
  555. return n;
  556. }
  557. /** Connection <b>conn</b> has finished writing and has no bytes left on
  558. * its outbuf.
  559. *
  560. * Otherwise it's in state "open": stop writing and return.
  561. *
  562. * If <b>conn</b> is broken, mark it for close and return -1, else
  563. * return 0.
  564. */
  565. int
  566. connection_or_finished_flushing(or_connection_t *conn)
  567. {
  568. tor_assert(conn);
  569. assert_connection_ok(TO_CONN(conn),0);
  570. switch (conn->base_.state) {
  571. case OR_CONN_STATE_PROXY_HANDSHAKING:
  572. case OR_CONN_STATE_OPEN:
  573. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  574. case OR_CONN_STATE_OR_HANDSHAKING_V3:
  575. break;
  576. default:
  577. log_err(LD_BUG,"Called in unexpected state %d.", conn->base_.state);
  578. tor_fragile_assert();
  579. return -1;
  580. }
  581. return 0;
  582. }
  583. /** Connected handler for OR connections: begin the TLS handshake.
  584. */
  585. int
  586. connection_or_finished_connecting(or_connection_t *or_conn)
  587. {
  588. const int proxy_type = or_conn->proxy_type;
  589. connection_t *conn;
  590. tor_assert(or_conn);
  591. conn = TO_CONN(or_conn);
  592. tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
  593. log_debug(LD_HANDSHAKE,"OR connect() to router at %s:%u finished.",
  594. conn->address,conn->port);
  595. control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE, 0);
  596. if (proxy_type != PROXY_NONE) {
  597. /* start proxy handshake */
  598. if (connection_proxy_connect(conn, proxy_type) < 0) {
  599. connection_or_close_for_error(or_conn, 0);
  600. return -1;
  601. }
  602. connection_start_reading(conn);
  603. connection_or_change_state(or_conn, OR_CONN_STATE_PROXY_HANDSHAKING);
  604. return 0;
  605. }
  606. if (connection_tls_start_handshake(or_conn, 0) < 0) {
  607. /* TLS handshaking error of some kind. */
  608. connection_or_close_for_error(or_conn, 0);
  609. return -1;
  610. }
  611. return 0;
  612. }
  613. /** Called when we're about to finally unlink and free an OR connection:
  614. * perform necessary accounting and cleanup */
  615. void
  616. connection_or_about_to_close(or_connection_t *or_conn)
  617. {
  618. time_t now = time(NULL);
  619. connection_t *conn = TO_CONN(or_conn);
  620. /* Tell the controlling channel we're closed */
  621. if (or_conn->chan) {
  622. channel_closed(TLS_CHAN_TO_BASE(or_conn->chan));
  623. /*
  624. * NULL this out because the channel might hang around a little
  625. * longer before channel_run_cleanup() gets it.
  626. */
  627. or_conn->chan->conn = NULL;
  628. or_conn->chan = NULL;
  629. }
  630. /* Remember why we're closing this connection. */
  631. if (conn->state != OR_CONN_STATE_OPEN) {
  632. /* now mark things down as needed */
  633. if (connection_or_nonopen_was_started_here(or_conn)) {
  634. const or_options_t *options = get_options();
  635. connection_or_note_state_when_broken(or_conn);
  636. rep_hist_note_connect_failed(or_conn->identity_digest, now);
  637. /* Tell the new guard API about the channel failure */
  638. entry_guard_chan_failed(TLS_CHAN_TO_BASE(or_conn->chan));
  639. #ifdef ENABLE_LEGACY_GUARD_ALGORITHM
  640. /* Tell the old guard API about the channel failure */
  641. entry_guard_register_connect_status(or_conn->identity_digest,0,
  642. !options->HTTPSProxy, now);
  643. #endif
  644. if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
  645. int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
  646. control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
  647. reason);
  648. if (!authdir_mode_tests_reachability(options))
  649. control_event_bootstrap_problem(
  650. orconn_end_reason_to_control_string(reason),
  651. reason, or_conn);
  652. }
  653. }
  654. } else if (conn->hold_open_until_flushed) {
  655. /* We only set hold_open_until_flushed when we're intentionally
  656. * closing a connection. */
  657. rep_hist_note_disconnect(or_conn->identity_digest, now);
  658. control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
  659. tls_error_to_orconn_end_reason(or_conn->tls_error));
  660. } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
  661. rep_hist_note_connection_died(or_conn->identity_digest, now);
  662. control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
  663. tls_error_to_orconn_end_reason(or_conn->tls_error));
  664. }
  665. }
  666. /** Return 1 if identity digest <b>id_digest</b> is known to be a
  667. * currently or recently running relay. Otherwise return 0. */
  668. int
  669. connection_or_digest_is_known_relay(const char *id_digest)
  670. {
  671. if (router_get_consensus_status_by_id(id_digest))
  672. return 1; /* It's in the consensus: "yes" */
  673. if (router_get_by_id_digest(id_digest))
  674. return 1; /* Not in the consensus, but we have a descriptor for
  675. * it. Probably it was in a recent consensus. "Yes". */
  676. return 0;
  677. }
  678. /** Set the per-conn read and write limits for <b>conn</b>. If it's a known
  679. * relay, we will rely on the global read and write buckets, so give it
  680. * per-conn limits that are big enough they'll never matter. But if it's
  681. * not a known relay, first check if we set PerConnBwRate/Burst, then
  682. * check if the consensus sets them, else default to 'big enough'.
  683. *
  684. * If <b>reset</b> is true, set the bucket to be full. Otherwise, just
  685. * clip the bucket if it happens to be <em>too</em> full.
  686. */
  687. static void
  688. connection_or_update_token_buckets_helper(or_connection_t *conn, int reset,
  689. const or_options_t *options)
  690. {
  691. int rate, burst; /* per-connection rate limiting params */
  692. if (connection_or_digest_is_known_relay(conn->identity_digest)) {
  693. /* It's in the consensus, or we have a descriptor for it meaning it
  694. * was probably in a recent consensus. It's a recognized relay:
  695. * give it full bandwidth. */
  696. rate = (int)options->BandwidthRate;
  697. burst = (int)options->BandwidthBurst;
  698. } else {
  699. /* Not a recognized relay. Squeeze it down based on the suggested
  700. * bandwidth parameters in the consensus, but allow local config
  701. * options to override. */
  702. rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
  703. networkstatus_get_param(NULL, "perconnbwrate",
  704. (int)options->BandwidthRate, 1, INT32_MAX);
  705. burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
  706. networkstatus_get_param(NULL, "perconnbwburst",
  707. (int)options->BandwidthBurst, 1, INT32_MAX);
  708. }
  709. conn->bandwidthrate = rate;
  710. conn->bandwidthburst = burst;
  711. if (reset) { /* set up the token buckets to be full */
  712. conn->read_bucket = conn->write_bucket = burst;
  713. return;
  714. }
  715. /* If the new token bucket is smaller, take out the extra tokens.
  716. * (If it's larger, don't -- the buckets can grow to reach the cap.) */
  717. if (conn->read_bucket > burst)
  718. conn->read_bucket = burst;
  719. if (conn->write_bucket > burst)
  720. conn->write_bucket = burst;
  721. }
  722. /** Either our set of relays or our per-conn rate limits have changed.
  723. * Go through all the OR connections and update their token buckets to make
  724. * sure they don't exceed their maximum values. */
  725. void
  726. connection_or_update_token_buckets(smartlist_t *conns,
  727. const or_options_t *options)
  728. {
  729. SMARTLIST_FOREACH(conns, connection_t *, conn,
  730. {
  731. if (connection_speaks_cells(conn))
  732. connection_or_update_token_buckets_helper(TO_OR_CONN(conn), 0, options);
  733. });
  734. }
  735. /** How long do we wait before killing non-canonical OR connections with no
  736. * circuits? In Tor versions up to 0.2.1.25 and 0.2.2.12-alpha, we waited 15
  737. * minutes before cancelling these connections, which caused fast relays to
  738. * accrue many many idle connections. Hopefully 3-4.5 minutes is low enough
  739. * that it kills most idle connections, without being so low that we cause
  740. * clients to bounce on and off.
  741. *
  742. * For canonical connections, the limit is higher, at 15-22.5 minutes.
  743. *
  744. * For each OR connection, we randomly add up to 50% extra to its idle_timeout
  745. * field, to avoid exposing when exactly the last circuit closed. Since we're
  746. * storing idle_timeout in a uint16_t, don't let these values get higher than
  747. * 12 hours or so without revising connection_or_set_canonical and/or expanding
  748. * idle_timeout.
  749. */
  750. #define IDLE_OR_CONN_TIMEOUT_NONCANONICAL 180
  751. #define IDLE_OR_CONN_TIMEOUT_CANONICAL 900
  752. /* Mark <b>or_conn</b> as canonical if <b>is_canonical</b> is set, and
  753. * non-canonical otherwise. Adjust idle_timeout accordingly.
  754. */
  755. void
  756. connection_or_set_canonical(or_connection_t *or_conn,
  757. int is_canonical)
  758. {
  759. const unsigned int timeout_base = is_canonical ?
  760. IDLE_OR_CONN_TIMEOUT_CANONICAL : IDLE_OR_CONN_TIMEOUT_NONCANONICAL;
  761. if (bool_eq(is_canonical, or_conn->is_canonical) &&
  762. or_conn->idle_timeout != 0) {
  763. /* Don't recalculate an existing idle_timeout unless the canonical
  764. * status changed. */
  765. return;
  766. }
  767. or_conn->is_canonical = !! is_canonical; /* force to a 1-bit boolean */
  768. or_conn->idle_timeout = timeout_base + crypto_rand_int(timeout_base / 2);
  769. }
  770. /** If we don't necessarily know the router we're connecting to, but we
  771. * have an addr/port/id_digest, then fill in as much as we can. Start
  772. * by checking to see if this describes a router we know.
  773. * <b>started_here</b> is 1 if we are the initiator of <b>conn</b> and
  774. * 0 if it's an incoming connection. */
  775. void
  776. connection_or_init_conn_from_address(or_connection_t *conn,
  777. const tor_addr_t *addr, uint16_t port,
  778. const char *id_digest,
  779. const ed25519_public_key_t *ed_id,
  780. int started_here)
  781. {
  782. (void) ed_id; // not fully used yet.
  783. const node_t *r = node_get_by_id(id_digest);
  784. connection_or_set_identity_digest(conn, id_digest, ed_id);
  785. connection_or_update_token_buckets_helper(conn, 1, get_options());
  786. conn->base_.port = port;
  787. tor_addr_copy(&conn->base_.addr, addr);
  788. tor_addr_copy(&conn->real_addr, addr);
  789. if (r) {
  790. tor_addr_port_t node_ap;
  791. node_get_pref_orport(r, &node_ap);
  792. /* XXXX proposal 186 is making this more complex. For now, a conn
  793. is canonical when it uses the _preferred_ address. */
  794. if (tor_addr_eq(&conn->base_.addr, &node_ap.addr))
  795. connection_or_set_canonical(conn, 1);
  796. if (!started_here) {
  797. /* Override the addr/port, so our log messages will make sense.
  798. * This is dangerous, since if we ever try looking up a conn by
  799. * its actual addr/port, we won't remember. Careful! */
  800. /* XXXX arma: this is stupid, and it's the reason we need real_addr
  801. * to track is_canonical properly. What requires it? */
  802. /* XXXX <arma> i believe the reason we did this, originally, is because
  803. * we wanted to log what OR a connection was to, and if we logged the
  804. * right IP address and port 56244, that wouldn't be as helpful. now we
  805. * log the "right" port too, so we know if it's moria1 or moria2.
  806. */
  807. tor_addr_copy(&conn->base_.addr, &node_ap.addr);
  808. conn->base_.port = node_ap.port;
  809. }
  810. conn->nickname = tor_strdup(node_get_nickname(r));
  811. tor_free(conn->base_.address);
  812. conn->base_.address = tor_addr_to_str_dup(&node_ap.addr);
  813. } else {
  814. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  815. conn->nickname[0] = '$';
  816. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  817. conn->identity_digest, DIGEST_LEN);
  818. tor_free(conn->base_.address);
  819. conn->base_.address = tor_addr_to_str_dup(addr);
  820. }
  821. /*
  822. * We have to tell channeltls.c to update the channel marks (local, in
  823. * particular), since we may have changed the address.
  824. */
  825. if (conn->chan) {
  826. channel_tls_update_marks(conn);
  827. }
  828. }
  829. /** These just pass all the is_bad_for_new_circs manipulation on to
  830. * channel_t */
  831. static unsigned int
  832. connection_or_is_bad_for_new_circs(or_connection_t *or_conn)
  833. {
  834. tor_assert(or_conn);
  835. if (or_conn->chan)
  836. return channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
  837. else return 0;
  838. }
  839. static void
  840. connection_or_mark_bad_for_new_circs(or_connection_t *or_conn)
  841. {
  842. tor_assert(or_conn);
  843. if (or_conn->chan)
  844. channel_mark_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
  845. }
  846. /** How old do we let a connection to an OR get before deciding it's
  847. * too old for new circuits? */
  848. #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
  849. /** Given the head of the linked list for all the or_connections with a given
  850. * identity, set elements of that list as is_bad_for_new_circs as
  851. * appropriate. Helper for connection_or_set_bad_connections().
  852. *
  853. * Specifically, we set the is_bad_for_new_circs flag on:
  854. * - all connections if <b>force</b> is true.
  855. * - all connections that are too old.
  856. * - all open non-canonical connections for which a canonical connection
  857. * exists to the same router.
  858. * - all open canonical connections for which a 'better' canonical
  859. * connection exists to the same router.
  860. * - all open non-canonical connections for which a 'better' non-canonical
  861. * connection exists to the same router at the same address.
  862. *
  863. * See channel_is_better() in channel.c for our idea of what makes one OR
  864. * connection better than another.
  865. */
  866. static void
  867. connection_or_group_set_badness(or_connection_t *head, int force)
  868. {
  869. or_connection_t *or_conn = NULL, *best = NULL;
  870. int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
  871. time_t now = time(NULL);
  872. /* Pass 1: expire everything that's old, and see what the status of
  873. * everything else is. */
  874. for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
  875. if (or_conn->base_.marked_for_close ||
  876. connection_or_is_bad_for_new_circs(or_conn))
  877. continue;
  878. if (force ||
  879. or_conn->base_.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
  880. < now) {
  881. log_info(LD_OR,
  882. "Marking OR conn to %s:%d as too old for new circuits "
  883. "(fd "TOR_SOCKET_T_FORMAT", %d secs old).",
  884. or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
  885. (int)(now - or_conn->base_.timestamp_created));
  886. connection_or_mark_bad_for_new_circs(or_conn);
  887. }
  888. if (connection_or_is_bad_for_new_circs(or_conn)) {
  889. ++n_old;
  890. } else if (or_conn->base_.state != OR_CONN_STATE_OPEN) {
  891. ++n_inprogress;
  892. } else if (or_conn->is_canonical) {
  893. ++n_canonical;
  894. } else {
  895. ++n_other;
  896. }
  897. }
  898. /* Pass 2: We know how about how good the best connection is.
  899. * expire everything that's worse, and find the very best if we can. */
  900. for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
  901. if (or_conn->base_.marked_for_close ||
  902. connection_or_is_bad_for_new_circs(or_conn))
  903. continue; /* This one doesn't need to be marked bad. */
  904. if (or_conn->base_.state != OR_CONN_STATE_OPEN)
  905. continue; /* Don't mark anything bad until we have seen what happens
  906. * when the connection finishes. */
  907. if (n_canonical && !or_conn->is_canonical) {
  908. /* We have at least one open canonical connection to this router,
  909. * and this one is open but not canonical. Mark it bad. */
  910. log_info(LD_OR,
  911. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  912. "(fd "TOR_SOCKET_T_FORMAT", %d secs old). It is not "
  913. "canonical, and we have another connection to that OR that is.",
  914. or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
  915. (int)(now - or_conn->base_.timestamp_created));
  916. connection_or_mark_bad_for_new_circs(or_conn);
  917. continue;
  918. }
  919. if (!best ||
  920. channel_is_better(now,
  921. TLS_CHAN_TO_BASE(or_conn->chan),
  922. TLS_CHAN_TO_BASE(best->chan),
  923. 0)) {
  924. best = or_conn;
  925. }
  926. }
  927. if (!best)
  928. return;
  929. /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
  930. * every other open connection. If it's non-canonical, mark as bad
  931. * every other open connection to the same address.
  932. *
  933. * XXXX This isn't optimal; if we have connections to an OR at multiple
  934. * addresses, we'd like to pick the best _for each address_, and mark as
  935. * bad every open connection that isn't best for its address. But this
  936. * can only occur in cases where the other OR is old (so we have no
  937. * canonical connection to it), or where all the connections to the OR are
  938. * at noncanonical addresses and we have no good direct connection (which
  939. * means we aren't at risk of attaching circuits to it anyway). As
  940. * 0.1.2.x dies out, the first case will go away, and the second one is
  941. * "mostly harmless", so a fix can wait until somebody is bored.
  942. */
  943. for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
  944. if (or_conn->base_.marked_for_close ||
  945. connection_or_is_bad_for_new_circs(or_conn) ||
  946. or_conn->base_.state != OR_CONN_STATE_OPEN)
  947. continue;
  948. if (or_conn != best &&
  949. channel_is_better(now,
  950. TLS_CHAN_TO_BASE(best->chan),
  951. TLS_CHAN_TO_BASE(or_conn->chan), 1)) {
  952. /* This isn't the best conn, _and_ the best conn is better than it,
  953. even when we're being forgiving. */
  954. if (best->is_canonical) {
  955. log_info(LD_OR,
  956. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  957. "(fd "TOR_SOCKET_T_FORMAT", %d secs old). "
  958. "We have a better canonical one "
  959. "(fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
  960. or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
  961. (int)(now - or_conn->base_.timestamp_created),
  962. best->base_.s, (int)(now - best->base_.timestamp_created));
  963. connection_or_mark_bad_for_new_circs(or_conn);
  964. } else if (!tor_addr_compare(&or_conn->real_addr,
  965. &best->real_addr, CMP_EXACT)) {
  966. log_info(LD_OR,
  967. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  968. "(fd "TOR_SOCKET_T_FORMAT", %d secs old). We have a better "
  969. "one with the "
  970. "same address (fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
  971. or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
  972. (int)(now - or_conn->base_.timestamp_created),
  973. best->base_.s, (int)(now - best->base_.timestamp_created));
  974. connection_or_mark_bad_for_new_circs(or_conn);
  975. }
  976. }
  977. }
  978. }
  979. /** Go through all the OR connections (or if <b>digest</b> is non-NULL, just
  980. * the OR connections with that digest), and set the is_bad_for_new_circs
  981. * flag based on the rules in connection_or_group_set_badness() (or just
  982. * always set it if <b>force</b> is true).
  983. */
  984. void
  985. connection_or_set_bad_connections(const char *digest, int force)
  986. {
  987. if (!orconn_identity_map)
  988. return;
  989. DIGESTMAP_FOREACH(orconn_identity_map, identity, or_connection_t *, conn) {
  990. if (!digest || tor_memeq(digest, conn->identity_digest, DIGEST_LEN))
  991. connection_or_group_set_badness(conn, force);
  992. } DIGESTMAP_FOREACH_END;
  993. }
  994. /** <b>conn</b> is in the 'connecting' state, and it failed to complete
  995. * a TCP connection. Send notifications appropriately.
  996. *
  997. * <b>reason</b> specifies the or_conn_end_reason for the failure;
  998. * <b>msg</b> specifies the strerror-style error message.
  999. */
  1000. void
  1001. connection_or_connect_failed(or_connection_t *conn,
  1002. int reason, const char *msg)
  1003. {
  1004. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
  1005. if (!authdir_mode_tests_reachability(get_options()))
  1006. control_event_bootstrap_problem(msg, reason, conn);
  1007. }
  1008. /** <b>conn</b> got an error in connection_handle_read_impl() or
  1009. * connection_handle_write_impl() and is going to die soon.
  1010. *
  1011. * <b>reason</b> specifies the or_conn_end_reason for the failure;
  1012. * <b>msg</b> specifies the strerror-style error message.
  1013. */
  1014. void
  1015. connection_or_notify_error(or_connection_t *conn,
  1016. int reason, const char *msg)
  1017. {
  1018. channel_t *chan;
  1019. tor_assert(conn);
  1020. /* If we're connecting, call connect_failed() too */
  1021. if (TO_CONN(conn)->state == OR_CONN_STATE_CONNECTING)
  1022. connection_or_connect_failed(conn, reason, msg);
  1023. /* Tell the controlling channel if we have one */
  1024. if (conn->chan) {
  1025. chan = TLS_CHAN_TO_BASE(conn->chan);
  1026. /* Don't transition if we're already in closing, closed or error */
  1027. if (!CHANNEL_CONDEMNED(chan)) {
  1028. channel_close_for_error(chan);
  1029. }
  1030. }
  1031. /* No need to mark for error because connection.c is about to do that */
  1032. }
  1033. /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
  1034. * handshake with an OR with identity digest <b>id_digest</b>. Optionally,
  1035. * pass in a pointer to a channel using this connection.
  1036. *
  1037. * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
  1038. * return that connection. If the connect() is in progress, set the
  1039. * new conn's state to 'connecting' and return it. If connect() succeeds,
  1040. * call connection_tls_start_handshake() on it.
  1041. *
  1042. * This function is called from router_retry_connections(), for
  1043. * ORs connecting to ORs, and circuit_establish_circuit(), for
  1044. * OPs connecting to ORs.
  1045. *
  1046. * Return the launched conn, or NULL if it failed.
  1047. */
  1048. MOCK_IMPL(or_connection_t *,
  1049. connection_or_connect, (const tor_addr_t *_addr, uint16_t port,
  1050. const char *id_digest,
  1051. const ed25519_public_key_t *ed_id,
  1052. channel_tls_t *chan))
  1053. {
  1054. (void) ed_id; // XXXX not fully used yet.
  1055. or_connection_t *conn;
  1056. const or_options_t *options = get_options();
  1057. int socket_error = 0;
  1058. tor_addr_t addr;
  1059. int r;
  1060. tor_addr_t proxy_addr;
  1061. uint16_t proxy_port;
  1062. int proxy_type;
  1063. tor_assert(_addr);
  1064. tor_assert(id_digest);
  1065. tor_addr_copy(&addr, _addr);
  1066. if (server_mode(options) && router_digest_is_me(id_digest)) {
  1067. log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
  1068. return NULL;
  1069. }
  1070. conn = or_connection_new(CONN_TYPE_OR, tor_addr_family(&addr));
  1071. /*
  1072. * Set up conn so it's got all the data we need to remember for channels
  1073. *
  1074. * This stuff needs to happen before connection_or_init_conn_from_address()
  1075. * so connection_or_set_identity_digest() and such know where to look to
  1076. * keep the channel up to date.
  1077. */
  1078. conn->chan = chan;
  1079. chan->conn = conn;
  1080. connection_or_init_conn_from_address(conn, &addr, port, id_digest, ed_id, 1);
  1081. connection_or_change_state(conn, OR_CONN_STATE_CONNECTING);
  1082. control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
  1083. conn->is_outgoing = 1;
  1084. /* If we are using a proxy server, find it and use it. */
  1085. r = get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, TO_CONN(conn));
  1086. if (r == 0) {
  1087. conn->proxy_type = proxy_type;
  1088. if (proxy_type != PROXY_NONE) {
  1089. tor_addr_copy(&addr, &proxy_addr);
  1090. port = proxy_port;
  1091. conn->base_.proxy_state = PROXY_INFANT;
  1092. }
  1093. } else {
  1094. /* get_proxy_addrport() might fail if we have a Bridge line that
  1095. references a transport, but no ClientTransportPlugin lines
  1096. defining its transport proxy. If this is the case, let's try to
  1097. output a useful log message to the user. */
  1098. const char *transport_name =
  1099. find_transport_name_by_bridge_addrport(&TO_CONN(conn)->addr,
  1100. TO_CONN(conn)->port);
  1101. if (transport_name) {
  1102. log_warn(LD_GENERAL, "We were supposed to connect to bridge '%s' "
  1103. "using pluggable transport '%s', but we can't find a pluggable "
  1104. "transport proxy supporting '%s'. This can happen if you "
  1105. "haven't provided a ClientTransportPlugin line, or if "
  1106. "your pluggable transport proxy stopped running.",
  1107. fmt_addrport(&TO_CONN(conn)->addr, TO_CONN(conn)->port),
  1108. transport_name, transport_name);
  1109. control_event_bootstrap_problem(
  1110. "Can't connect to bridge",
  1111. END_OR_CONN_REASON_PT_MISSING,
  1112. conn);
  1113. } else {
  1114. log_warn(LD_GENERAL, "Tried to connect to '%s' through a proxy, but "
  1115. "the proxy address could not be found.",
  1116. fmt_addrport(&TO_CONN(conn)->addr, TO_CONN(conn)->port));
  1117. }
  1118. connection_free(TO_CONN(conn));
  1119. return NULL;
  1120. }
  1121. switch (connection_connect(TO_CONN(conn), conn->base_.address,
  1122. &addr, port, &socket_error)) {
  1123. case -1:
  1124. /* We failed to establish a connection probably because of a local
  1125. * error. No need to blame the guard in this case. Notify the networking
  1126. * system of this failure. */
  1127. connection_or_connect_failed(conn,
  1128. errno_to_orconn_end_reason(socket_error),
  1129. tor_socket_strerror(socket_error));
  1130. connection_free(TO_CONN(conn));
  1131. return NULL;
  1132. case 0:
  1133. connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
  1134. /* writable indicates finish, readable indicates broken link,
  1135. error indicates broken link on windows */
  1136. return conn;
  1137. /* case 1: fall through */
  1138. }
  1139. if (connection_or_finished_connecting(conn) < 0) {
  1140. /* already marked for close */
  1141. return NULL;
  1142. }
  1143. return conn;
  1144. }
  1145. /** Mark orconn for close and transition the associated channel, if any, to
  1146. * the closing state.
  1147. *
  1148. * It's safe to call this and connection_or_close_for_error() any time, and
  1149. * channel layer will treat it as a connection closing for reasons outside
  1150. * its control, like the remote end closing it. It can also be a local
  1151. * reason that's specific to connection_t/or_connection_t rather than
  1152. * the channel mechanism, such as expiration of old connections in
  1153. * run_connection_housekeeping(). If you want to close a channel_t
  1154. * from somewhere that logically works in terms of generic channels
  1155. * rather than connections, use channel_mark_for_close(); see also
  1156. * the comment on that function in channel.c.
  1157. */
  1158. void
  1159. connection_or_close_normally(or_connection_t *orconn, int flush)
  1160. {
  1161. channel_t *chan = NULL;
  1162. tor_assert(orconn);
  1163. if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
  1164. else connection_mark_for_close_internal(TO_CONN(orconn));
  1165. if (orconn->chan) {
  1166. chan = TLS_CHAN_TO_BASE(orconn->chan);
  1167. /* Don't transition if we're already in closing, closed or error */
  1168. if (!CHANNEL_CONDEMNED(chan)) {
  1169. channel_close_from_lower_layer(chan);
  1170. }
  1171. }
  1172. }
  1173. /** Mark orconn for close and transition the associated channel, if any, to
  1174. * the error state.
  1175. */
  1176. MOCK_IMPL(void,
  1177. connection_or_close_for_error,(or_connection_t *orconn, int flush))
  1178. {
  1179. channel_t *chan = NULL;
  1180. tor_assert(orconn);
  1181. if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
  1182. else connection_mark_for_close_internal(TO_CONN(orconn));
  1183. if (orconn->chan) {
  1184. chan = TLS_CHAN_TO_BASE(orconn->chan);
  1185. /* Don't transition if we're already in closing, closed or error */
  1186. if (!CHANNEL_CONDEMNED(chan)) {
  1187. channel_close_for_error(chan);
  1188. }
  1189. }
  1190. }
  1191. /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
  1192. * we initiated the connection, else it's 1.
  1193. *
  1194. * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
  1195. * pass <b>conn</b> to connection_tls_continue_handshake().
  1196. *
  1197. * Return -1 if <b>conn</b> is broken, else return 0.
  1198. */
  1199. MOCK_IMPL(int,
  1200. connection_tls_start_handshake,(or_connection_t *conn, int receiving))
  1201. {
  1202. channel_listener_t *chan_listener;
  1203. channel_t *chan;
  1204. /* Incoming connections will need a new channel passed to the
  1205. * channel_tls_listener */
  1206. if (receiving) {
  1207. /* It shouldn't already be set */
  1208. tor_assert(!(conn->chan));
  1209. chan_listener = channel_tls_get_listener();
  1210. if (!chan_listener) {
  1211. chan_listener = channel_tls_start_listener();
  1212. command_setup_listener(chan_listener);
  1213. }
  1214. chan = channel_tls_handle_incoming(conn);
  1215. channel_listener_queue_incoming(chan_listener, chan);
  1216. }
  1217. connection_or_change_state(conn, OR_CONN_STATE_TLS_HANDSHAKING);
  1218. tor_assert(!conn->tls);
  1219. conn->tls = tor_tls_new(conn->base_.s, receiving);
  1220. if (!conn->tls) {
  1221. log_warn(LD_BUG,"tor_tls_new failed. Closing.");
  1222. return -1;
  1223. }
  1224. tor_tls_set_logged_address(conn->tls, // XXX client and relay?
  1225. escaped_safe_str(conn->base_.address));
  1226. connection_start_reading(TO_CONN(conn));
  1227. log_debug(LD_HANDSHAKE,"starting TLS handshake on fd "TOR_SOCKET_T_FORMAT,
  1228. conn->base_.s);
  1229. note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);
  1230. if (connection_tls_continue_handshake(conn) < 0)
  1231. return -1;
  1232. return 0;
  1233. }
  1234. /** Block all future attempts to renegotiate on 'conn' */
  1235. void
  1236. connection_or_block_renegotiation(or_connection_t *conn)
  1237. {
  1238. tor_tls_t *tls = conn->tls;
  1239. if (!tls)
  1240. return;
  1241. tor_tls_set_renegotiate_callback(tls, NULL, NULL);
  1242. tor_tls_block_renegotiation(tls);
  1243. }
  1244. /** Invoked on the server side from inside tor_tls_read() when the server
  1245. * gets a successful TLS renegotiation from the client. */
  1246. static void
  1247. connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
  1248. {
  1249. or_connection_t *conn = _conn;
  1250. (void)tls;
  1251. /* Don't invoke this again. */
  1252. connection_or_block_renegotiation(conn);
  1253. if (connection_tls_finish_handshake(conn) < 0) {
  1254. /* XXXX_TLS double-check that it's ok to do this from inside read. */
  1255. /* XXXX_TLS double-check that this verifies certificates. */
  1256. connection_or_close_for_error(conn, 0);
  1257. }
  1258. }
  1259. /** Move forward with the tls handshake. If it finishes, hand
  1260. * <b>conn</b> to connection_tls_finish_handshake().
  1261. *
  1262. * Return -1 if <b>conn</b> is broken, else return 0.
  1263. */
  1264. int
  1265. connection_tls_continue_handshake(or_connection_t *conn)
  1266. {
  1267. int result;
  1268. check_no_tls_errors();
  1269. tor_assert(conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING);
  1270. // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
  1271. result = tor_tls_handshake(conn->tls);
  1272. // log_notice(LD_OR, "Result: %d", result);
  1273. switch (result) {
  1274. CASE_TOR_TLS_ERROR_ANY:
  1275. log_info(LD_OR,"tls error [%s]. breaking connection.",
  1276. tor_tls_err_to_string(result));
  1277. return -1;
  1278. case TOR_TLS_DONE:
  1279. if (! tor_tls_used_v1_handshake(conn->tls)) {
  1280. if (!tor_tls_is_server(conn->tls)) {
  1281. tor_assert(conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING);
  1282. return connection_or_launch_v3_or_handshake(conn);
  1283. } else {
  1284. /* v2/v3 handshake, but we are not a client. */
  1285. log_debug(LD_OR, "Done with initial SSL handshake (server-side). "
  1286. "Expecting renegotiation or VERSIONS cell");
  1287. tor_tls_set_renegotiate_callback(conn->tls,
  1288. connection_or_tls_renegotiated_cb,
  1289. conn);
  1290. connection_or_change_state(conn,
  1291. OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
  1292. connection_stop_writing(TO_CONN(conn));
  1293. connection_start_reading(TO_CONN(conn));
  1294. return 0;
  1295. }
  1296. }
  1297. tor_assert(tor_tls_is_server(conn->tls));
  1298. return connection_tls_finish_handshake(conn);
  1299. case TOR_TLS_WANTWRITE:
  1300. connection_start_writing(TO_CONN(conn));
  1301. log_debug(LD_OR,"wanted write");
  1302. return 0;
  1303. case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
  1304. log_debug(LD_OR,"wanted read");
  1305. return 0;
  1306. case TOR_TLS_CLOSE:
  1307. log_info(LD_OR,"tls closed. breaking connection.");
  1308. return -1;
  1309. }
  1310. return 0;
  1311. }
  1312. /** Return 1 if we initiated this connection, or 0 if it started
  1313. * out as an incoming connection.
  1314. */
  1315. int
  1316. connection_or_nonopen_was_started_here(or_connection_t *conn)
  1317. {
  1318. tor_assert(conn->base_.type == CONN_TYPE_OR ||
  1319. conn->base_.type == CONN_TYPE_EXT_OR);
  1320. if (!conn->tls)
  1321. return 1; /* it's still in proxy states or something */
  1322. if (conn->handshake_state)
  1323. return conn->handshake_state->started_here;
  1324. return !tor_tls_is_server(conn->tls);
  1325. }
  1326. /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
  1327. * return -1 if they are lying, broken, or otherwise something is wrong.
  1328. *
  1329. * If we initiated this connection (<b>started_here</b> is true), make sure
  1330. * the other side sent a correctly formed certificate. If I initiated the
  1331. * connection, make sure it's the right relay by checking the certificate.
  1332. *
  1333. * Otherwise (if we _didn't_ initiate this connection), it's okay for
  1334. * the certificate to be weird or absent.
  1335. *
  1336. * If we return 0, and the certificate is as expected, write a hash of the
  1337. * identity key into <b>digest_rcvd_out</b>, which must have DIGEST_LEN
  1338. * space in it.
  1339. * If the certificate is invalid or missing on an incoming connection,
  1340. * we return 0 and set <b>digest_rcvd_out</b> to DIGEST_LEN NUL bytes.
  1341. * (If we return -1, the contents of this buffer are undefined.)
  1342. *
  1343. * As side effects,
  1344. * 1) Set conn->circ_id_type according to tor-spec.txt.
  1345. * 2) If we're an authdirserver and we initiated the connection: drop all
  1346. * descriptors that claim to be on that IP/port but that aren't
  1347. * this relay; and note that this relay is reachable.
  1348. * 3) If this is a bridge and we didn't configure its identity
  1349. * fingerprint, remember the keyid we just learned.
  1350. */
  1351. static int
  1352. connection_or_check_valid_tls_handshake(or_connection_t *conn,
  1353. int started_here,
  1354. char *digest_rcvd_out)
  1355. {
  1356. crypto_pk_t *identity_rcvd=NULL;
  1357. const or_options_t *options = get_options();
  1358. int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
  1359. const char *safe_address =
  1360. started_here ? conn->base_.address :
  1361. safe_str_client(conn->base_.address);
  1362. const char *conn_type = started_here ? "outgoing" : "incoming";
  1363. int has_cert = 0;
  1364. check_no_tls_errors();
  1365. has_cert = tor_tls_peer_has_cert(conn->tls);
  1366. if (started_here && !has_cert) {
  1367. log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
  1368. "send a cert! Closing.",
  1369. safe_address, conn->base_.port);
  1370. return -1;
  1371. } else if (!has_cert) {
  1372. log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
  1373. "That's ok.");
  1374. }
  1375. check_no_tls_errors();
  1376. if (has_cert) {
  1377. int v = tor_tls_verify(started_here?severity:LOG_INFO,
  1378. conn->tls, &identity_rcvd);
  1379. if (started_here && v<0) {
  1380. log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
  1381. " has a cert but it's invalid. Closing.",
  1382. safe_address, conn->base_.port);
  1383. return -1;
  1384. } else if (v<0) {
  1385. log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
  1386. "chain; ignoring.");
  1387. } else {
  1388. log_debug(LD_HANDSHAKE,
  1389. "The certificate seems to be valid on %s connection "
  1390. "with %s:%d", conn_type, safe_address, conn->base_.port);
  1391. }
  1392. check_no_tls_errors();
  1393. }
  1394. if (identity_rcvd) {
  1395. crypto_pk_get_digest(identity_rcvd, digest_rcvd_out);
  1396. } else {
  1397. memset(digest_rcvd_out, 0, DIGEST_LEN);
  1398. }
  1399. tor_assert(conn->chan);
  1400. channel_set_circid_type(TLS_CHAN_TO_BASE(conn->chan), identity_rcvd, 1);
  1401. crypto_pk_free(identity_rcvd);
  1402. if (started_here)
  1403. return connection_or_client_learned_peer_id(conn,
  1404. (const uint8_t*)digest_rcvd_out,
  1405. NULL // Ed25519 ID
  1406. );
  1407. return 0;
  1408. }
  1409. /** Called when we (as a connection initiator) have definitively,
  1410. * authenticatedly, learned that ID of the Tor instance on the other
  1411. * side of <b>conn</b> is <b>peer_id</b>. For v1 and v2 handshakes,
  1412. * this is right after we get a certificate chain in a TLS handshake
  1413. * or renegotiation. For v3 handshakes, this is right after we get a
  1414. * certificate chain in a CERTS cell.
  1415. *
  1416. * If we did not know the ID before, record the one we got.
  1417. *
  1418. * If we wanted an ID, but we didn't get the one we expected, log a message
  1419. * and return -1.
  1420. * On relays:
  1421. * - log a protocol warning whenever the fingerprints don't match;
  1422. * On clients:
  1423. * - if a relay's fingerprint doesn't match, log a warning;
  1424. * - if we don't have updated relay fingerprints from a recent consensus, and
  1425. * a fallback directory mirror's hard-coded fingerprint has changed, log an
  1426. * info explaining that we will try another fallback.
  1427. *
  1428. * If we're testing reachability, remember what we learned.
  1429. *
  1430. * Return 0 on success, -1 on failure.
  1431. */
  1432. int
  1433. connection_or_client_learned_peer_id(or_connection_t *conn,
  1434. const uint8_t *rsa_peer_id,
  1435. const ed25519_public_key_t *ed_peer_id)
  1436. {
  1437. (void) ed_peer_id; // not used yet.
  1438. const or_options_t *options = get_options();
  1439. if (tor_digest_is_zero(conn->identity_digest)) {
  1440. connection_or_set_identity_digest(conn,
  1441. (const char*)rsa_peer_id, ed_peer_id);
  1442. tor_free(conn->nickname);
  1443. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  1444. conn->nickname[0] = '$';
  1445. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  1446. conn->identity_digest, DIGEST_LEN);
  1447. log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
  1448. "its key. Hoping for the best.",
  1449. conn->nickname, conn->base_.address, conn->base_.port);
  1450. /* if it's a bridge and we didn't know its identity fingerprint, now
  1451. * we do -- remember it for future attempts. */
  1452. learned_router_identity(&conn->base_.addr, conn->base_.port,
  1453. (const char*)rsa_peer_id /*, ed_peer_id XXXX */);
  1454. }
  1455. if (tor_memneq(rsa_peer_id, conn->identity_digest, DIGEST_LEN)) {
  1456. /* I was aiming for a particular digest. I didn't get it! */
  1457. char seen[HEX_DIGEST_LEN+1];
  1458. char expected[HEX_DIGEST_LEN+1];
  1459. base16_encode(seen, sizeof(seen), (const char*)rsa_peer_id, DIGEST_LEN);
  1460. base16_encode(expected, sizeof(expected), conn->identity_digest,
  1461. DIGEST_LEN);
  1462. const int using_hardcoded_fingerprints =
  1463. !networkstatus_get_reasonably_live_consensus(time(NULL),
  1464. usable_consensus_flavor());
  1465. const int is_fallback_fingerprint = router_digest_is_fallback_dir(
  1466. conn->identity_digest);
  1467. const int is_authority_fingerprint = router_digest_is_trusted_dir(
  1468. conn->identity_digest);
  1469. int severity;
  1470. const char *extra_log = "";
  1471. if (server_mode(options)) {
  1472. severity = LOG_PROTOCOL_WARN;
  1473. } else {
  1474. if (using_hardcoded_fingerprints) {
  1475. /* We need to do the checks in this order, because the list of
  1476. * fallbacks includes the list of authorities */
  1477. if (is_authority_fingerprint) {
  1478. severity = LOG_WARN;
  1479. } else if (is_fallback_fingerprint) {
  1480. /* we expect a small number of fallbacks to change from their
  1481. * hard-coded fingerprints over the life of a release */
  1482. severity = LOG_INFO;
  1483. extra_log = " Tor will try a different fallback.";
  1484. } else {
  1485. /* it's a bridge, it's either a misconfiguration, or unexpected */
  1486. severity = LOG_WARN;
  1487. }
  1488. } else {
  1489. /* a relay has changed its fingerprint from the one in the consensus */
  1490. severity = LOG_WARN;
  1491. }
  1492. }
  1493. log_fn(severity, LD_HANDSHAKE,
  1494. "Tried connecting to router at %s:%d, but identity key was not "
  1495. "as expected: wanted %s but got %s.%s",
  1496. conn->base_.address, conn->base_.port, expected, seen, extra_log);
  1497. /* Tell the new guard API about the channel failure */
  1498. entry_guard_chan_failed(TLS_CHAN_TO_BASE(conn->chan));
  1499. #ifdef ENABLE_LEGACY_GUARD_ALGORITHM
  1500. /* Tell the old guard API about the channel failure */
  1501. entry_guard_register_connect_status(conn->identity_digest, 0, 1,
  1502. time(NULL));
  1503. #endif
  1504. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
  1505. END_OR_CONN_REASON_OR_IDENTITY);
  1506. if (!authdir_mode_tests_reachability(options))
  1507. control_event_bootstrap_problem(
  1508. "Unexpected identity in router certificate",
  1509. END_OR_CONN_REASON_OR_IDENTITY,
  1510. conn);
  1511. return -1;
  1512. }
  1513. if (authdir_mode_tests_reachability(options)) {
  1514. dirserv_orconn_tls_done(&conn->base_.addr, conn->base_.port,
  1515. (const char*)rsa_peer_id /*, ed_id XXXX */);
  1516. }
  1517. return 0;
  1518. }
  1519. /** Return when a client used this, for connection.c, since client_used
  1520. * is now one of the timestamps of channel_t */
  1521. time_t
  1522. connection_or_client_used(or_connection_t *conn)
  1523. {
  1524. tor_assert(conn);
  1525. if (conn->chan) {
  1526. return channel_when_last_client(TLS_CHAN_TO_BASE(conn->chan));
  1527. } else return 0;
  1528. }
  1529. /** The v1/v2 TLS handshake is finished.
  1530. *
  1531. * Make sure we are happy with the person we just handshaked with.
  1532. *
  1533. * If they initiated the connection, make sure they're not already connected,
  1534. * then initialize conn from the information in router.
  1535. *
  1536. * If all is successful, call circuit_n_conn_done() to handle events
  1537. * that have been pending on the <tls handshake completion. Also set the
  1538. * directory to be dirty (only matters if I'm an authdirserver).
  1539. *
  1540. * If this is a v2 TLS handshake, send a versions cell.
  1541. */
  1542. static int
  1543. connection_tls_finish_handshake(or_connection_t *conn)
  1544. {
  1545. char digest_rcvd[DIGEST_LEN];
  1546. int started_here = connection_or_nonopen_was_started_here(conn);
  1547. tor_assert(!started_here);
  1548. log_debug(LD_HANDSHAKE,"%s tls handshake on %p with %s done, using "
  1549. "ciphersuite %s. verifying.",
  1550. started_here?"outgoing":"incoming",
  1551. conn,
  1552. safe_str_client(conn->base_.address),
  1553. tor_tls_get_ciphersuite_name(conn->tls));
  1554. if (connection_or_check_valid_tls_handshake(conn, started_here,
  1555. digest_rcvd) < 0)
  1556. return -1;
  1557. circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  1558. if (tor_tls_used_v1_handshake(conn->tls)) {
  1559. conn->link_proto = 1;
  1560. connection_or_init_conn_from_address(conn, &conn->base_.addr,
  1561. conn->base_.port, digest_rcvd,
  1562. NULL, 0);
  1563. tor_tls_block_renegotiation(conn->tls);
  1564. rep_hist_note_negotiated_link_proto(1, started_here);
  1565. return connection_or_set_state_open(conn);
  1566. } else {
  1567. connection_or_change_state(conn, OR_CONN_STATE_OR_HANDSHAKING_V2);
  1568. if (connection_init_or_handshake_state(conn, started_here) < 0)
  1569. return -1;
  1570. connection_or_init_conn_from_address(conn, &conn->base_.addr,
  1571. conn->base_.port, digest_rcvd,
  1572. NULL, 0);
  1573. return connection_or_send_versions(conn, 0);
  1574. }
  1575. }
  1576. /**
  1577. * Called as client when initial TLS handshake is done, and we notice
  1578. * that we got a v3-handshake signalling certificate from the server.
  1579. * Set up structures, do bookkeeping, and send the versions cell.
  1580. * Return 0 on success and -1 on failure.
  1581. */
  1582. static int
  1583. connection_or_launch_v3_or_handshake(or_connection_t *conn)
  1584. {
  1585. tor_assert(connection_or_nonopen_was_started_here(conn));
  1586. circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  1587. connection_or_change_state(conn, OR_CONN_STATE_OR_HANDSHAKING_V3);
  1588. if (connection_init_or_handshake_state(conn, 1) < 0)
  1589. return -1;
  1590. return connection_or_send_versions(conn, 1);
  1591. }
  1592. /** Allocate a new connection handshake state for the connection
  1593. * <b>conn</b>. Return 0 on success, -1 on failure. */
  1594. int
  1595. connection_init_or_handshake_state(or_connection_t *conn, int started_here)
  1596. {
  1597. or_handshake_state_t *s;
  1598. if (conn->handshake_state) {
  1599. log_warn(LD_BUG, "Duplicate call to connection_init_or_handshake_state!");
  1600. return 0;
  1601. }
  1602. s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
  1603. s->started_here = started_here ? 1 : 0;
  1604. s->digest_sent_data = 1;
  1605. s->digest_received_data = 1;
  1606. s->certs = or_handshake_certs_new();
  1607. s->certs->started_here = s->started_here;
  1608. return 0;
  1609. }
  1610. /** Free all storage held by <b>state</b>. */
  1611. void
  1612. or_handshake_state_free(or_handshake_state_t *state)
  1613. {
  1614. if (!state)
  1615. return;
  1616. crypto_digest_free(state->digest_sent);
  1617. crypto_digest_free(state->digest_received);
  1618. or_handshake_certs_free(state->certs);
  1619. memwipe(state, 0xBE, sizeof(or_handshake_state_t));
  1620. tor_free(state);
  1621. }
  1622. /**
  1623. * Remember that <b>cell</b> has been transmitted (if <b>incoming</b> is
  1624. * false) or received (if <b>incoming</b> is true) during a V3 handshake using
  1625. * <b>state</b>.
  1626. *
  1627. * (We don't record the cell, but we keep a digest of everything sent or
  1628. * received during the v3 handshake, and the client signs it in an
  1629. * authenticate cell.)
  1630. */
  1631. void
  1632. or_handshake_state_record_cell(or_connection_t *conn,
  1633. or_handshake_state_t *state,
  1634. const cell_t *cell,
  1635. int incoming)
  1636. {
  1637. size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
  1638. crypto_digest_t *d, **dptr;
  1639. packed_cell_t packed;
  1640. if (incoming) {
  1641. if (!state->digest_received_data)
  1642. return;
  1643. } else {
  1644. if (!state->digest_sent_data)
  1645. return;
  1646. }
  1647. if (!incoming) {
  1648. log_warn(LD_BUG, "We shouldn't be sending any non-variable-length cells "
  1649. "while making a handshake digest. But we think we are sending "
  1650. "one with type %d.", (int)cell->command);
  1651. }
  1652. dptr = incoming ? &state->digest_received : &state->digest_sent;
  1653. if (! *dptr)
  1654. *dptr = crypto_digest256_new(DIGEST_SHA256);
  1655. d = *dptr;
  1656. /* Re-packing like this is a little inefficient, but we don't have to do
  1657. this very often at all. */
  1658. cell_pack(&packed, cell, conn->wide_circ_ids);
  1659. crypto_digest_add_bytes(d, packed.body, cell_network_size);
  1660. memwipe(&packed, 0, sizeof(packed));
  1661. }
  1662. /** Remember that a variable-length <b>cell</b> has been transmitted (if
  1663. * <b>incoming</b> is false) or received (if <b>incoming</b> is true) during a
  1664. * V3 handshake using <b>state</b>.
  1665. *
  1666. * (We don't record the cell, but we keep a digest of everything sent or
  1667. * received during the v3 handshake, and the client signs it in an
  1668. * authenticate cell.)
  1669. */
  1670. void
  1671. or_handshake_state_record_var_cell(or_connection_t *conn,
  1672. or_handshake_state_t *state,
  1673. const var_cell_t *cell,
  1674. int incoming)
  1675. {
  1676. crypto_digest_t *d, **dptr;
  1677. int n;
  1678. char buf[VAR_CELL_MAX_HEADER_SIZE];
  1679. if (incoming) {
  1680. if (!state->digest_received_data)
  1681. return;
  1682. } else {
  1683. if (!state->digest_sent_data)
  1684. return;
  1685. }
  1686. dptr = incoming ? &state->digest_received : &state->digest_sent;
  1687. if (! *dptr)
  1688. *dptr = crypto_digest256_new(DIGEST_SHA256);
  1689. d = *dptr;
  1690. n = var_cell_pack_header(cell, buf, conn->wide_circ_ids);
  1691. crypto_digest_add_bytes(d, buf, n);
  1692. crypto_digest_add_bytes(d, (const char *)cell->payload, cell->payload_len);
  1693. memwipe(buf, 0, sizeof(buf));
  1694. }
  1695. /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
  1696. * as appropriate. Called when we are done with all TLS and OR handshaking.
  1697. */
  1698. int
  1699. connection_or_set_state_open(or_connection_t *conn)
  1700. {
  1701. connection_or_change_state(conn, OR_CONN_STATE_OPEN);
  1702. control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
  1703. or_handshake_state_free(conn->handshake_state);
  1704. conn->handshake_state = NULL;
  1705. connection_start_reading(TO_CONN(conn));
  1706. return 0;
  1707. }
  1708. /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
  1709. * For cells that use or affect a circuit, this should only be called by
  1710. * connection_or_flush_from_first_active_circuit().
  1711. */
  1712. void
  1713. connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
  1714. {
  1715. packed_cell_t networkcell;
  1716. size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
  1717. tor_assert(cell);
  1718. tor_assert(conn);
  1719. cell_pack(&networkcell, cell, conn->wide_circ_ids);
  1720. connection_write_to_buf(networkcell.body, cell_network_size, TO_CONN(conn));
  1721. /* Touch the channel's active timestamp if there is one */
  1722. if (conn->chan)
  1723. channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
  1724. if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
  1725. or_handshake_state_record_cell(conn, conn->handshake_state, cell, 0);
  1726. }
  1727. /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
  1728. * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
  1729. * affect a circuit.
  1730. */
  1731. MOCK_IMPL(void,
  1732. connection_or_write_var_cell_to_buf,(const var_cell_t *cell,
  1733. or_connection_t *conn))
  1734. {
  1735. int n;
  1736. char hdr[VAR_CELL_MAX_HEADER_SIZE];
  1737. tor_assert(cell);
  1738. tor_assert(conn);
  1739. n = var_cell_pack_header(cell, hdr, conn->wide_circ_ids);
  1740. connection_write_to_buf(hdr, n, TO_CONN(conn));
  1741. connection_write_to_buf((char*)cell->payload,
  1742. cell->payload_len, TO_CONN(conn));
  1743. if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
  1744. or_handshake_state_record_var_cell(conn, conn->handshake_state, cell, 0);
  1745. /* Touch the channel's active timestamp if there is one */
  1746. if (conn->chan)
  1747. channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
  1748. }
  1749. /** See whether there's a variable-length cell waiting on <b>or_conn</b>'s
  1750. * inbuf. Return values as for fetch_var_cell_from_buf(). */
  1751. static int
  1752. connection_fetch_var_cell_from_buf(or_connection_t *or_conn, var_cell_t **out)
  1753. {
  1754. connection_t *conn = TO_CONN(or_conn);
  1755. return fetch_var_cell_from_buf(conn->inbuf, out, or_conn->link_proto);
  1756. }
  1757. /** Process cells from <b>conn</b>'s inbuf.
  1758. *
  1759. * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
  1760. * and hand it to command_process_cell().
  1761. *
  1762. * Always return 0.
  1763. */
  1764. static int
  1765. connection_or_process_cells_from_inbuf(or_connection_t *conn)
  1766. {
  1767. var_cell_t *var_cell;
  1768. /*
  1769. * Note on memory management for incoming cells: below the channel layer,
  1770. * we shouldn't need to consider its internal queueing/copying logic. It
  1771. * is safe to pass cells to it on the stack or on the heap, but in the
  1772. * latter case we must be sure we free them later.
  1773. *
  1774. * The incoming cell queue code in channel.c will (in the common case)
  1775. * decide it can pass them to the upper layer immediately, in which case
  1776. * those functions may run directly on the cell pointers we pass here, or
  1777. * it may decide to queue them, in which case it will allocate its own
  1778. * buffer and copy the cell.
  1779. */
  1780. while (1) {
  1781. log_debug(LD_OR,
  1782. TOR_SOCKET_T_FORMAT": starting, inbuf_datalen %d "
  1783. "(%d pending in tls object).",
  1784. conn->base_.s,(int)connection_get_inbuf_len(TO_CONN(conn)),
  1785. tor_tls_get_pending_bytes(conn->tls));
  1786. if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
  1787. if (!var_cell)
  1788. return 0; /* not yet. */
  1789. /* Touch the channel's active timestamp if there is one */
  1790. if (conn->chan)
  1791. channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
  1792. circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  1793. channel_tls_handle_var_cell(var_cell, conn);
  1794. var_cell_free(var_cell);
  1795. } else {
  1796. const int wide_circ_ids = conn->wide_circ_ids;
  1797. size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
  1798. char buf[CELL_MAX_NETWORK_SIZE];
  1799. cell_t cell;
  1800. if (connection_get_inbuf_len(TO_CONN(conn))
  1801. < cell_network_size) /* whole response available? */
  1802. return 0; /* not yet */
  1803. /* Touch the channel's active timestamp if there is one */
  1804. if (conn->chan)
  1805. channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
  1806. circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  1807. connection_fetch_from_buf(buf, cell_network_size, TO_CONN(conn));
  1808. /* retrieve cell info from buf (create the host-order struct from the
  1809. * network-order string) */
  1810. cell_unpack(&cell, buf, wide_circ_ids);
  1811. channel_tls_handle_cell(&cell, conn);
  1812. }
  1813. }
  1814. }
  1815. /** Array of recognized link protocol versions. */
  1816. static const uint16_t or_protocol_versions[] = { 1, 2, 3, 4 };
  1817. /** Number of versions in <b>or_protocol_versions</b>. */
  1818. static const int n_or_protocol_versions =
  1819. (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
  1820. /** Return true iff <b>v</b> is a link protocol version that this Tor
  1821. * implementation believes it can support. */
  1822. int
  1823. is_or_protocol_version_known(uint16_t v)
  1824. {
  1825. int i;
  1826. for (i = 0; i < n_or_protocol_versions; ++i) {
  1827. if (or_protocol_versions[i] == v)
  1828. return 1;
  1829. }
  1830. return 0;
  1831. }
  1832. /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
  1833. * link protocol versions that this Tor can support.
  1834. *
  1835. * If <b>v3_plus</b>, this is part of a V3 protocol handshake, so only
  1836. * allow protocol version v3 or later. If not <b>v3_plus</b>, this is
  1837. * not part of a v3 protocol handshake, so don't allow protocol v3 or
  1838. * later.
  1839. **/
  1840. int
  1841. connection_or_send_versions(or_connection_t *conn, int v3_plus)
  1842. {
  1843. var_cell_t *cell;
  1844. int i;
  1845. int n_versions = 0;
  1846. const int min_version = v3_plus ? 3 : 0;
  1847. const int max_version = v3_plus ? UINT16_MAX : 2;
  1848. tor_assert(conn->handshake_state &&
  1849. !conn->handshake_state->sent_versions_at);
  1850. cell = var_cell_new(n_or_protocol_versions * 2);
  1851. cell->command = CELL_VERSIONS;
  1852. for (i = 0; i < n_or_protocol_versions; ++i) {
  1853. uint16_t v = or_protocol_versions[i];
  1854. if (v < min_version || v > max_version)
  1855. continue;
  1856. set_uint16(cell->payload+(2*n_versions), htons(v));
  1857. ++n_versions;
  1858. }
  1859. cell->payload_len = n_versions * 2;
  1860. connection_or_write_var_cell_to_buf(cell, conn);
  1861. conn->handshake_state->sent_versions_at = time(NULL);
  1862. var_cell_free(cell);
  1863. return 0;
  1864. }
  1865. /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
  1866. * about their address, our address, and the current time. */
  1867. MOCK_IMPL(int,
  1868. connection_or_send_netinfo,(or_connection_t *conn))
  1869. {
  1870. cell_t cell;
  1871. time_t now = time(NULL);
  1872. const routerinfo_t *me;
  1873. int len;
  1874. uint8_t *out;
  1875. tor_assert(conn->handshake_state);
  1876. if (conn->handshake_state->sent_netinfo) {
  1877. log_warn(LD_BUG, "Attempted to send an extra netinfo cell on a connection "
  1878. "where we already sent one.");
  1879. return 0;
  1880. }
  1881. memset(&cell, 0, sizeof(cell_t));
  1882. cell.command = CELL_NETINFO;
  1883. /* Timestamp, if we're a relay. */
  1884. if (public_server_mode(get_options()) || ! conn->is_outgoing)
  1885. set_uint32(cell.payload, htonl((uint32_t)now));
  1886. /* Their address. */
  1887. out = cell.payload + 4;
  1888. /* We use &conn->real_addr below, unless it hasn't yet been set. If it
  1889. * hasn't yet been set, we know that base_.addr hasn't been tampered with
  1890. * yet either. */
  1891. len = append_address_to_payload(out, !tor_addr_is_null(&conn->real_addr)
  1892. ? &conn->real_addr : &conn->base_.addr);
  1893. if (len<0)
  1894. return -1;
  1895. out += len;
  1896. /* My address -- only include it if I'm a public relay, or if I'm a
  1897. * bridge and this is an incoming connection. If I'm a bridge and this
  1898. * is an outgoing connection, act like a normal client and omit it. */
  1899. if ((public_server_mode(get_options()) || !conn->is_outgoing) &&
  1900. (me = router_get_my_routerinfo())) {
  1901. tor_addr_t my_addr;
  1902. *out++ = 1 + !tor_addr_is_null(&me->ipv6_addr);
  1903. tor_addr_from_ipv4h(&my_addr, me->addr);
  1904. len = append_address_to_payload(out, &my_addr);
  1905. if (len < 0)
  1906. return -1;
  1907. out += len;
  1908. if (!tor_addr_is_null(&me->ipv6_addr)) {
  1909. len = append_address_to_payload(out, &me->ipv6_addr);
  1910. if (len < 0)
  1911. return -1;
  1912. }
  1913. } else {
  1914. *out = 0;
  1915. }
  1916. conn->handshake_state->digest_sent_data = 0;
  1917. conn->handshake_state->sent_netinfo = 1;
  1918. connection_or_write_cell_to_buf(&cell, conn);
  1919. return 0;
  1920. }
  1921. /** Helper used to add an encoded certs to a cert cell */
  1922. static void
  1923. add_certs_cell_cert_helper(certs_cell_t *certs_cell,
  1924. uint8_t cert_type,
  1925. const uint8_t *cert_encoded,
  1926. size_t cert_len)
  1927. {
  1928. tor_assert(cert_len <= UINT16_MAX);
  1929. certs_cell_cert_t *ccc = certs_cell_cert_new();
  1930. ccc->cert_type = cert_type;
  1931. ccc->cert_len = cert_len;
  1932. certs_cell_cert_setlen_body(ccc, cert_len);
  1933. memcpy(certs_cell_cert_getarray_body(ccc), cert_encoded, cert_len);
  1934. certs_cell_add_certs(certs_cell, ccc);
  1935. }
  1936. /** Add an encoded X509 cert (stored as <b>cert_len</b> bytes at
  1937. * <b>cert_encoded</b>) to the trunnel certs_cell_t object that we are
  1938. * building in <b>certs_cell</b>. Set its type field to <b>cert_type</b>. */
  1939. static void
  1940. add_x509_cert(certs_cell_t *certs_cell,
  1941. uint8_t cert_type,
  1942. const tor_x509_cert_t *cert)
  1943. {
  1944. if (NULL == cert)
  1945. return;
  1946. const uint8_t *cert_encoded = NULL;
  1947. size_t cert_len;
  1948. tor_x509_cert_get_der(cert, &cert_encoded, &cert_len);
  1949. add_certs_cell_cert_helper(certs_cell, cert_type, cert_encoded, cert_len);
  1950. }
  1951. /** Add an Ed25519 cert from <b>cert</b> to the trunnel certs_cell_t object
  1952. * that we are building in <b>certs_cell</b>. Set its type field to
  1953. * <b>cert_type</b>. */
  1954. static void
  1955. add_ed25519_cert(certs_cell_t *certs_cell,
  1956. uint8_t cert_type,
  1957. const tor_cert_t *cert)
  1958. {
  1959. if (NULL == cert)
  1960. return;
  1961. add_certs_cell_cert_helper(certs_cell, cert_type,
  1962. cert->encoded, cert->encoded_len);
  1963. }
  1964. /** Send a CERTS cell on the connection <b>conn</b>. Return 0 on success, -1
  1965. * on failure. */
  1966. int
  1967. connection_or_send_certs_cell(or_connection_t *conn)
  1968. {
  1969. const tor_x509_cert_t *link_cert = NULL, *id_cert = NULL;
  1970. var_cell_t *cell;
  1971. certs_cell_t *certs_cell = NULL;
  1972. tor_assert(conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3);
  1973. if (! conn->handshake_state)
  1974. return -1;
  1975. const int conn_in_server_mode = ! conn->handshake_state->started_here;
  1976. /* Get the encoded values of the X509 certificates */
  1977. if (tor_tls_get_my_certs(conn_in_server_mode, &link_cert, &id_cert) < 0)
  1978. return -1;
  1979. tor_assert(link_cert);
  1980. tor_assert(id_cert);
  1981. certs_cell = certs_cell_new();
  1982. /* Start adding certs. First the link cert or auth1024 cert. */
  1983. if (conn_in_server_mode) {
  1984. add_x509_cert(certs_cell,
  1985. OR_CERT_TYPE_TLS_LINK, link_cert);
  1986. } else {
  1987. add_x509_cert(certs_cell,
  1988. OR_CERT_TYPE_AUTH_1024, link_cert);
  1989. }
  1990. /* Next the RSA->RSA ID cert */
  1991. add_x509_cert(certs_cell,
  1992. OR_CERT_TYPE_ID_1024, id_cert);
  1993. /* Next the Ed25519 certs */
  1994. add_ed25519_cert(certs_cell,
  1995. CERTTYPE_ED_ID_SIGN,
  1996. get_master_signing_key_cert());
  1997. if (conn_in_server_mode) {
  1998. add_ed25519_cert(certs_cell,
  1999. CERTTYPE_ED_SIGN_LINK,
  2000. get_current_link_cert_cert());
  2001. } else {
  2002. add_ed25519_cert(certs_cell,
  2003. CERTTYPE_ED_SIGN_AUTH,
  2004. get_current_auth_key_cert());
  2005. }
  2006. /* And finally the crosscert. */
  2007. {
  2008. const uint8_t *crosscert=NULL;
  2009. size_t crosscert_len;
  2010. get_master_rsa_crosscert(&crosscert, &crosscert_len);
  2011. if (crosscert) {
  2012. add_certs_cell_cert_helper(certs_cell,
  2013. CERTTYPE_RSA1024_ID_EDID,
  2014. crosscert, crosscert_len);
  2015. }
  2016. }
  2017. /* We've added all the certs; make the cell. */
  2018. certs_cell->n_certs = certs_cell_getlen_certs(certs_cell);
  2019. ssize_t alloc_len = certs_cell_encoded_len(certs_cell);
  2020. tor_assert(alloc_len >= 0 && alloc_len <= UINT16_MAX);
  2021. cell = var_cell_new(alloc_len);
  2022. cell->command = CELL_CERTS;
  2023. ssize_t enc_len = certs_cell_encode(cell->payload, alloc_len, certs_cell);
  2024. tor_assert(enc_len > 0 && enc_len <= alloc_len);
  2025. cell->payload_len = enc_len;
  2026. connection_or_write_var_cell_to_buf(cell, conn);
  2027. var_cell_free(cell);
  2028. certs_cell_free(certs_cell);
  2029. return 0;
  2030. }
  2031. /** Return true iff <b>challenge_type</b> is an AUTHCHALLENGE type that
  2032. * we can send and receive. */
  2033. int
  2034. authchallenge_type_is_supported(uint16_t challenge_type)
  2035. {
  2036. switch (challenge_type) {
  2037. case AUTHTYPE_RSA_SHA256_TLSSECRET:
  2038. case AUTHTYPE_ED25519_SHA256_RFC5705:
  2039. return 1;
  2040. case AUTHTYPE_RSA_SHA256_RFC5705:
  2041. default:
  2042. return 0;
  2043. }
  2044. }
  2045. /** Return true iff <b>challenge_type_a</b> is one that we would rather
  2046. * use than <b>challenge_type_b</b>. */
  2047. int
  2048. authchallenge_type_is_better(uint16_t challenge_type_a,
  2049. uint16_t challenge_type_b)
  2050. {
  2051. /* Any supported type is better than an unsupported one;
  2052. * all unsupported types are equally bad. */
  2053. if (!authchallenge_type_is_supported(challenge_type_a))
  2054. return 0;
  2055. if (!authchallenge_type_is_supported(challenge_type_b))
  2056. return 1;
  2057. /* It happens that types are superior in numerically ascending order.
  2058. * If that ever changes, this must change too. */
  2059. return (challenge_type_a > challenge_type_b);
  2060. }
  2061. /** Send an AUTH_CHALLENGE cell on the connection <b>conn</b>. Return 0
  2062. * on success, -1 on failure. */
  2063. int
  2064. connection_or_send_auth_challenge_cell(or_connection_t *conn)
  2065. {
  2066. var_cell_t *cell = NULL;
  2067. int r = -1;
  2068. tor_assert(conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3);
  2069. if (! conn->handshake_state)
  2070. return -1;
  2071. auth_challenge_cell_t *ac = auth_challenge_cell_new();
  2072. tor_assert(sizeof(ac->challenge) == 32);
  2073. crypto_rand((char*)ac->challenge, sizeof(ac->challenge));
  2074. auth_challenge_cell_add_methods(ac, AUTHTYPE_RSA_SHA256_TLSSECRET);
  2075. /* Disabled, because everything that supports this method also supports
  2076. * the much-superior ED25519_SHA256_RFC5705 */
  2077. /* auth_challenge_cell_add_methods(ac, AUTHTYPE_RSA_SHA256_RFC5705); */
  2078. auth_challenge_cell_add_methods(ac, AUTHTYPE_ED25519_SHA256_RFC5705);
  2079. auth_challenge_cell_set_n_methods(ac,
  2080. auth_challenge_cell_getlen_methods(ac));
  2081. cell = var_cell_new(auth_challenge_cell_encoded_len(ac));
  2082. ssize_t len = auth_challenge_cell_encode(cell->payload, cell->payload_len,
  2083. ac);
  2084. if (len != cell->payload_len) {
  2085. /* LCOV_EXCL_START */
  2086. log_warn(LD_BUG, "Encoded auth challenge cell length not as expected");
  2087. goto done;
  2088. /* LCOV_EXCL_STOP */
  2089. }
  2090. cell->command = CELL_AUTH_CHALLENGE;
  2091. connection_or_write_var_cell_to_buf(cell, conn);
  2092. r = 0;
  2093. done:
  2094. var_cell_free(cell);
  2095. auth_challenge_cell_free(ac);
  2096. return r;
  2097. }
  2098. /** Compute the main body of an AUTHENTICATE cell that a client can use
  2099. * to authenticate itself on a v3 handshake for <b>conn</b>. Return it
  2100. * in a var_cell_t.
  2101. *
  2102. * If <b>server</b> is true, only calculate the first
  2103. * V3_AUTH_FIXED_PART_LEN bytes -- the part of the authenticator that's
  2104. * determined by the rest of the handshake, and which match the provided value
  2105. * exactly.
  2106. *
  2107. * If <b>server</b> is false and <b>signing_key</b> is NULL, calculate the
  2108. * first V3_AUTH_BODY_LEN bytes of the authenticator (that is, everything
  2109. * that should be signed), but don't actually sign it.
  2110. *
  2111. * If <b>server</b> is false and <b>signing_key</b> is provided, calculate the
  2112. * entire authenticator, signed with <b>signing_key</b>.
  2113. *
  2114. * Return the length of the cell body on success, and -1 on failure.
  2115. */
  2116. var_cell_t *
  2117. connection_or_compute_authenticate_cell_body(or_connection_t *conn,
  2118. const int authtype,
  2119. crypto_pk_t *signing_key,
  2120. const ed25519_keypair_t *ed_signing_key,
  2121. int server)
  2122. {
  2123. auth1_t *auth = NULL;
  2124. auth_ctx_t *ctx = auth_ctx_new();
  2125. var_cell_t *result = NULL;
  2126. int old_tlssecrets_algorithm = 0;
  2127. const char *authtype_str = NULL;
  2128. int is_ed = 0;
  2129. /* assert state is reasonable XXXX */
  2130. switch (authtype) {
  2131. case AUTHTYPE_RSA_SHA256_TLSSECRET:
  2132. authtype_str = "AUTH0001";
  2133. old_tlssecrets_algorithm = 1;
  2134. break;
  2135. case AUTHTYPE_RSA_SHA256_RFC5705:
  2136. authtype_str = "AUTH0002";
  2137. break;
  2138. case AUTHTYPE_ED25519_SHA256_RFC5705:
  2139. authtype_str = "AUTH0003";
  2140. is_ed = 1;
  2141. break;
  2142. default:
  2143. tor_assert(0);
  2144. break;
  2145. }
  2146. auth = auth1_new();
  2147. ctx->is_ed = is_ed;
  2148. /* Type: 8 bytes. */
  2149. memcpy(auth1_getarray_type(auth), authtype_str, 8);
  2150. {
  2151. const tor_x509_cert_t *id_cert=NULL, *link_cert=NULL;
  2152. const common_digests_t *my_digests, *their_digests;
  2153. const uint8_t *my_id, *their_id, *client_id, *server_id;
  2154. if (tor_tls_get_my_certs(server, &link_cert, &id_cert))
  2155. goto err;
  2156. my_digests = tor_x509_cert_get_id_digests(id_cert);
  2157. their_digests =
  2158. tor_x509_cert_get_id_digests(conn->handshake_state->certs->id_cert);
  2159. tor_assert(my_digests);
  2160. tor_assert(their_digests);
  2161. my_id = (uint8_t*)my_digests->d[DIGEST_SHA256];
  2162. their_id = (uint8_t*)their_digests->d[DIGEST_SHA256];
  2163. client_id = server ? their_id : my_id;
  2164. server_id = server ? my_id : their_id;
  2165. /* Client ID digest: 32 octets. */
  2166. memcpy(auth->cid, client_id, 32);
  2167. /* Server ID digest: 32 octets. */
  2168. memcpy(auth->sid, server_id, 32);
  2169. }
  2170. if (is_ed) {
  2171. const ed25519_public_key_t *my_ed_id, *their_ed_id;
  2172. if (!conn->handshake_state->certs->ed_id_sign) {
  2173. log_warn(LD_OR, "Ed authenticate without Ed ID cert from peer.");
  2174. goto err;
  2175. }
  2176. my_ed_id = get_master_identity_key();
  2177. their_ed_id = &conn->handshake_state->certs->ed_id_sign->signing_key;
  2178. const uint8_t *cid_ed = (server ? their_ed_id : my_ed_id)->pubkey;
  2179. const uint8_t *sid_ed = (server ? my_ed_id : their_ed_id)->pubkey;
  2180. memcpy(auth->u1_cid_ed, cid_ed, ED25519_PUBKEY_LEN);
  2181. memcpy(auth->u1_sid_ed, sid_ed, ED25519_PUBKEY_LEN);
  2182. }
  2183. {
  2184. crypto_digest_t *server_d, *client_d;
  2185. if (server) {
  2186. server_d = conn->handshake_state->digest_sent;
  2187. client_d = conn->handshake_state->digest_received;
  2188. } else {
  2189. client_d = conn->handshake_state->digest_sent;
  2190. server_d = conn->handshake_state->digest_received;
  2191. }
  2192. /* Server log digest : 32 octets */
  2193. crypto_digest_get_digest(server_d, (char*)auth->slog, 32);
  2194. /* Client log digest : 32 octets */
  2195. crypto_digest_get_digest(client_d, (char*)auth->clog, 32);
  2196. }
  2197. {
  2198. /* Digest of cert used on TLS link : 32 octets. */
  2199. const tor_x509_cert_t *cert = NULL;
  2200. tor_x509_cert_t *freecert = NULL;
  2201. if (server) {
  2202. tor_tls_get_my_certs(1, &cert, NULL);
  2203. } else {
  2204. freecert = tor_tls_get_peer_cert(conn->tls);
  2205. cert = freecert;
  2206. }
  2207. if (!cert) {
  2208. log_warn(LD_OR, "Unable to find cert when making %s data.",
  2209. authtype_str);
  2210. goto err;
  2211. }
  2212. memcpy(auth->scert,
  2213. tor_x509_cert_get_cert_digests(cert)->d[DIGEST_SHA256], 32);
  2214. if (freecert)
  2215. tor_x509_cert_free(freecert);
  2216. }
  2217. /* HMAC of clientrandom and serverrandom using master key : 32 octets */
  2218. if (old_tlssecrets_algorithm) {
  2219. tor_tls_get_tlssecrets(conn->tls, auth->tlssecrets);
  2220. } else {
  2221. char label[128];
  2222. tor_snprintf(label, sizeof(label),
  2223. "EXPORTER FOR TOR TLS CLIENT BINDING %s", authtype_str);
  2224. tor_tls_export_key_material(conn->tls, auth->tlssecrets,
  2225. auth->cid, sizeof(auth->cid),
  2226. label);
  2227. }
  2228. /* 8 octets were reserved for the current time, but we're trying to get out
  2229. * of the habit of sending time around willynilly. Fortunately, nothing
  2230. * checks it. That's followed by 16 bytes of nonce. */
  2231. crypto_rand((char*)auth->rand, 24);
  2232. ssize_t maxlen = auth1_encoded_len(auth, ctx);
  2233. if (ed_signing_key && is_ed) {
  2234. maxlen += ED25519_SIG_LEN;
  2235. } else if (signing_key && !is_ed) {
  2236. maxlen += crypto_pk_keysize(signing_key);
  2237. }
  2238. const int AUTH_CELL_HEADER_LEN = 4; /* 2 bytes of type, 2 bytes of length */
  2239. result = var_cell_new(AUTH_CELL_HEADER_LEN + maxlen);
  2240. uint8_t *const out = result->payload + AUTH_CELL_HEADER_LEN;
  2241. const size_t outlen = maxlen;
  2242. ssize_t len;
  2243. result->command = CELL_AUTHENTICATE;
  2244. set_uint16(result->payload, htons(authtype));
  2245. if ((len = auth1_encode(out, outlen, auth, ctx)) < 0) {
  2246. /* LCOV_EXCL_START */
  2247. log_warn(LD_BUG, "Unable to encode signed part of AUTH1 data.");
  2248. goto err;
  2249. /* LCOV_EXCL_STOP */
  2250. }
  2251. if (server) {
  2252. auth1_t *tmp = NULL;
  2253. ssize_t len2 = auth1_parse(&tmp, out, len, ctx);
  2254. if (!tmp) {
  2255. /* LCOV_EXCL_START */
  2256. log_warn(LD_BUG, "Unable to parse signed part of AUTH1 data that "
  2257. "we just encoded");
  2258. goto err;
  2259. /* LCOV_EXCL_STOP */
  2260. }
  2261. result->payload_len = (tmp->end_of_signed - result->payload);
  2262. auth1_free(tmp);
  2263. if (len2 != len) {
  2264. /* LCOV_EXCL_START */
  2265. log_warn(LD_BUG, "Mismatched length when re-parsing AUTH1 data.");
  2266. goto err;
  2267. /* LCOV_EXCL_STOP */
  2268. }
  2269. goto done;
  2270. }
  2271. if (ed_signing_key && is_ed) {
  2272. ed25519_signature_t sig;
  2273. if (ed25519_sign(&sig, out, len, ed_signing_key) < 0) {
  2274. /* LCOV_EXCL_START */
  2275. log_warn(LD_BUG, "Unable to sign ed25519 authentication data");
  2276. goto err;
  2277. /* LCOV_EXCL_STOP */
  2278. }
  2279. auth1_setlen_sig(auth, ED25519_SIG_LEN);
  2280. memcpy(auth1_getarray_sig(auth), sig.sig, ED25519_SIG_LEN);
  2281. } else if (signing_key && !is_ed) {
  2282. auth1_setlen_sig(auth, crypto_pk_keysize(signing_key));
  2283. char d[32];
  2284. crypto_digest256(d, (char*)out, len, DIGEST_SHA256);
  2285. int siglen = crypto_pk_private_sign(signing_key,
  2286. (char*)auth1_getarray_sig(auth),
  2287. auth1_getlen_sig(auth),
  2288. d, 32);
  2289. if (siglen < 0) {
  2290. log_warn(LD_OR, "Unable to sign AUTH1 data.");
  2291. goto err;
  2292. }
  2293. auth1_setlen_sig(auth, siglen);
  2294. }
  2295. len = auth1_encode(out, outlen, auth, ctx);
  2296. if (len < 0) {
  2297. /* LCOV_EXCL_START */
  2298. log_warn(LD_BUG, "Unable to encode signed AUTH1 data.");
  2299. goto err;
  2300. /* LCOV_EXCL_STOP */
  2301. }
  2302. tor_assert(len + AUTH_CELL_HEADER_LEN <= result->payload_len);
  2303. result->payload_len = len + AUTH_CELL_HEADER_LEN;
  2304. set_uint16(result->payload+2, htons(len));
  2305. goto done;
  2306. err:
  2307. var_cell_free(result);
  2308. result = NULL;
  2309. done:
  2310. auth1_free(auth);
  2311. auth_ctx_free(ctx);
  2312. return result;
  2313. }
  2314. /** Send an AUTHENTICATE cell on the connection <b>conn</b>. Return 0 on
  2315. * success, -1 on failure */
  2316. MOCK_IMPL(int,
  2317. connection_or_send_authenticate_cell,(or_connection_t *conn, int authtype))
  2318. {
  2319. var_cell_t *cell;
  2320. crypto_pk_t *pk = tor_tls_get_my_client_auth_key();
  2321. /* XXXX make sure we're actually supposed to send this! */
  2322. if (!pk) {
  2323. log_warn(LD_BUG, "Can't compute authenticate cell: no client auth key");
  2324. return -1;
  2325. }
  2326. if (! authchallenge_type_is_supported(authtype)) {
  2327. log_warn(LD_BUG, "Tried to send authenticate cell with unknown "
  2328. "authentication type %d", authtype);
  2329. return -1;
  2330. }
  2331. cell = connection_or_compute_authenticate_cell_body(conn,
  2332. authtype,
  2333. pk,
  2334. get_current_auth_keypair(),
  2335. 0 /* not server */);
  2336. if (! cell) {
  2337. /* LCOV_EXCL_START */
  2338. log_warn(LD_BUG, "Unable to compute authenticate cell!");
  2339. return -1;
  2340. /* LCOV_EXCL_STOP */
  2341. }
  2342. connection_or_write_var_cell_to_buf(cell, conn);
  2343. var_cell_free(cell);
  2344. return 0;
  2345. }