connection_or.c 88 KB

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