or.h 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305
  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-2018, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file or.h
  8. * \brief Master header file for Tor-specific functionality.
  9. **/
  10. #ifndef TOR_OR_H
  11. #define TOR_OR_H
  12. #include "orconfig.h"
  13. #ifdef HAVE_UNISTD_H
  14. #include <unistd.h>
  15. #endif
  16. #ifdef HAVE_SIGNAL_H
  17. #include <signal.h>
  18. #endif
  19. #ifdef HAVE_NETDB_H
  20. #include <netdb.h>
  21. #endif
  22. #ifdef HAVE_SYS_PARAM_H
  23. #include <sys/param.h> /* FreeBSD needs this to know what version it is */
  24. #endif
  25. #include "lib/cc/torint.h"
  26. #ifdef HAVE_SYS_FCNTL_H
  27. #include <sys/fcntl.h>
  28. #endif
  29. #ifdef HAVE_FCNTL_H
  30. #include <fcntl.h>
  31. #endif
  32. #ifdef HAVE_SYS_IOCTL_H
  33. #include <sys/ioctl.h>
  34. #endif
  35. #ifdef HAVE_SYS_UN_H
  36. #include <sys/un.h>
  37. #endif
  38. #ifdef HAVE_SYS_STAT_H
  39. #include <sys/stat.h>
  40. #endif
  41. #ifdef HAVE_NETINET_IN_H
  42. #include <netinet/in.h>
  43. #endif
  44. #ifdef HAVE_ARPA_INET_H
  45. #include <arpa/inet.h>
  46. #endif
  47. #ifdef HAVE_ERRNO_H
  48. #include <errno.h>
  49. #endif
  50. #ifdef HAVE_TIME_H
  51. #include <time.h>
  52. #endif
  53. #ifdef _WIN32
  54. #include <winsock2.h>
  55. #include <io.h>
  56. #include <process.h>
  57. #include <direct.h>
  58. #include <windows.h>
  59. #endif /* defined(_WIN32) */
  60. #include "common/util.h"
  61. #include "lib/container/map.h"
  62. #include "lib/container/smartlist.h"
  63. #include "lib/crypt_ops/crypto.h"
  64. #include "lib/defs/dh_sizes.h"
  65. #include "lib/encoding/binascii.h"
  66. #include "lib/net/address.h"
  67. #include "ht.h"
  68. // These, more than other includes, are for keeping the other struct
  69. // definitions working. We should remove them when we minimize our includes.
  70. #include "or/entry_port_cfg_st.h"
  71. struct ed25519_public_key_t;
  72. struct curve25519_public_key_t;
  73. /* These signals are defined to help handle_control_signal work.
  74. */
  75. #ifndef SIGHUP
  76. #define SIGHUP 1
  77. #endif
  78. #ifndef SIGINT
  79. #define SIGINT 2
  80. #endif
  81. #ifndef SIGUSR1
  82. #define SIGUSR1 10
  83. #endif
  84. #ifndef SIGUSR2
  85. #define SIGUSR2 12
  86. #endif
  87. #ifndef SIGTERM
  88. #define SIGTERM 15
  89. #endif
  90. /* Controller signals start at a high number so we don't
  91. * conflict with system-defined signals. */
  92. #define SIGNEWNYM 129
  93. #define SIGCLEARDNSCACHE 130
  94. #define SIGHEARTBEAT 131
  95. #if (SIZEOF_CELL_T != 0)
  96. /* On Irix, stdlib.h defines a cell_t type, so we need to make sure
  97. * that our stuff always calls cell_t something different. */
  98. #define cell_t tor_cell_t
  99. #endif
  100. #ifdef ENABLE_TOR2WEB_MODE
  101. #define NON_ANONYMOUS_MODE_ENABLED 1
  102. #endif
  103. /** Helper macro: Given a pointer to to.base_, of type from*, return &to. */
  104. #define DOWNCAST(to, ptr) ((to*)SUBTYPE_P(ptr, to, base_))
  105. /** Length of longest allowable configured nickname. */
  106. #define MAX_NICKNAME_LEN 19
  107. /** Length of a router identity encoded as a hexadecimal digest, plus
  108. * possible dollar sign. */
  109. #define MAX_HEX_NICKNAME_LEN (HEX_DIGEST_LEN+1)
  110. /** Maximum length of verbose router identifier: dollar sign, hex ID digest,
  111. * equal sign or tilde, nickname. */
  112. #define MAX_VERBOSE_NICKNAME_LEN (1+HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN)
  113. /** For HTTP parsing: Maximum number of bytes we'll accept in the headers
  114. * of an HTTP request or response. */
  115. #define MAX_HEADERS_SIZE 50000
  116. /** Maximum size, in bytes, of a single router descriptor uploaded to us
  117. * as a directory authority. Caches and clients fetch whatever descriptors
  118. * the authorities tell them to fetch, and don't care about size. */
  119. #define MAX_DESCRIPTOR_UPLOAD_SIZE 20000
  120. /** Maximum size of a single extrainfo document, as above. */
  121. #define MAX_EXTRAINFO_UPLOAD_SIZE 50000
  122. /** Minimum lifetime for an onion key in days. */
  123. #define MIN_ONION_KEY_LIFETIME_DAYS (1)
  124. /** Maximum lifetime for an onion key in days. */
  125. #define MAX_ONION_KEY_LIFETIME_DAYS (90)
  126. /** Default lifetime for an onion key in days. */
  127. #define DEFAULT_ONION_KEY_LIFETIME_DAYS (28)
  128. /** Minimum grace period for acceptance of an onion key in days.
  129. * The maximum value is defined in proposal #274 as being the current network
  130. * consensus parameter for "onion-key-rotation-days". */
  131. #define MIN_ONION_KEY_GRACE_PERIOD_DAYS (1)
  132. /** Default grace period for acceptance of an onion key in days. */
  133. #define DEFAULT_ONION_KEY_GRACE_PERIOD_DAYS (7)
  134. /** How often we should check the network consensus if it is time to rotate or
  135. * expire onion keys. */
  136. #define ONION_KEY_CONSENSUS_CHECK_INTERVAL (60*60)
  137. /** How often do we rotate TLS contexts? */
  138. #define MAX_SSL_KEY_LIFETIME_INTERNAL (2*60*60)
  139. /** How old do we allow a router to get before removing it
  140. * from the router list? In seconds. */
  141. #define ROUTER_MAX_AGE (60*60*48)
  142. /** How old can a router get before we (as a server) will no longer
  143. * consider it live? In seconds. */
  144. #define ROUTER_MAX_AGE_TO_PUBLISH (60*60*24)
  145. /** How old do we let a saved descriptor get before force-removing it? */
  146. #define OLD_ROUTER_DESC_MAX_AGE (60*60*24*5)
  147. /* Proxy client types */
  148. #define PROXY_NONE 0
  149. #define PROXY_CONNECT 1
  150. #define PROXY_SOCKS4 2
  151. #define PROXY_SOCKS5 3
  152. /* !!!! If there is ever a PROXY_* type over 3, we must grow the proxy_type
  153. * field in or_connection_t */
  154. /* Pluggable transport proxy type. Don't use this in or_connection_t,
  155. * instead use the actual underlying proxy type (see above). */
  156. #define PROXY_PLUGGABLE 4
  157. /** How many circuits do we want simultaneously in-progress to handle
  158. * a given stream? */
  159. #define MIN_CIRCUITS_HANDLING_STREAM 2
  160. /* These RELAY_COMMAND constants define values for relay cell commands, and
  161. * must match those defined in tor-spec.txt. */
  162. #define RELAY_COMMAND_BEGIN 1
  163. #define RELAY_COMMAND_DATA 2
  164. #define RELAY_COMMAND_END 3
  165. #define RELAY_COMMAND_CONNECTED 4
  166. #define RELAY_COMMAND_SENDME 5
  167. #define RELAY_COMMAND_EXTEND 6
  168. #define RELAY_COMMAND_EXTENDED 7
  169. #define RELAY_COMMAND_TRUNCATE 8
  170. #define RELAY_COMMAND_TRUNCATED 9
  171. #define RELAY_COMMAND_DROP 10
  172. #define RELAY_COMMAND_RESOLVE 11
  173. #define RELAY_COMMAND_RESOLVED 12
  174. #define RELAY_COMMAND_BEGIN_DIR 13
  175. #define RELAY_COMMAND_EXTEND2 14
  176. #define RELAY_COMMAND_EXTENDED2 15
  177. #define RELAY_COMMAND_ESTABLISH_INTRO 32
  178. #define RELAY_COMMAND_ESTABLISH_RENDEZVOUS 33
  179. #define RELAY_COMMAND_INTRODUCE1 34
  180. #define RELAY_COMMAND_INTRODUCE2 35
  181. #define RELAY_COMMAND_RENDEZVOUS1 36
  182. #define RELAY_COMMAND_RENDEZVOUS2 37
  183. #define RELAY_COMMAND_INTRO_ESTABLISHED 38
  184. #define RELAY_COMMAND_RENDEZVOUS_ESTABLISHED 39
  185. #define RELAY_COMMAND_INTRODUCE_ACK 40
  186. /* Reasons why an OR connection is closed. */
  187. #define END_OR_CONN_REASON_DONE 1
  188. #define END_OR_CONN_REASON_REFUSED 2 /* connection refused */
  189. #define END_OR_CONN_REASON_OR_IDENTITY 3
  190. #define END_OR_CONN_REASON_CONNRESET 4 /* connection reset by peer */
  191. #define END_OR_CONN_REASON_TIMEOUT 5
  192. #define END_OR_CONN_REASON_NO_ROUTE 6 /* no route to host/net */
  193. #define END_OR_CONN_REASON_IO_ERROR 7 /* read/write error */
  194. #define END_OR_CONN_REASON_RESOURCE_LIMIT 8 /* sockets, buffers, etc */
  195. #define END_OR_CONN_REASON_PT_MISSING 9 /* PT failed or not available */
  196. #define END_OR_CONN_REASON_MISC 10
  197. /* Reasons why we (or a remote OR) might close a stream. See tor-spec.txt for
  198. * documentation of these. The values must match. */
  199. #define END_STREAM_REASON_MISC 1
  200. #define END_STREAM_REASON_RESOLVEFAILED 2
  201. #define END_STREAM_REASON_CONNECTREFUSED 3
  202. #define END_STREAM_REASON_EXITPOLICY 4
  203. #define END_STREAM_REASON_DESTROY 5
  204. #define END_STREAM_REASON_DONE 6
  205. #define END_STREAM_REASON_TIMEOUT 7
  206. #define END_STREAM_REASON_NOROUTE 8
  207. #define END_STREAM_REASON_HIBERNATING 9
  208. #define END_STREAM_REASON_INTERNAL 10
  209. #define END_STREAM_REASON_RESOURCELIMIT 11
  210. #define END_STREAM_REASON_CONNRESET 12
  211. #define END_STREAM_REASON_TORPROTOCOL 13
  212. #define END_STREAM_REASON_NOTDIRECTORY 14
  213. #define END_STREAM_REASON_ENTRYPOLICY 15
  214. /* These high-numbered end reasons are not part of the official spec,
  215. * and are not intended to be put in relay end cells. They are here
  216. * to be more informative when sending back socks replies to the
  217. * application. */
  218. /* XXXX 256 is no longer used; feel free to reuse it. */
  219. /** We were unable to attach the connection to any circuit at all. */
  220. /* XXXX the ways we use this one don't make a lot of sense. */
  221. #define END_STREAM_REASON_CANT_ATTACH 257
  222. /** We can't connect to any directories at all, so we killed our streams
  223. * before they can time out. */
  224. #define END_STREAM_REASON_NET_UNREACHABLE 258
  225. /** This is a SOCKS connection, and the client used (or misused) the SOCKS
  226. * protocol in a way we couldn't handle. */
  227. #define END_STREAM_REASON_SOCKSPROTOCOL 259
  228. /** This is a transparent proxy connection, but we can't extract the original
  229. * target address:port. */
  230. #define END_STREAM_REASON_CANT_FETCH_ORIG_DEST 260
  231. /** This is a connection on the NATD port, and the destination IP:Port was
  232. * either ill-formed or out-of-range. */
  233. #define END_STREAM_REASON_INVALID_NATD_DEST 261
  234. /** The target address is in a private network (like 127.0.0.1 or 10.0.0.1);
  235. * you don't want to do that over a randomly chosen exit */
  236. #define END_STREAM_REASON_PRIVATE_ADDR 262
  237. /** This is an HTTP tunnel connection and the client used or misused HTTP in a
  238. * way we can't handle.
  239. */
  240. #define END_STREAM_REASON_HTTPPROTOCOL 263
  241. /** Bitwise-and this value with endreason to mask out all flags. */
  242. #define END_STREAM_REASON_MASK 511
  243. /** Bitwise-or this with the argument to control_event_stream_status
  244. * to indicate that the reason came from an END cell. */
  245. #define END_STREAM_REASON_FLAG_REMOTE 512
  246. /** Bitwise-or this with the argument to control_event_stream_status
  247. * to indicate that we already sent a CLOSED stream event. */
  248. #define END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED 1024
  249. /** Bitwise-or this with endreason to indicate that we already sent
  250. * a socks reply, and no further reply needs to be sent from
  251. * connection_mark_unattached_ap(). */
  252. #define END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED 2048
  253. /* 'type' values to use in RESOLVED cells. Specified in tor-spec.txt. */
  254. #define RESOLVED_TYPE_HOSTNAME 0
  255. #define RESOLVED_TYPE_IPV4 4
  256. #define RESOLVED_TYPE_IPV6 6
  257. #define RESOLVED_TYPE_ERROR_TRANSIENT 0xF0
  258. #define RESOLVED_TYPE_ERROR 0xF1
  259. /* Negative reasons are internal: we never send them in a DESTROY or TRUNCATE
  260. * call; they only go to the controller for tracking */
  261. /* Closing introduction point that were opened in parallel. */
  262. #define END_CIRC_REASON_IP_NOW_REDUNDANT -4
  263. /** Our post-timeout circuit time measurement period expired.
  264. * We must give up now */
  265. #define END_CIRC_REASON_MEASUREMENT_EXPIRED -3
  266. /** We couldn't build a path for this circuit. */
  267. #define END_CIRC_REASON_NOPATH -2
  268. /** Catch-all "other" reason for closing origin circuits. */
  269. #define END_CIRC_AT_ORIGIN -1
  270. /* Reasons why we (or a remote OR) might close a circuit. See tor-spec.txt
  271. * section 5.4 for documentation of these. */
  272. #define END_CIRC_REASON_MIN_ 0
  273. #define END_CIRC_REASON_NONE 0
  274. #define END_CIRC_REASON_TORPROTOCOL 1
  275. #define END_CIRC_REASON_INTERNAL 2
  276. #define END_CIRC_REASON_REQUESTED 3
  277. #define END_CIRC_REASON_HIBERNATING 4
  278. #define END_CIRC_REASON_RESOURCELIMIT 5
  279. #define END_CIRC_REASON_CONNECTFAILED 6
  280. #define END_CIRC_REASON_OR_IDENTITY 7
  281. #define END_CIRC_REASON_CHANNEL_CLOSED 8
  282. #define END_CIRC_REASON_FINISHED 9
  283. #define END_CIRC_REASON_TIMEOUT 10
  284. #define END_CIRC_REASON_DESTROYED 11
  285. #define END_CIRC_REASON_NOSUCHSERVICE 12
  286. #define END_CIRC_REASON_MAX_ 12
  287. /** Bitwise-OR this with the argument to circuit_mark_for_close() or
  288. * control_event_circuit_status() to indicate that the reason was
  289. * passed through from a destroy or truncate cell. */
  290. #define END_CIRC_REASON_FLAG_REMOTE 512
  291. /** Length of 'y' portion of 'y.onion' URL. */
  292. #define REND_SERVICE_ID_LEN_BASE32 16
  293. /** Length of 'y.onion' including '.onion' URL. */
  294. #define REND_SERVICE_ADDRESS_LEN (16+1+5)
  295. /** Length of a binary-encoded rendezvous service ID. */
  296. #define REND_SERVICE_ID_LEN 10
  297. /** Time period for which a v2 descriptor will be valid. */
  298. #define REND_TIME_PERIOD_V2_DESC_VALIDITY (24*60*60)
  299. /** Time period within which two sets of v2 descriptors will be uploaded in
  300. * parallel. */
  301. #define REND_TIME_PERIOD_OVERLAPPING_V2_DESCS (60*60)
  302. /** Number of non-consecutive replicas (i.e. distributed somewhere
  303. * in the ring) for a descriptor. */
  304. #define REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS 2
  305. /** Number of consecutive replicas for a descriptor. */
  306. #define REND_NUMBER_OF_CONSECUTIVE_REPLICAS 3
  307. /** Length of v2 descriptor ID (32 base32 chars = 160 bits). */
  308. #define REND_DESC_ID_V2_LEN_BASE32 BASE32_DIGEST_LEN
  309. /** Length of the base32-encoded secret ID part of versioned hidden service
  310. * descriptors. */
  311. #define REND_SECRET_ID_PART_LEN_BASE32 BASE32_DIGEST_LEN
  312. /** Length of the base32-encoded hash of an introduction point's
  313. * identity key. */
  314. #define REND_INTRO_POINT_ID_LEN_BASE32 BASE32_DIGEST_LEN
  315. /** Length of the descriptor cookie that is used for client authorization
  316. * to hidden services. */
  317. #define REND_DESC_COOKIE_LEN 16
  318. /** Length of the base64-encoded descriptor cookie that is used for
  319. * exchanging client authorization between hidden service and client. */
  320. #define REND_DESC_COOKIE_LEN_BASE64 22
  321. /** Length of client identifier in encrypted introduction points for hidden
  322. * service authorization type 'basic'. */
  323. #define REND_BASIC_AUTH_CLIENT_ID_LEN 4
  324. /** Multiple of the number of clients to which the real number of clients
  325. * is padded with fake clients for hidden service authorization type
  326. * 'basic'. */
  327. #define REND_BASIC_AUTH_CLIENT_MULTIPLE 16
  328. /** Length of client entry consisting of client identifier and encrypted
  329. * session key for hidden service authorization type 'basic'. */
  330. #define REND_BASIC_AUTH_CLIENT_ENTRY_LEN (REND_BASIC_AUTH_CLIENT_ID_LEN \
  331. + CIPHER_KEY_LEN)
  332. /** Maximum size of v2 hidden service descriptors. */
  333. #define REND_DESC_MAX_SIZE (20 * 1024)
  334. /** Legal characters for use in authorized client names for a hidden
  335. * service. */
  336. #define REND_LEGAL_CLIENTNAME_CHARACTERS \
  337. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-_"
  338. /** Maximum length of authorized client names for a hidden service. */
  339. #define REND_CLIENTNAME_MAX_LEN 16
  340. /** Length of the rendezvous cookie that is used to connect circuits at the
  341. * rendezvous point. */
  342. #define REND_COOKIE_LEN DIGEST_LEN
  343. /** Client authorization type that a hidden service performs. */
  344. typedef enum rend_auth_type_t {
  345. REND_NO_AUTH = 0,
  346. REND_BASIC_AUTH = 1,
  347. REND_STEALTH_AUTH = 2,
  348. } rend_auth_type_t;
  349. /** Client-side configuration of authorization for a hidden service. */
  350. typedef struct rend_service_authorization_t {
  351. uint8_t descriptor_cookie[REND_DESC_COOKIE_LEN];
  352. char onion_address[REND_SERVICE_ADDRESS_LEN+1];
  353. rend_auth_type_t auth_type;
  354. } rend_service_authorization_t;
  355. /** Client- and server-side data that is used for hidden service connection
  356. * establishment. Not all fields contain data depending on where this struct
  357. * is used. */
  358. typedef struct rend_data_t {
  359. /* Hidden service protocol version of this base object. */
  360. uint32_t version;
  361. /** List of HSDir fingerprints on which this request has been sent to. This
  362. * contains binary identity digest of the directory of size DIGEST_LEN. */
  363. smartlist_t *hsdirs_fp;
  364. /** Rendezvous cookie used by both, client and service. */
  365. char rend_cookie[REND_COOKIE_LEN];
  366. /** Number of streams associated with this rendezvous circuit. */
  367. int nr_streams;
  368. } rend_data_t;
  369. typedef struct rend_data_v2_t {
  370. /* Rendezvous base data. */
  371. rend_data_t base_;
  372. /** Onion address (without the .onion part) that a client requests. */
  373. char onion_address[REND_SERVICE_ID_LEN_BASE32+1];
  374. /** Descriptor ID for each replicas computed from the onion address. If
  375. * the onion address is empty, this array MUST be empty. We keep them so
  376. * we know when to purge our entry in the last hsdir request table. */
  377. char descriptor_id[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS][DIGEST_LEN];
  378. /** (Optional) descriptor cookie that is used by a client. */
  379. char descriptor_cookie[REND_DESC_COOKIE_LEN];
  380. /** Authorization type for accessing a service used by a client. */
  381. rend_auth_type_t auth_type;
  382. /** Descriptor ID for a client request. The control port command HSFETCH
  383. * uses this. It's set if the descriptor query should only use this
  384. * descriptor ID. */
  385. char desc_id_fetch[DIGEST_LEN];
  386. /** Hash of the hidden service's PK used by a service. */
  387. char rend_pk_digest[DIGEST_LEN];
  388. } rend_data_v2_t;
  389. /* From a base rend_data_t object <b>d</d>, return the v2 object. */
  390. static inline
  391. rend_data_v2_t *TO_REND_DATA_V2(const rend_data_t *d)
  392. {
  393. tor_assert(d);
  394. tor_assert(d->version == 2);
  395. return DOWNCAST(rend_data_v2_t, d);
  396. }
  397. /* Stub because we can't include hs_ident.h. */
  398. struct hs_ident_edge_conn_t;
  399. struct hs_ident_dir_conn_t;
  400. struct hs_ident_circuit_t;
  401. typedef struct hsdir_index_t hsdir_index_t;
  402. /** Time interval for tracking replays of DH public keys received in
  403. * INTRODUCE2 cells. Used only to avoid launching multiple
  404. * simultaneous attempts to connect to the same rendezvous point. */
  405. #define REND_REPLAY_TIME_INTERVAL (5 * 60)
  406. /** Used to indicate which way a cell is going on a circuit. */
  407. typedef enum {
  408. CELL_DIRECTION_IN=1, /**< The cell is moving towards the origin. */
  409. CELL_DIRECTION_OUT=2, /**< The cell is moving away from the origin. */
  410. } cell_direction_t;
  411. /** Initial value for both sides of a circuit transmission window when the
  412. * circuit is initialized. Measured in cells. */
  413. #define CIRCWINDOW_START 1000
  414. #define CIRCWINDOW_START_MIN 100
  415. #define CIRCWINDOW_START_MAX 1000
  416. /** Amount to increment a circuit window when we get a circuit SENDME. */
  417. #define CIRCWINDOW_INCREMENT 100
  418. /** Initial value on both sides of a stream transmission window when the
  419. * stream is initialized. Measured in cells. */
  420. #define STREAMWINDOW_START 500
  421. #define STREAMWINDOW_START_MAX 500
  422. /** Amount to increment a stream window when we get a stream SENDME. */
  423. #define STREAMWINDOW_INCREMENT 50
  424. /** Maximum number of queued cells on a circuit for which we are the
  425. * midpoint before we give up and kill it. This must be >= circwindow
  426. * to avoid killing innocent circuits, and >= circwindow*2 to give
  427. * leaky-pipe a chance of working someday. The ORCIRC_MAX_MIDDLE_KILL_THRESH
  428. * ratio controls the margin of error between emitting a warning and
  429. * killing the circuit.
  430. */
  431. #define ORCIRC_MAX_MIDDLE_CELLS (CIRCWINDOW_START_MAX*2)
  432. /** Ratio of hard (circuit kill) to soft (warning) thresholds for the
  433. * ORCIRC_MAX_MIDDLE_CELLS tests.
  434. */
  435. #define ORCIRC_MAX_MIDDLE_KILL_THRESH (1.1f)
  436. /* Cell commands. These values are defined in tor-spec.txt. */
  437. #define CELL_PADDING 0
  438. #define CELL_CREATE 1
  439. #define CELL_CREATED 2
  440. #define CELL_RELAY 3
  441. #define CELL_DESTROY 4
  442. #define CELL_CREATE_FAST 5
  443. #define CELL_CREATED_FAST 6
  444. #define CELL_VERSIONS 7
  445. #define CELL_NETINFO 8
  446. #define CELL_RELAY_EARLY 9
  447. #define CELL_CREATE2 10
  448. #define CELL_CREATED2 11
  449. #define CELL_PADDING_NEGOTIATE 12
  450. #define CELL_VPADDING 128
  451. #define CELL_CERTS 129
  452. #define CELL_AUTH_CHALLENGE 130
  453. #define CELL_AUTHENTICATE 131
  454. #define CELL_AUTHORIZE 132
  455. #define CELL_COMMAND_MAX_ 132
  456. /** How long to test reachability before complaining to the user. */
  457. #define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT (20*60)
  458. /** Legal characters in a nickname. */
  459. #define LEGAL_NICKNAME_CHARACTERS \
  460. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  461. /** Name to use in client TLS certificates if no nickname is given. Once
  462. * Tor 0.1.2.x is obsolete, we can remove this. */
  463. #define DEFAULT_CLIENT_NICKNAME "client"
  464. /** Name chosen by routers that don't configure nicknames */
  465. #define UNNAMED_ROUTER_NICKNAME "Unnamed"
  466. /** Number of bytes in a SOCKS4 header. */
  467. #define SOCKS4_NETWORK_LEN 8
  468. /*
  469. * Relay payload:
  470. * Relay command [1 byte]
  471. * Recognized [2 bytes]
  472. * Stream ID [2 bytes]
  473. * Partial SHA-1 [4 bytes]
  474. * Length [2 bytes]
  475. * Relay payload [498 bytes]
  476. */
  477. /** Number of bytes in a cell, minus cell header. */
  478. #define CELL_PAYLOAD_SIZE 509
  479. /** Number of bytes in a cell transmitted over the network, in the longest
  480. * form */
  481. #define CELL_MAX_NETWORK_SIZE 514
  482. /** Maximum length of a header on a variable-length cell. */
  483. #define VAR_CELL_MAX_HEADER_SIZE 7
  484. static int get_cell_network_size(int wide_circ_ids);
  485. static inline int get_cell_network_size(int wide_circ_ids)
  486. {
  487. return wide_circ_ids ? CELL_MAX_NETWORK_SIZE : CELL_MAX_NETWORK_SIZE - 2;
  488. }
  489. static int get_var_cell_header_size(int wide_circ_ids);
  490. static inline int get_var_cell_header_size(int wide_circ_ids)
  491. {
  492. return wide_circ_ids ? VAR_CELL_MAX_HEADER_SIZE :
  493. VAR_CELL_MAX_HEADER_SIZE - 2;
  494. }
  495. static int get_circ_id_size(int wide_circ_ids);
  496. static inline int get_circ_id_size(int wide_circ_ids)
  497. {
  498. return wide_circ_ids ? 4 : 2;
  499. }
  500. /** Number of bytes in a relay cell's header (not including general cell
  501. * header). */
  502. #define RELAY_HEADER_SIZE (1+2+2+4+2)
  503. /** Largest number of bytes that can fit in a relay cell payload. */
  504. #define RELAY_PAYLOAD_SIZE (CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE)
  505. /** Identifies a circuit on an or_connection */
  506. typedef uint32_t circid_t;
  507. /** Identifies a stream on a circuit */
  508. typedef uint16_t streamid_t;
  509. /* channel_t typedef; struct channel_s is in channel.h */
  510. typedef struct channel_s channel_t;
  511. /* channel_listener_t typedef; struct channel_listener_s is in channel.h */
  512. typedef struct channel_listener_s channel_listener_t;
  513. /* TLS channel stuff */
  514. typedef struct channel_tls_s channel_tls_t;
  515. /* circuitmux_t typedef; struct circuitmux_s is in circuitmux.h */
  516. typedef struct circuitmux_s circuitmux_t;
  517. typedef struct cell_t cell_t;
  518. typedef struct var_cell_t var_cell_t;
  519. typedef struct packed_cell_t packed_cell_t;
  520. typedef struct cell_queue_t cell_queue_t;
  521. typedef struct destroy_cell_t destroy_cell_t;
  522. typedef struct destroy_cell_queue_t destroy_cell_queue_t;
  523. /** A parsed Extended ORPort message. */
  524. typedef struct ext_or_cmd_t {
  525. uint16_t cmd; /** Command type */
  526. uint16_t len; /** Body length */
  527. char body[FLEXIBLE_ARRAY_MEMBER]; /** Message body */
  528. } ext_or_cmd_t;
  529. /** Beginning of a RELAY cell payload. */
  530. typedef struct {
  531. uint8_t command; /**< The end-to-end relay command. */
  532. uint16_t recognized; /**< Used to tell whether cell is for us. */
  533. streamid_t stream_id; /**< Which stream is this cell associated with? */
  534. char integrity[4]; /**< Used to tell whether cell is corrupted. */
  535. uint16_t length; /**< How long is the payload body? */
  536. } relay_header_t;
  537. typedef struct socks_request_t socks_request_t;
  538. typedef struct entry_port_cfg_t entry_port_cfg_t;
  539. typedef struct server_port_cfg_t server_port_cfg_t;
  540. /** Minimum length of the random part of an AUTH_CHALLENGE cell. */
  541. #define OR_AUTH_CHALLENGE_LEN 32
  542. /**
  543. * @name Certificate types for CERTS cells.
  544. *
  545. * These values are defined by the protocol, and affect how an X509
  546. * certificate in a CERTS cell is interpreted and used.
  547. *
  548. * @{ */
  549. /** A certificate that authenticates a TLS link key. The subject key
  550. * must match the key used in the TLS handshake; it must be signed by
  551. * the identity key. */
  552. #define OR_CERT_TYPE_TLS_LINK 1
  553. /** A self-signed identity certificate. The subject key must be a
  554. * 1024-bit RSA key. */
  555. #define OR_CERT_TYPE_ID_1024 2
  556. /** A certificate that authenticates a key used in an AUTHENTICATE cell
  557. * in the v3 handshake. The subject key must be a 1024-bit RSA key; it
  558. * must be signed by the identity key */
  559. #define OR_CERT_TYPE_AUTH_1024 3
  560. /* DOCDOC */
  561. #define OR_CERT_TYPE_RSA_ED_CROSSCERT 7
  562. /**@}*/
  563. /** The first supported type of AUTHENTICATE cell. It contains
  564. * a bunch of structures signed with an RSA1024 key. The signed
  565. * structures include a HMAC using negotiated TLS secrets, and a digest
  566. * of all cells sent or received before the AUTHENTICATE cell (including
  567. * the random server-generated AUTH_CHALLENGE cell).
  568. */
  569. #define AUTHTYPE_RSA_SHA256_TLSSECRET 1
  570. /** As AUTHTYPE_RSA_SHA256_TLSSECRET, but instead of using the
  571. * negotiated TLS secrets, uses exported keying material from the TLS
  572. * session as described in RFC 5705.
  573. *
  574. * Not used by today's tors, since everything that supports this
  575. * also supports ED25519_SHA256_5705, which is better.
  576. **/
  577. #define AUTHTYPE_RSA_SHA256_RFC5705 2
  578. /** As AUTHTYPE_RSA_SHA256_RFC5705, but uses an Ed25519 identity key to
  579. * authenticate. */
  580. #define AUTHTYPE_ED25519_SHA256_RFC5705 3
  581. /*
  582. * NOTE: authchallenge_type_is_better() relies on these AUTHTYPE codes
  583. * being sorted in order of preference. If we someday add one with
  584. * a higher numerical value that we don't like as much, we should revise
  585. * authchallenge_type_is_better().
  586. */
  587. /** The length of the part of the AUTHENTICATE cell body that the client and
  588. * server can generate independently (when using RSA_SHA256_TLSSECRET). It
  589. * contains everything except the client's timestamp, the client's randomly
  590. * generated nonce, and the signature. */
  591. #define V3_AUTH_FIXED_PART_LEN (8+(32*6))
  592. /** The length of the part of the AUTHENTICATE cell body that the client
  593. * signs. */
  594. #define V3_AUTH_BODY_LEN (V3_AUTH_FIXED_PART_LEN + 8 + 16)
  595. typedef struct or_handshake_certs_t or_handshake_certs_t;
  596. typedef struct or_handshake_state_t or_handshake_state_t;
  597. /** Length of Extended ORPort connection identifier. */
  598. #define EXT_OR_CONN_ID_LEN DIGEST_LEN /* 20 */
  599. /*
  600. * OR_CONN_HIGHWATER and OR_CONN_LOWWATER moved from connection_or.c so
  601. * channeltls.c can see them too.
  602. */
  603. /** When adding cells to an OR connection's outbuf, keep adding until the
  604. * outbuf is at least this long, or we run out of cells. */
  605. #define OR_CONN_HIGHWATER (32*1024)
  606. /** Add cells to an OR connection's outbuf whenever the outbuf's data length
  607. * drops below this size. */
  608. #define OR_CONN_LOWWATER (16*1024)
  609. typedef struct connection_t connection_t;
  610. typedef struct control_connection_t control_connection_t;
  611. typedef struct dir_connection_t dir_connection_t;
  612. typedef struct edge_connection_t edge_connection_t;
  613. typedef struct entry_connection_t entry_connection_t;
  614. typedef struct listener_connection_t listener_connection_t;
  615. typedef struct or_connection_t or_connection_t;
  616. /** Cast a connection_t subtype pointer to a connection_t **/
  617. #define TO_CONN(c) (&(((c)->base_)))
  618. /** Cast a entry_connection_t subtype pointer to a connection_t **/
  619. #define ENTRY_TO_CONN(c) (TO_CONN(ENTRY_TO_EDGE_CONN(c)))
  620. typedef struct addr_policy_t addr_policy_t;
  621. typedef struct cached_dir_t cached_dir_t;
  622. /** Enum used to remember where a signed_descriptor_t is stored and how to
  623. * manage the memory for signed_descriptor_body. */
  624. typedef enum {
  625. /** The descriptor isn't stored on disk at all: the copy in memory is
  626. * canonical; the saved_offset field is meaningless. */
  627. SAVED_NOWHERE=0,
  628. /** The descriptor is stored in the cached_routers file: the
  629. * signed_descriptor_body is meaningless; the signed_descriptor_len and
  630. * saved_offset are used to index into the mmaped cache file. */
  631. SAVED_IN_CACHE,
  632. /** The descriptor is stored in the cached_routers.new file: the
  633. * signed_descriptor_body and saved_offset fields are both set. */
  634. /* FFFF (We could also mmap the file and grow the mmap as needed, or
  635. * lazy-load the descriptor text by using seek and read. We don't, for
  636. * now.)
  637. */
  638. SAVED_IN_JOURNAL
  639. } saved_location_t;
  640. #define saved_location_bitfield_t ENUM_BF(saved_location_t)
  641. /** Enumeration: what directory object is being downloaded?
  642. * This determines which schedule is selected to perform the download. */
  643. typedef enum {
  644. DL_SCHED_GENERIC = 0,
  645. DL_SCHED_CONSENSUS = 1,
  646. DL_SCHED_BRIDGE = 2,
  647. } download_schedule_t;
  648. #define download_schedule_bitfield_t ENUM_BF(download_schedule_t)
  649. /** Enumeration: is the download schedule for downloading from an authority,
  650. * or from any available directory mirror?
  651. * During bootstrap, "any" means a fallback (or an authority, if there
  652. * are no fallbacks).
  653. * When we have a valid consensus, "any" means any directory server. */
  654. typedef enum {
  655. DL_WANT_ANY_DIRSERVER = 0,
  656. DL_WANT_AUTHORITY = 1,
  657. } download_want_authority_t;
  658. #define download_want_authority_bitfield_t \
  659. ENUM_BF(download_want_authority_t)
  660. /** Enumeration: do we want to increment the schedule position each time a
  661. * connection is attempted (these attempts can be concurrent), or do we want
  662. * to increment the schedule position after a connection fails? */
  663. typedef enum {
  664. DL_SCHED_INCREMENT_FAILURE = 0,
  665. DL_SCHED_INCREMENT_ATTEMPT = 1,
  666. } download_schedule_increment_t;
  667. #define download_schedule_increment_bitfield_t \
  668. ENUM_BF(download_schedule_increment_t)
  669. typedef struct download_status_t download_status_t;
  670. /** If n_download_failures is this high, the download can never happen. */
  671. #define IMPOSSIBLE_TO_DOWNLOAD 255
  672. /** The max size we expect router descriptor annotations we create to
  673. * be. We'll accept larger ones if we see them on disk, but we won't
  674. * create any that are larger than this. */
  675. #define ROUTER_ANNOTATION_BUF_LEN 256
  676. typedef struct signed_descriptor_t signed_descriptor_t;
  677. /** A signed integer representing a country code. */
  678. typedef int16_t country_t;
  679. /** Flags used to summarize the declared protocol versions of a relay,
  680. * so we don't need to parse them again and again. */
  681. typedef struct protover_summary_flags_t {
  682. /** True iff we have a proto line for this router, or a versions line
  683. * from which we could infer the protocols. */
  684. unsigned int protocols_known:1;
  685. /** True iff this router has a version or protocol list that allows it to
  686. * accept EXTEND2 cells. This requires Relay=2. */
  687. unsigned int supports_extend2_cells:1;
  688. /** True iff this router has a protocol list that allows it to negotiate
  689. * ed25519 identity keys on a link handshake with us. This
  690. * requires LinkAuth=3. */
  691. unsigned int supports_ed25519_link_handshake_compat:1;
  692. /** True iff this router has a protocol list that allows it to negotiate
  693. * ed25519 identity keys on a link handshake, at all. This requires some
  694. * LinkAuth=X for X >= 3. */
  695. unsigned int supports_ed25519_link_handshake_any:1;
  696. /** True iff this router has a protocol list that allows it to be an
  697. * introduction point supporting ed25519 authentication key which is part of
  698. * the v3 protocol detailed in proposal 224. This requires HSIntro=4. */
  699. unsigned int supports_ed25519_hs_intro : 1;
  700. /** True iff this router has a protocol list that allows it to be an hidden
  701. * service directory supporting version 3 as seen in proposal 224. This
  702. * requires HSDir=2. */
  703. unsigned int supports_v3_hsdir : 1;
  704. /** True iff this router has a protocol list that allows it to be an hidden
  705. * service rendezvous point supporting version 3 as seen in proposal 224.
  706. * This requires HSRend=2. */
  707. unsigned int supports_v3_rendezvous_point: 1;
  708. } protover_summary_flags_t;
  709. typedef struct routerinfo_t routerinfo_t;
  710. typedef struct extrainfo_t extrainfo_t;
  711. typedef struct routerstatus_t routerstatus_t;
  712. typedef struct microdesc_t microdesc_t;
  713. typedef struct node_t node_t;
  714. typedef struct vote_microdesc_hash_t vote_microdesc_hash_t;
  715. typedef struct vote_routerstatus_t vote_routerstatus_t;
  716. typedef struct document_signature_t document_signature_t;
  717. typedef struct networkstatus_voter_info_t networkstatus_voter_info_t;
  718. typedef struct networkstatus_sr_info_t networkstatus_sr_info_t;
  719. /** Enumerates recognized flavors of a consensus networkstatus document. All
  720. * flavors of a consensus are generated from the same set of votes, but they
  721. * present different types information to different versions of Tor. */
  722. typedef enum {
  723. FLAV_NS = 0,
  724. FLAV_MICRODESC = 1,
  725. } consensus_flavor_t;
  726. /** How many different consensus flavors are there? */
  727. #define N_CONSENSUS_FLAVORS ((int)(FLAV_MICRODESC)+1)
  728. typedef struct networkstatus_t networkstatus_t;
  729. typedef struct ns_detached_signatures_t ns_detached_signatures_t;
  730. /** Allowable types of desc_store_t. */
  731. typedef enum store_type_t {
  732. ROUTER_STORE = 0,
  733. EXTRAINFO_STORE = 1
  734. } store_type_t;
  735. typedef struct desc_store_t desc_store_t;
  736. typedef struct routerlist_t routerlist_t;
  737. typedef struct extend_info_t extend_info_t;
  738. typedef struct authority_cert_t authority_cert_t;
  739. /** Bitfield enum type listing types of information that directory authorities
  740. * can be authoritative about, and that directory caches may or may not cache.
  741. *
  742. * Note that the granularity here is based on authority granularity and on
  743. * cache capabilities. Thus, one particular bit may correspond in practice to
  744. * a few types of directory info, so long as every authority that pronounces
  745. * officially about one of the types prounounces officially about all of them,
  746. * and so long as every cache that caches one of them caches all of them.
  747. */
  748. typedef enum {
  749. NO_DIRINFO = 0,
  750. /** Serves/signs v3 directory information: votes, consensuses, certs */
  751. V3_DIRINFO = 1 << 2,
  752. /** Serves bridge descriptors. */
  753. BRIDGE_DIRINFO = 1 << 4,
  754. /** Serves extrainfo documents. */
  755. EXTRAINFO_DIRINFO=1 << 5,
  756. /** Serves microdescriptors. */
  757. MICRODESC_DIRINFO=1 << 6,
  758. } dirinfo_type_t;
  759. #define ALL_DIRINFO ((dirinfo_type_t)((1<<7)-1))
  760. #define CRYPT_PATH_MAGIC 0x70127012u
  761. struct fast_handshake_state_t;
  762. struct ntor_handshake_state_t;
  763. struct crypto_dh_t;
  764. #define ONION_HANDSHAKE_TYPE_TAP 0x0000
  765. #define ONION_HANDSHAKE_TYPE_FAST 0x0001
  766. #define ONION_HANDSHAKE_TYPE_NTOR 0x0002
  767. #define MAX_ONION_HANDSHAKE_TYPE 0x0002
  768. typedef struct {
  769. uint16_t tag;
  770. union {
  771. struct fast_handshake_state_t *fast;
  772. struct crypto_dh_t *tap;
  773. struct ntor_handshake_state_t *ntor;
  774. } u;
  775. } onion_handshake_state_t;
  776. typedef struct relay_crypto_t relay_crypto_t;
  777. typedef struct crypt_path_t crypt_path_t;
  778. typedef struct crypt_path_reference_t crypt_path_reference_t;
  779. #define CPATH_KEY_MATERIAL_LEN (20*2+16*2)
  780. typedef struct cpath_build_state_t cpath_build_state_t;
  781. struct create_cell_t;
  782. /** Entry in the cell stats list of a circuit; used only if CELL_STATS
  783. * events are enabled. */
  784. typedef struct testing_cell_stats_entry_t {
  785. uint8_t command; /**< cell command number. */
  786. /** Waiting time in centiseconds if this event is for a removed cell,
  787. * or 0 if this event is for adding a cell to the queue. 22 bits can
  788. * store more than 11 hours, enough to assume that a circuit with this
  789. * delay would long have been closed. */
  790. unsigned int waiting_time:22;
  791. unsigned int removed:1; /**< 0 for added to, 1 for removed from queue. */
  792. unsigned int exitward:1; /**< 0 for app-ward, 1 for exit-ward. */
  793. } testing_cell_stats_entry_t;
  794. typedef struct circuit_t circuit_t;
  795. typedef struct origin_circuit_t origin_circuit_t;
  796. typedef struct or_circuit_t or_circuit_t;
  797. /** Largest number of relay_early cells that we can send on a given
  798. * circuit. */
  799. #define MAX_RELAY_EARLY_CELLS_PER_CIRCUIT 8
  800. /**
  801. * Describes the circuit building process in simplified terms based
  802. * on the path bias accounting state for a circuit.
  803. *
  804. * NOTE: These state values are enumerated in the order for which we
  805. * expect circuits to transition through them. If you add states,
  806. * you need to preserve this overall ordering. The various pathbias
  807. * state transition and accounting functions (pathbias_mark_* and
  808. * pathbias_count_*) contain ordinal comparisons to enforce proper
  809. * state transitions for corrections.
  810. *
  811. * This state machine and the associated logic was created to prevent
  812. * miscounting due to unknown cases of circuit reuse. See also tickets
  813. * #6475 and #7802.
  814. */
  815. typedef enum {
  816. /** This circuit is "new". It has not yet completed a first hop
  817. * or been counted by the path bias code. */
  818. PATH_STATE_NEW_CIRC = 0,
  819. /** This circuit has completed one/two hops, and has been counted by
  820. * the path bias logic. */
  821. PATH_STATE_BUILD_ATTEMPTED = 1,
  822. /** This circuit has been completely built */
  823. PATH_STATE_BUILD_SUCCEEDED = 2,
  824. /** Did we try to attach any SOCKS streams or hidserv introductions to
  825. * this circuit?
  826. *
  827. * Note: If we ever implement end-to-end stream timing through test
  828. * stream probes (#5707), we must *not* set this for those probes
  829. * (or any other automatic streams) because the adversary could
  830. * just tag at a later point.
  831. */
  832. PATH_STATE_USE_ATTEMPTED = 3,
  833. /** Did any SOCKS streams or hidserv introductions actually succeed on
  834. * this circuit?
  835. *
  836. * If any streams detatch/fail from this circuit, the code transitions
  837. * the circuit back to PATH_STATE_USE_ATTEMPTED to ensure we probe. See
  838. * pathbias_mark_use_rollback() for that.
  839. */
  840. PATH_STATE_USE_SUCCEEDED = 4,
  841. /**
  842. * This is a special state to indicate that we got a corrupted
  843. * relay cell on a circuit and we don't intend to probe it.
  844. */
  845. PATH_STATE_USE_FAILED = 5,
  846. /**
  847. * This is a special state to indicate that we already counted
  848. * the circuit. Used to guard against potential state machine
  849. * violations.
  850. */
  851. PATH_STATE_ALREADY_COUNTED = 6,
  852. } path_state_t;
  853. #define path_state_bitfield_t ENUM_BF(path_state_t)
  854. #if REND_COOKIE_LEN != DIGEST_LEN
  855. #error "The REND_TOKEN_LEN macro assumes REND_COOKIE_LEN == DIGEST_LEN"
  856. #endif
  857. #define REND_TOKEN_LEN DIGEST_LEN
  858. /** Convert a circuit subtype to a circuit_t. */
  859. #define TO_CIRCUIT(x) (&((x)->base_))
  860. /** @name Isolation flags
  861. Ways to isolate client streams
  862. @{
  863. */
  864. /** Isolate based on destination port */
  865. #define ISO_DESTPORT (1u<<0)
  866. /** Isolate based on destination address */
  867. #define ISO_DESTADDR (1u<<1)
  868. /** Isolate based on SOCKS authentication */
  869. #define ISO_SOCKSAUTH (1u<<2)
  870. /** Isolate based on client protocol choice */
  871. #define ISO_CLIENTPROTO (1u<<3)
  872. /** Isolate based on client address */
  873. #define ISO_CLIENTADDR (1u<<4)
  874. /** Isolate based on session group (always on). */
  875. #define ISO_SESSIONGRP (1u<<5)
  876. /** Isolate based on newnym epoch (always on). */
  877. #define ISO_NYM_EPOCH (1u<<6)
  878. /** Isolate all streams (Internal only). */
  879. #define ISO_STREAM (1u<<7)
  880. /**@}*/
  881. /** Default isolation level for ports. */
  882. #define ISO_DEFAULT (ISO_CLIENTADDR|ISO_SOCKSAUTH|ISO_SESSIONGRP|ISO_NYM_EPOCH)
  883. /** Indicates that we haven't yet set a session group on a port_cfg_t. */
  884. #define SESSION_GROUP_UNSET -1
  885. /** Session group reserved for directory connections */
  886. #define SESSION_GROUP_DIRCONN -2
  887. /** Session group reserved for resolve requests launched by a controller */
  888. #define SESSION_GROUP_CONTROL_RESOLVE -3
  889. /** First automatically allocated session group number */
  890. #define SESSION_GROUP_FIRST_AUTO -4
  891. typedef struct port_cfg_t port_cfg_t;
  892. typedef struct routerset_t routerset_t;
  893. /** A magic value for the (Socks|OR|...)Port options below, telling Tor
  894. * to pick its own port. */
  895. #define CFG_AUTO_PORT 0xc4005e
  896. /** Enumeration of outbound address configuration types:
  897. * Exit-only, OR-only, or both */
  898. typedef enum {OUTBOUND_ADDR_EXIT, OUTBOUND_ADDR_OR,
  899. OUTBOUND_ADDR_EXIT_AND_OR,
  900. OUTBOUND_ADDR_MAX} outbound_addr_t;
  901. struct config_line_t;
  902. /** Configuration options for a Tor process. */
  903. typedef struct {
  904. uint32_t magic_;
  905. /** What should the tor process actually do? */
  906. enum {
  907. CMD_RUN_TOR=0, CMD_LIST_FINGERPRINT, CMD_HASH_PASSWORD,
  908. CMD_VERIFY_CONFIG, CMD_RUN_UNITTESTS, CMD_DUMP_CONFIG,
  909. CMD_KEYGEN,
  910. CMD_KEY_EXPIRATION,
  911. } command;
  912. char *command_arg; /**< Argument for command-line option. */
  913. struct config_line_t *Logs; /**< New-style list of configuration lines
  914. * for logs */
  915. int LogTimeGranularity; /**< Log resolution in milliseconds. */
  916. int LogMessageDomains; /**< Boolean: Should we log the domain(s) in which
  917. * each log message occurs? */
  918. int TruncateLogFile; /**< Boolean: Should we truncate the log file
  919. before we start writing? */
  920. char *SyslogIdentityTag; /**< Identity tag to add for syslog logging. */
  921. char *AndroidIdentityTag; /**< Identity tag to add for Android logging. */
  922. char *DebugLogFile; /**< Where to send verbose log messages. */
  923. char *DataDirectory_option; /**< Where to store long-term data, as
  924. * configured by the user. */
  925. char *DataDirectory; /**< Where to store long-term data, as modified. */
  926. int DataDirectoryGroupReadable; /**< Boolean: Is the DataDirectory g+r? */
  927. char *KeyDirectory_option; /**< Where to store keys, as
  928. * configured by the user. */
  929. char *KeyDirectory; /**< Where to store keys data, as modified. */
  930. int KeyDirectoryGroupReadable; /**< Boolean: Is the KeyDirectory g+r? */
  931. char *CacheDirectory_option; /**< Where to store cached data, as
  932. * configured by the user. */
  933. char *CacheDirectory; /**< Where to store cached data, as modified. */
  934. int CacheDirectoryGroupReadable; /**< Boolean: Is the CacheDirectory g+r? */
  935. char *Nickname; /**< OR only: nickname of this onion router. */
  936. char *Address; /**< OR only: configured address for this onion router. */
  937. char *PidFile; /**< Where to store PID of Tor process. */
  938. routerset_t *ExitNodes; /**< Structure containing nicknames, digests,
  939. * country codes and IP address patterns of ORs to
  940. * consider as exits. */
  941. routerset_t *EntryNodes;/**< Structure containing nicknames, digests,
  942. * country codes and IP address patterns of ORs to
  943. * consider as entry points. */
  944. int StrictNodes; /**< Boolean: When none of our EntryNodes or ExitNodes
  945. * are up, or we need to access a node in ExcludeNodes,
  946. * do we just fail instead? */
  947. routerset_t *ExcludeNodes;/**< Structure containing nicknames, digests,
  948. * country codes and IP address patterns of ORs
  949. * not to use in circuits. But see StrictNodes
  950. * above. */
  951. routerset_t *ExcludeExitNodes;/**< Structure containing nicknames, digests,
  952. * country codes and IP address patterns of
  953. * ORs not to consider as exits. */
  954. /** Union of ExcludeNodes and ExcludeExitNodes */
  955. routerset_t *ExcludeExitNodesUnion_;
  956. int DisableAllSwap; /**< Boolean: Attempt to call mlockall() on our
  957. * process for all current and future memory. */
  958. struct config_line_t *ExitPolicy; /**< Lists of exit policy components. */
  959. int ExitPolicyRejectPrivate; /**< Should we not exit to reserved private
  960. * addresses, and our own published addresses?
  961. */
  962. int ExitPolicyRejectLocalInterfaces; /**< Should we not exit to local
  963. * interface addresses?
  964. * Includes OutboundBindAddresses and
  965. * configured ports. */
  966. int ReducedExitPolicy; /**<Should we use the Reduced Exit Policy? */
  967. struct config_line_t *SocksPolicy; /**< Lists of socks policy components */
  968. struct config_line_t *DirPolicy; /**< Lists of dir policy components */
  969. /** Local address to bind outbound sockets */
  970. struct config_line_t *OutboundBindAddress;
  971. /** Local address to bind outbound relay sockets */
  972. struct config_line_t *OutboundBindAddressOR;
  973. /** Local address to bind outbound exit sockets */
  974. struct config_line_t *OutboundBindAddressExit;
  975. /** Addresses derived from the various OutboundBindAddress lines.
  976. * [][0] is IPv4, [][1] is IPv6
  977. */
  978. tor_addr_t OutboundBindAddresses[OUTBOUND_ADDR_MAX][2];
  979. /** Directory server only: which versions of
  980. * Tor should we tell users to run? */
  981. struct config_line_t *RecommendedVersions;
  982. struct config_line_t *RecommendedClientVersions;
  983. struct config_line_t *RecommendedServerVersions;
  984. struct config_line_t *RecommendedPackages;
  985. /** Whether dirservers allow router descriptors with private IPs. */
  986. int DirAllowPrivateAddresses;
  987. /** Whether routers accept EXTEND cells to routers with private IPs. */
  988. int ExtendAllowPrivateAddresses;
  989. char *User; /**< Name of user to run Tor as. */
  990. /** Ports to listen on for OR connections. */
  991. struct config_line_t *ORPort_lines;
  992. /** Ports to listen on for extended OR connections. */
  993. struct config_line_t *ExtORPort_lines;
  994. /** Ports to listen on for SOCKS connections. */
  995. struct config_line_t *SocksPort_lines;
  996. /** Ports to listen on for transparent pf/netfilter connections. */
  997. struct config_line_t *TransPort_lines;
  998. char *TransProxyType; /**< What kind of transparent proxy
  999. * implementation are we using? */
  1000. /** Parsed value of TransProxyType. */
  1001. enum {
  1002. TPT_DEFAULT,
  1003. TPT_PF_DIVERT,
  1004. TPT_IPFW,
  1005. TPT_TPROXY,
  1006. } TransProxyType_parsed;
  1007. /** Ports to listen on for transparent natd connections. */
  1008. struct config_line_t *NATDPort_lines;
  1009. /** Ports to listen on for HTTP Tunnel connections. */
  1010. struct config_line_t *HTTPTunnelPort_lines;
  1011. struct config_line_t *ControlPort_lines; /**< Ports to listen on for control
  1012. * connections. */
  1013. /** List of Unix Domain Sockets to listen on for control connections. */
  1014. struct config_line_t *ControlSocket;
  1015. int ControlSocketsGroupWritable; /**< Boolean: Are control sockets g+rw? */
  1016. int UnixSocksGroupWritable; /**< Boolean: Are SOCKS Unix sockets g+rw? */
  1017. /** Ports to listen on for directory connections. */
  1018. struct config_line_t *DirPort_lines;
  1019. /** Ports to listen on for DNS requests. */
  1020. struct config_line_t *DNSPort_lines;
  1021. /* MaxMemInQueues value as input by the user. We clean this up to be
  1022. * MaxMemInQueues. */
  1023. uint64_t MaxMemInQueues_raw;
  1024. uint64_t MaxMemInQueues;/**< If we have more memory than this allocated
  1025. * for queues and buffers, run the OOM handler */
  1026. /** Above this value, consider ourselves low on RAM. */
  1027. uint64_t MaxMemInQueues_low_threshold;
  1028. /** @name port booleans
  1029. *
  1030. * Derived booleans: For server ports and ControlPort, true iff there is a
  1031. * non-listener port on an AF_INET or AF_INET6 address of the given type
  1032. * configured in one of the _lines options above.
  1033. * For client ports, also true if there is a unix socket configured.
  1034. * If you are checking for client ports, you may want to use:
  1035. * SocksPort_set || TransPort_set || NATDPort_set || DNSPort_set ||
  1036. * HTTPTunnelPort_set
  1037. * rather than SocksPort_set.
  1038. *
  1039. * @{
  1040. */
  1041. unsigned int ORPort_set : 1;
  1042. unsigned int SocksPort_set : 1;
  1043. unsigned int TransPort_set : 1;
  1044. unsigned int NATDPort_set : 1;
  1045. unsigned int ControlPort_set : 1;
  1046. unsigned int DirPort_set : 1;
  1047. unsigned int DNSPort_set : 1;
  1048. unsigned int ExtORPort_set : 1;
  1049. unsigned int HTTPTunnelPort_set : 1;
  1050. /**@}*/
  1051. int AssumeReachable; /**< Whether to publish our descriptor regardless. */
  1052. int AuthoritativeDir; /**< Boolean: is this an authoritative directory? */
  1053. int V3AuthoritativeDir; /**< Boolean: is this an authoritative directory
  1054. * for version 3 directories? */
  1055. int VersioningAuthoritativeDir; /**< Boolean: is this an authoritative
  1056. * directory that's willing to recommend
  1057. * versions? */
  1058. int BridgeAuthoritativeDir; /**< Boolean: is this an authoritative directory
  1059. * that aggregates bridge descriptors? */
  1060. /** If set on a bridge relay, it will include this value on a new
  1061. * "bridge-distribution-request" line in its bridge descriptor. */
  1062. char *BridgeDistribution;
  1063. /** If set on a bridge authority, it will answer requests on its dirport
  1064. * for bridge statuses -- but only if the requests use this password. */
  1065. char *BridgePassword;
  1066. /** If BridgePassword is set, this is a SHA256 digest of the basic http
  1067. * authenticator for it. Used so we can do a time-independent comparison. */
  1068. char *BridgePassword_AuthDigest_;
  1069. int UseBridges; /**< Boolean: should we start all circuits with a bridge? */
  1070. struct config_line_t *Bridges; /**< List of bootstrap bridge addresses. */
  1071. struct config_line_t *ClientTransportPlugin; /**< List of client
  1072. transport plugins. */
  1073. struct config_line_t *ServerTransportPlugin; /**< List of client
  1074. transport plugins. */
  1075. /** List of TCP/IP addresses that transports should listen at. */
  1076. struct config_line_t *ServerTransportListenAddr;
  1077. /** List of options that must be passed to pluggable transports. */
  1078. struct config_line_t *ServerTransportOptions;
  1079. int BridgeRelay; /**< Boolean: are we acting as a bridge relay? We make
  1080. * this explicit so we can change how we behave in the
  1081. * future. */
  1082. /** Boolean: if we know the bridge's digest, should we get new
  1083. * descriptors from the bridge authorities or from the bridge itself? */
  1084. int UpdateBridgesFromAuthority;
  1085. int AvoidDiskWrites; /**< Boolean: should we never cache things to disk?
  1086. * Not used yet. */
  1087. int ClientOnly; /**< Boolean: should we never evolve into a server role? */
  1088. int ReducedConnectionPadding; /**< Boolean: Should we try to keep connections
  1089. open shorter and pad them less against
  1090. connection-level traffic analysis? */
  1091. /** Autobool: if auto, then connection padding will be negotiated by client
  1092. * and server. If 0, it will be fully disabled. If 1, the client will still
  1093. * pad to the server regardless of server support. */
  1094. int ConnectionPadding;
  1095. /** To what authority types do we publish our descriptor? Choices are
  1096. * "v1", "v2", "v3", "bridge", or "". */
  1097. smartlist_t *PublishServerDescriptor;
  1098. /** A bitfield of authority types, derived from PublishServerDescriptor. */
  1099. dirinfo_type_t PublishServerDescriptor_;
  1100. /** Boolean: do we publish hidden service descriptors to the HS auths? */
  1101. int PublishHidServDescriptors;
  1102. int FetchServerDescriptors; /**< Do we fetch server descriptors as normal? */
  1103. int FetchHidServDescriptors; /**< and hidden service descriptors? */
  1104. int MinUptimeHidServDirectoryV2; /**< As directory authority, accept hidden
  1105. * service directories after what time? */
  1106. int FetchUselessDescriptors; /**< Do we fetch non-running descriptors too? */
  1107. int AllDirActionsPrivate; /**< Should every directory action be sent
  1108. * through a Tor circuit? */
  1109. /** Run in 'tor2web mode'? (I.e. only make client connections to hidden
  1110. * services, and use a single hop for all hidden-service-related
  1111. * circuits.) */
  1112. int Tor2webMode;
  1113. /** A routerset that should be used when picking RPs for HS circuits. */
  1114. routerset_t *Tor2webRendezvousPoints;
  1115. /** A routerset that should be used when picking middle nodes for HS
  1116. * circuits. */
  1117. routerset_t *HSLayer2Nodes;
  1118. /** A routerset that should be used when picking third-hop nodes for HS
  1119. * circuits. */
  1120. routerset_t *HSLayer3Nodes;
  1121. /** Onion Services in HiddenServiceSingleHopMode make one-hop (direct)
  1122. * circuits between the onion service server, and the introduction and
  1123. * rendezvous points. (Onion service descriptors are still posted using
  1124. * 3-hop paths, to avoid onion service directories blocking the service.)
  1125. * This option makes every hidden service instance hosted by
  1126. * this tor instance a Single Onion Service.
  1127. * HiddenServiceSingleHopMode requires HiddenServiceNonAnonymousMode to be
  1128. * set to 1.
  1129. * Use rend_service_allow_non_anonymous_connection() or
  1130. * rend_service_reveal_startup_time() instead of using this option directly.
  1131. */
  1132. int HiddenServiceSingleHopMode;
  1133. /* Makes hidden service clients and servers non-anonymous on this tor
  1134. * instance. Allows the non-anonymous HiddenServiceSingleHopMode. Enables
  1135. * non-anonymous behaviour in the hidden service protocol.
  1136. * Use rend_service_non_anonymous_mode_enabled() instead of using this option
  1137. * directly.
  1138. */
  1139. int HiddenServiceNonAnonymousMode;
  1140. int ConnLimit; /**< Demanded minimum number of simultaneous connections. */
  1141. int ConnLimit_; /**< Maximum allowed number of simultaneous connections. */
  1142. int ConnLimit_high_thresh; /**< start trying to lower socket usage if we
  1143. * have this many. */
  1144. int ConnLimit_low_thresh; /**< try to get down to here after socket
  1145. * exhaustion. */
  1146. int RunAsDaemon; /**< If true, run in the background. (Unix only) */
  1147. int FascistFirewall; /**< Whether to prefer ORs reachable on open ports. */
  1148. smartlist_t *FirewallPorts; /**< Which ports our firewall allows
  1149. * (strings). */
  1150. /** IP:ports our firewall allows. */
  1151. struct config_line_t *ReachableAddresses;
  1152. struct config_line_t *ReachableORAddresses; /**< IP:ports for OR conns. */
  1153. struct config_line_t *ReachableDirAddresses; /**< IP:ports for Dir conns. */
  1154. int ConstrainedSockets; /**< Shrink xmit and recv socket buffers. */
  1155. uint64_t ConstrainedSockSize; /**< Size of constrained buffers. */
  1156. /** Whether we should drop exit streams from Tors that we don't know are
  1157. * relays. One of "0" (never refuse), "1" (always refuse), or "-1" (do
  1158. * what the consensus says, defaulting to 'refuse' if the consensus says
  1159. * nothing). */
  1160. int RefuseUnknownExits;
  1161. /** Application ports that require all nodes in circ to have sufficient
  1162. * uptime. */
  1163. smartlist_t *LongLivedPorts;
  1164. /** Application ports that are likely to be unencrypted and
  1165. * unauthenticated; we reject requests for them to prevent the
  1166. * user from screwing up and leaking plaintext secrets to an
  1167. * observer somewhere on the Internet. */
  1168. smartlist_t *RejectPlaintextPorts;
  1169. /** Related to RejectPlaintextPorts above, except this config option
  1170. * controls whether we warn (in the log and via a controller status
  1171. * event) every time a risky connection is attempted. */
  1172. smartlist_t *WarnPlaintextPorts;
  1173. /** Should we try to reuse the same exit node for a given host */
  1174. smartlist_t *TrackHostExits;
  1175. int TrackHostExitsExpire; /**< Number of seconds until we expire an
  1176. * addressmap */
  1177. struct config_line_t *AddressMap; /**< List of address map directives. */
  1178. int AutomapHostsOnResolve; /**< If true, when we get a resolve request for a
  1179. * hostname ending with one of the suffixes in
  1180. * <b>AutomapHostsSuffixes</b>, map it to a
  1181. * virtual address. */
  1182. /** List of suffixes for <b>AutomapHostsOnResolve</b>. The special value
  1183. * "." means "match everything." */
  1184. smartlist_t *AutomapHostsSuffixes;
  1185. int RendPostPeriod; /**< How often do we post each rendezvous service
  1186. * descriptor? Remember to publish them independently. */
  1187. int KeepalivePeriod; /**< How often do we send padding cells to keep
  1188. * connections alive? */
  1189. int SocksTimeout; /**< How long do we let a socks connection wait
  1190. * unattached before we fail it? */
  1191. int LearnCircuitBuildTimeout; /**< If non-zero, we attempt to learn a value
  1192. * for CircuitBuildTimeout based on timeout
  1193. * history. Use circuit_build_times_disabled()
  1194. * rather than checking this value directly. */
  1195. int CircuitBuildTimeout; /**< Cull non-open circuits that were born at
  1196. * least this many seconds ago. Used until
  1197. * adaptive algorithm learns a new value. */
  1198. int CircuitsAvailableTimeout; /**< Try to have an open circuit for at
  1199. least this long after last activity */
  1200. int CircuitStreamTimeout; /**< If non-zero, detach streams from circuits
  1201. * and try a new circuit if the stream has been
  1202. * waiting for this many seconds. If zero, use
  1203. * our default internal timeout schedule. */
  1204. int MaxOnionQueueDelay; /*< DOCDOC */
  1205. int NewCircuitPeriod; /**< How long do we use a circuit before building
  1206. * a new one? */
  1207. int MaxCircuitDirtiness; /**< Never use circs that were first used more than
  1208. this interval ago. */
  1209. uint64_t BandwidthRate; /**< How much bandwidth, on average, are we willing
  1210. * to use in a second? */
  1211. uint64_t BandwidthBurst; /**< How much bandwidth, at maximum, are we willing
  1212. * to use in a second? */
  1213. uint64_t MaxAdvertisedBandwidth; /**< How much bandwidth are we willing to
  1214. * tell other nodes we have? */
  1215. uint64_t RelayBandwidthRate; /**< How much bandwidth, on average, are we
  1216. * willing to use for all relayed conns? */
  1217. uint64_t RelayBandwidthBurst; /**< How much bandwidth, at maximum, will we
  1218. * use in a second for all relayed conns? */
  1219. uint64_t PerConnBWRate; /**< Long-term bw on a single TLS conn, if set. */
  1220. uint64_t PerConnBWBurst; /**< Allowed burst on a single TLS conn, if set. */
  1221. int NumCPUs; /**< How many CPUs should we try to use? */
  1222. struct config_line_t *RendConfigLines; /**< List of configuration lines
  1223. * for rendezvous services. */
  1224. struct config_line_t *HidServAuth; /**< List of configuration lines for
  1225. * client-side authorizations for hidden
  1226. * services */
  1227. char *ContactInfo; /**< Contact info to be published in the directory. */
  1228. int HeartbeatPeriod; /**< Log heartbeat messages after this many seconds
  1229. * have passed. */
  1230. int MainloopStats; /**< Log main loop statistics as part of the
  1231. * heartbeat messages. */
  1232. char *HTTPProxy; /**< hostname[:port] to use as http proxy, if any. */
  1233. tor_addr_t HTTPProxyAddr; /**< Parsed IPv4 addr for http proxy, if any. */
  1234. uint16_t HTTPProxyPort; /**< Parsed port for http proxy, if any. */
  1235. char *HTTPProxyAuthenticator; /**< username:password string, if any. */
  1236. char *HTTPSProxy; /**< hostname[:port] to use as https proxy, if any. */
  1237. tor_addr_t HTTPSProxyAddr; /**< Parsed addr for https proxy, if any. */
  1238. uint16_t HTTPSProxyPort; /**< Parsed port for https proxy, if any. */
  1239. char *HTTPSProxyAuthenticator; /**< username:password string, if any. */
  1240. char *Socks4Proxy; /**< hostname:port to use as a SOCKS4 proxy, if any. */
  1241. tor_addr_t Socks4ProxyAddr; /**< Derived from Socks4Proxy. */
  1242. uint16_t Socks4ProxyPort; /**< Derived from Socks4Proxy. */
  1243. char *Socks5Proxy; /**< hostname:port to use as a SOCKS5 proxy, if any. */
  1244. tor_addr_t Socks5ProxyAddr; /**< Derived from Sock5Proxy. */
  1245. uint16_t Socks5ProxyPort; /**< Derived from Socks5Proxy. */
  1246. char *Socks5ProxyUsername; /**< Username for SOCKS5 authentication, if any */
  1247. char *Socks5ProxyPassword; /**< Password for SOCKS5 authentication, if any */
  1248. /** List of configuration lines for replacement directory authorities.
  1249. * If you just want to replace one class of authority at a time,
  1250. * use the "Alternate*Authority" options below instead. */
  1251. struct config_line_t *DirAuthorities;
  1252. /** List of fallback directory servers */
  1253. struct config_line_t *FallbackDir;
  1254. /** Whether to use the default hard-coded FallbackDirs */
  1255. int UseDefaultFallbackDirs;
  1256. /** Weight to apply to all directory authority rates if considering them
  1257. * along with fallbackdirs */
  1258. double DirAuthorityFallbackRate;
  1259. /** If set, use these main (currently v3) directory authorities and
  1260. * not the default ones. */
  1261. struct config_line_t *AlternateDirAuthority;
  1262. /** If set, use these bridge authorities and not the default one. */
  1263. struct config_line_t *AlternateBridgeAuthority;
  1264. struct config_line_t *MyFamily_lines; /**< Declared family for this OR. */
  1265. struct config_line_t *MyFamily; /**< Declared family for this OR,
  1266. normalized */
  1267. struct config_line_t *NodeFamilies; /**< List of config lines for
  1268. * node families */
  1269. smartlist_t *NodeFamilySets; /**< List of parsed NodeFamilies values. */
  1270. struct config_line_t *AuthDirBadExit; /**< Address policy for descriptors to
  1271. * mark as bad exits. */
  1272. struct config_line_t *AuthDirReject; /**< Address policy for descriptors to
  1273. * reject. */
  1274. struct config_line_t *AuthDirInvalid; /**< Address policy for descriptors to
  1275. * never mark as valid. */
  1276. /** @name AuthDir...CC
  1277. *
  1278. * Lists of country codes to mark as BadExit, or Invalid, or to
  1279. * reject entirely.
  1280. *
  1281. * @{
  1282. */
  1283. smartlist_t *AuthDirBadExitCCs;
  1284. smartlist_t *AuthDirInvalidCCs;
  1285. smartlist_t *AuthDirRejectCCs;
  1286. /**@}*/
  1287. int AuthDirListBadExits; /**< True iff we should list bad exits,
  1288. * and vote for all other exits as good. */
  1289. int AuthDirMaxServersPerAddr; /**< Do not permit more than this
  1290. * number of servers per IP address. */
  1291. int AuthDirHasIPv6Connectivity; /**< Boolean: are we on IPv6? */
  1292. int AuthDirPinKeys; /**< Boolean: Do we enforce key-pinning? */
  1293. /** If non-zero, always vote the Fast flag for any relay advertising
  1294. * this amount of capacity or more. */
  1295. uint64_t AuthDirFastGuarantee;
  1296. /** If non-zero, this advertised capacity or more is always sufficient
  1297. * to satisfy the bandwidth requirement for the Guard flag. */
  1298. uint64_t AuthDirGuardBWGuarantee;
  1299. char *AccountingStart; /**< How long is the accounting interval, and when
  1300. * does it start? */
  1301. uint64_t AccountingMax; /**< How many bytes do we allow per accounting
  1302. * interval before hibernation? 0 for "never
  1303. * hibernate." */
  1304. /** How do we determine when our AccountingMax has been reached?
  1305. * "max" for when in or out reaches AccountingMax
  1306. * "sum" for when in plus out reaches AccountingMax
  1307. * "in" for when in reaches AccountingMax
  1308. * "out" for when out reaches AccountingMax */
  1309. char *AccountingRule_option;
  1310. enum { ACCT_MAX, ACCT_SUM, ACCT_IN, ACCT_OUT } AccountingRule;
  1311. /** Base64-encoded hash of accepted passwords for the control system. */
  1312. struct config_line_t *HashedControlPassword;
  1313. /** As HashedControlPassword, but not saved. */
  1314. struct config_line_t *HashedControlSessionPassword;
  1315. int CookieAuthentication; /**< Boolean: do we enable cookie-based auth for
  1316. * the control system? */
  1317. char *CookieAuthFile; /**< Filesystem location of a ControlPort
  1318. * authentication cookie. */
  1319. char *ExtORPortCookieAuthFile; /**< Filesystem location of Extended
  1320. * ORPort authentication cookie. */
  1321. int CookieAuthFileGroupReadable; /**< Boolean: Is the CookieAuthFile g+r? */
  1322. int ExtORPortCookieAuthFileGroupReadable; /**< Boolean: Is the
  1323. * ExtORPortCookieAuthFile g+r? */
  1324. int LeaveStreamsUnattached; /**< Boolean: Does Tor attach new streams to
  1325. * circuits itself (0), or does it expect a controller
  1326. * to cope? (1) */
  1327. int DisablePredictedCircuits; /**< Boolean: does Tor preemptively
  1328. * make circuits in the background (0),
  1329. * or not (1)? */
  1330. /** Process specifier for a controller that ‘owns’ this Tor
  1331. * instance. Tor will terminate if its owning controller does. */
  1332. char *OwningControllerProcess;
  1333. /** FD specifier for a controller that owns this Tor instance. */
  1334. int OwningControllerFD;
  1335. int ShutdownWaitLength; /**< When we get a SIGINT and we're a server, how
  1336. * long do we wait before exiting? */
  1337. char *SafeLogging; /**< Contains "relay", "1", "0" (meaning no scrubbing). */
  1338. /* Derived from SafeLogging */
  1339. enum {
  1340. SAFELOG_SCRUB_ALL, SAFELOG_SCRUB_RELAY, SAFELOG_SCRUB_NONE
  1341. } SafeLogging_;
  1342. int Sandbox; /**< Boolean: should sandboxing be enabled? */
  1343. int SafeSocks; /**< Boolean: should we outright refuse application
  1344. * connections that use socks4 or socks5-with-local-dns? */
  1345. int ProtocolWarnings; /**< Boolean: when other parties screw up the Tor
  1346. * protocol, is it a warn or an info in our logs? */
  1347. int TestSocks; /**< Boolean: when we get a socks connection, do we loudly
  1348. * log whether it was DNS-leaking or not? */
  1349. int HardwareAccel; /**< Boolean: Should we enable OpenSSL hardware
  1350. * acceleration where available? */
  1351. /** Token Bucket Refill resolution in milliseconds. */
  1352. int TokenBucketRefillInterval;
  1353. char *AccelName; /**< Optional hardware acceleration engine name. */
  1354. char *AccelDir; /**< Optional hardware acceleration engine search dir. */
  1355. /** Boolean: Do we try to enter from a smallish number
  1356. * of fixed nodes? */
  1357. int UseEntryGuards_option;
  1358. /** Internal variable to remember whether we're actually acting on
  1359. * UseEntryGuards_option -- when we're a non-anonymous Tor2web client or
  1360. * Single Onion Service, it is always false, otherwise we use the value of
  1361. * UseEntryGuards_option. */
  1362. int UseEntryGuards;
  1363. int NumEntryGuards; /**< How many entry guards do we try to establish? */
  1364. /** If 1, we use any guardfraction information we see in the
  1365. * consensus. If 0, we don't. If -1, let the consensus parameter
  1366. * decide. */
  1367. int UseGuardFraction;
  1368. int NumDirectoryGuards; /**< How many dir guards do we try to establish?
  1369. * If 0, use value from NumEntryGuards. */
  1370. int NumPrimaryGuards; /**< How many primary guards do we want? */
  1371. int RephistTrackTime; /**< How many seconds do we keep rephist info? */
  1372. /** Should we always fetch our dir info on the mirror schedule (which
  1373. * means directly from the authorities) no matter our other config? */
  1374. int FetchDirInfoEarly;
  1375. /** Should we fetch our dir info at the start of the consensus period? */
  1376. int FetchDirInfoExtraEarly;
  1377. int DirCache; /**< Cache all directory documents and accept requests via
  1378. * tunnelled dir conns from clients. If 1, enabled (default);
  1379. * If 0, disabled. */
  1380. char *VirtualAddrNetworkIPv4; /**< Address and mask to hand out for virtual
  1381. * MAPADDRESS requests for IPv4 addresses */
  1382. char *VirtualAddrNetworkIPv6; /**< Address and mask to hand out for virtual
  1383. * MAPADDRESS requests for IPv6 addresses */
  1384. int ServerDNSSearchDomains; /**< Boolean: If set, we don't force exit
  1385. * addresses to be FQDNs, but rather search for them in
  1386. * the local domains. */
  1387. int ServerDNSDetectHijacking; /**< Boolean: If true, check for DNS failure
  1388. * hijacking. */
  1389. int ServerDNSRandomizeCase; /**< Boolean: Use the 0x20-hack to prevent
  1390. * DNS poisoning attacks. */
  1391. char *ServerDNSResolvConfFile; /**< If provided, we configure our internal
  1392. * resolver from the file here rather than from
  1393. * /etc/resolv.conf (Unix) or the registry (Windows). */
  1394. char *DirPortFrontPage; /**< This is a full path to a file with an html
  1395. disclaimer. This allows a server administrator to show
  1396. that they're running Tor and anyone visiting their server
  1397. will know this without any specialized knowledge. */
  1398. int DisableDebuggerAttachment; /**< Currently Linux only specific attempt to
  1399. disable ptrace; needs BSD testing. */
  1400. /** Boolean: if set, we start even if our resolv.conf file is missing
  1401. * or broken. */
  1402. int ServerDNSAllowBrokenConfig;
  1403. /** Boolean: if set, then even connections to private addresses will get
  1404. * rate-limited. */
  1405. int CountPrivateBandwidth;
  1406. smartlist_t *ServerDNSTestAddresses; /**< A list of addresses that definitely
  1407. * should be resolvable. Used for
  1408. * testing our DNS server. */
  1409. int EnforceDistinctSubnets; /**< If true, don't allow multiple routers in the
  1410. * same network zone in the same circuit. */
  1411. int AllowNonRFC953Hostnames; /**< If true, we allow connections to hostnames
  1412. * with weird characters. */
  1413. /** If true, we try resolving hostnames with weird characters. */
  1414. int ServerDNSAllowNonRFC953Hostnames;
  1415. /** If true, we try to download extra-info documents (and we serve them,
  1416. * if we are a cache). For authorities, this is always true. */
  1417. int DownloadExtraInfo;
  1418. /** If true, we're configured to collect statistics on clients
  1419. * requesting network statuses from us as directory. */
  1420. int DirReqStatistics_option;
  1421. /** Internal variable to remember whether we're actually acting on
  1422. * DirReqStatistics_option -- yes if it's set and we're a server, else no. */
  1423. int DirReqStatistics;
  1424. /** If true, the user wants us to collect statistics on port usage. */
  1425. int ExitPortStatistics;
  1426. /** If true, the user wants us to collect connection statistics. */
  1427. int ConnDirectionStatistics;
  1428. /** If true, the user wants us to collect cell statistics. */
  1429. int CellStatistics;
  1430. /** If true, the user wants us to collect padding statistics. */
  1431. int PaddingStatistics;
  1432. /** If true, the user wants us to collect statistics as entry node. */
  1433. int EntryStatistics;
  1434. /** If true, the user wants us to collect statistics as hidden service
  1435. * directory, introduction point, or rendezvous point. */
  1436. int HiddenServiceStatistics_option;
  1437. /** Internal variable to remember whether we're actually acting on
  1438. * HiddenServiceStatistics_option -- yes if it's set and we're a server,
  1439. * else no. */
  1440. int HiddenServiceStatistics;
  1441. /** If true, include statistics file contents in extra-info documents. */
  1442. int ExtraInfoStatistics;
  1443. /** If true, do not believe anybody who tells us that a domain resolves
  1444. * to an internal address, or that an internal address has a PTR mapping.
  1445. * Helps avoid some cross-site attacks. */
  1446. int ClientDNSRejectInternalAddresses;
  1447. /** If true, do not accept any requests to connect to internal addresses
  1448. * over randomly chosen exits. */
  1449. int ClientRejectInternalAddresses;
  1450. /** If true, clients may connect over IPv4. If false, they will avoid
  1451. * connecting over IPv4. We enforce this for OR and Dir connections. */
  1452. int ClientUseIPv4;
  1453. /** If true, clients may connect over IPv6. If false, they will avoid
  1454. * connecting over IPv4. We enforce this for OR and Dir connections.
  1455. * Use fascist_firewall_use_ipv6() instead of accessing this value
  1456. * directly. */
  1457. int ClientUseIPv6;
  1458. /** If true, prefer an IPv6 OR port over an IPv4 one for entry node
  1459. * connections. If auto, bridge clients prefer IPv6, and other clients
  1460. * prefer IPv4. Use node_ipv6_or_preferred() instead of accessing this value
  1461. * directly. */
  1462. int ClientPreferIPv6ORPort;
  1463. /** If true, prefer an IPv6 directory port over an IPv4 one for direct
  1464. * directory connections. If auto, bridge clients prefer IPv6, and other
  1465. * clients prefer IPv4. Use fascist_firewall_prefer_ipv6_dirport() instead of
  1466. * accessing this value directly. */
  1467. int ClientPreferIPv6DirPort;
  1468. /** The length of time that we think a consensus should be fresh. */
  1469. int V3AuthVotingInterval;
  1470. /** The length of time we think it will take to distribute votes. */
  1471. int V3AuthVoteDelay;
  1472. /** The length of time we think it will take to distribute signatures. */
  1473. int V3AuthDistDelay;
  1474. /** The number of intervals we think a consensus should be valid. */
  1475. int V3AuthNIntervalsValid;
  1476. /** Should advertise and sign consensuses with a legacy key, for key
  1477. * migration purposes? */
  1478. int V3AuthUseLegacyKey;
  1479. /** Location of bandwidth measurement file */
  1480. char *V3BandwidthsFile;
  1481. /** Location of guardfraction file */
  1482. char *GuardfractionFile;
  1483. /** Authority only: key=value pairs that we add to our networkstatus
  1484. * consensus vote on the 'params' line. */
  1485. char *ConsensusParams;
  1486. /** Authority only: minimum number of measured bandwidths we must see
  1487. * before we only believe measured bandwidths to assign flags. */
  1488. int MinMeasuredBWsForAuthToIgnoreAdvertised;
  1489. /** The length of time that we think an initial consensus should be fresh.
  1490. * Only altered on testing networks. */
  1491. int TestingV3AuthInitialVotingInterval;
  1492. /** The length of time we think it will take to distribute initial votes.
  1493. * Only altered on testing networks. */
  1494. int TestingV3AuthInitialVoteDelay;
  1495. /** The length of time we think it will take to distribute initial
  1496. * signatures. Only altered on testing networks.*/
  1497. int TestingV3AuthInitialDistDelay;
  1498. /** Offset in seconds added to the starting time for consensus
  1499. voting. Only altered on testing networks. */
  1500. int TestingV3AuthVotingStartOffset;
  1501. /** If an authority has been around for less than this amount of time, it
  1502. * does not believe its reachability information is accurate. Only
  1503. * altered on testing networks. */
  1504. int TestingAuthDirTimeToLearnReachability;
  1505. /** Clients don't download any descriptor this recent, since it will
  1506. * probably not have propagated to enough caches. Only altered on testing
  1507. * networks. */
  1508. int TestingEstimatedDescriptorPropagationTime;
  1509. /** Schedule for when servers should download things in general. Only
  1510. * altered on testing networks. */
  1511. int TestingServerDownloadInitialDelay;
  1512. /** Schedule for when clients should download things in general. Only
  1513. * altered on testing networks. */
  1514. int TestingClientDownloadInitialDelay;
  1515. /** Schedule for when servers should download consensuses. Only altered
  1516. * on testing networks. */
  1517. int TestingServerConsensusDownloadInitialDelay;
  1518. /** Schedule for when clients should download consensuses. Only altered
  1519. * on testing networks. */
  1520. int TestingClientConsensusDownloadInitialDelay;
  1521. /** Schedule for when clients should download consensuses from authorities
  1522. * if they are bootstrapping (that is, they don't have a usable, reasonably
  1523. * live consensus). Only used by clients fetching from a list of fallback
  1524. * directory mirrors.
  1525. *
  1526. * This schedule is incremented by (potentially concurrent) connection
  1527. * attempts, unlike other schedules, which are incremented by connection
  1528. * failures. Only altered on testing networks. */
  1529. int ClientBootstrapConsensusAuthorityDownloadInitialDelay;
  1530. /** Schedule for when clients should download consensuses from fallback
  1531. * directory mirrors if they are bootstrapping (that is, they don't have a
  1532. * usable, reasonably live consensus). Only used by clients fetching from a
  1533. * list of fallback directory mirrors.
  1534. *
  1535. * This schedule is incremented by (potentially concurrent) connection
  1536. * attempts, unlike other schedules, which are incremented by connection
  1537. * failures. Only altered on testing networks. */
  1538. int ClientBootstrapConsensusFallbackDownloadInitialDelay;
  1539. /** Schedule for when clients should download consensuses from authorities
  1540. * if they are bootstrapping (that is, they don't have a usable, reasonably
  1541. * live consensus). Only used by clients which don't have or won't fetch
  1542. * from a list of fallback directory mirrors.
  1543. *
  1544. * This schedule is incremented by (potentially concurrent) connection
  1545. * attempts, unlike other schedules, which are incremented by connection
  1546. * failures. Only altered on testing networks. */
  1547. int ClientBootstrapConsensusAuthorityOnlyDownloadInitialDelay;
  1548. /** Schedule for when clients should download bridge descriptors. Only
  1549. * altered on testing networks. */
  1550. int TestingBridgeDownloadInitialDelay;
  1551. /** Schedule for when clients should download bridge descriptors when they
  1552. * have no running bridges. Only altered on testing networks. */
  1553. int TestingBridgeBootstrapDownloadInitialDelay;
  1554. /** When directory clients have only a few descriptors to request, they
  1555. * batch them until they have more, or until this amount of time has
  1556. * passed. Only altered on testing networks. */
  1557. int TestingClientMaxIntervalWithoutRequest;
  1558. /** How long do we let a directory connection stall before expiring
  1559. * it? Only altered on testing networks. */
  1560. int TestingDirConnectionMaxStall;
  1561. /** How many simultaneous in-progress connections will we make when trying
  1562. * to fetch a consensus before we wait for one to complete, timeout, or
  1563. * error out? Only altered on testing networks. */
  1564. int ClientBootstrapConsensusMaxInProgressTries;
  1565. /** If true, we take part in a testing network. Change the defaults of a
  1566. * couple of other configuration options and allow to change the values
  1567. * of certain configuration options. */
  1568. int TestingTorNetwork;
  1569. /** Minimum value for the Exit flag threshold on testing networks. */
  1570. uint64_t TestingMinExitFlagThreshold;
  1571. /** Minimum value for the Fast flag threshold on testing networks. */
  1572. uint64_t TestingMinFastFlagThreshold;
  1573. /** Relays in a testing network which should be voted Exit
  1574. * regardless of exit policy. */
  1575. routerset_t *TestingDirAuthVoteExit;
  1576. int TestingDirAuthVoteExitIsStrict;
  1577. /** Relays in a testing network which should be voted Guard
  1578. * regardless of uptime and bandwidth. */
  1579. routerset_t *TestingDirAuthVoteGuard;
  1580. int TestingDirAuthVoteGuardIsStrict;
  1581. /** Relays in a testing network which should be voted HSDir
  1582. * regardless of uptime and DirPort. */
  1583. routerset_t *TestingDirAuthVoteHSDir;
  1584. int TestingDirAuthVoteHSDirIsStrict;
  1585. /** Enable CONN_BW events. Only altered on testing networks. */
  1586. int TestingEnableConnBwEvent;
  1587. /** Enable CELL_STATS events. Only altered on testing networks. */
  1588. int TestingEnableCellStatsEvent;
  1589. /** If true, and we have GeoIP data, and we're a bridge, keep a per-country
  1590. * count of how many client addresses have contacted us so that we can help
  1591. * the bridge authority guess which countries have blocked access to us. */
  1592. int BridgeRecordUsageByCountry;
  1593. /** Optionally, IPv4 and IPv6 GeoIP data. */
  1594. char *GeoIPFile;
  1595. char *GeoIPv6File;
  1596. /** Autobool: if auto, then any attempt to Exclude{Exit,}Nodes a particular
  1597. * country code will exclude all nodes in ?? and A1. If true, all nodes in
  1598. * ?? and A1 are excluded. Has no effect if we don't know any GeoIP data. */
  1599. int GeoIPExcludeUnknown;
  1600. /** If true, SIGHUP should reload the torrc. Sometimes controllers want
  1601. * to make this false. */
  1602. int ReloadTorrcOnSIGHUP;
  1603. /* The main parameter for picking circuits within a connection.
  1604. *
  1605. * If this value is positive, when picking a cell to relay on a connection,
  1606. * we always relay from the circuit whose weighted cell count is lowest.
  1607. * Cells are weighted exponentially such that if one cell is sent
  1608. * 'CircuitPriorityHalflife' seconds before another, it counts for half as
  1609. * much.
  1610. *
  1611. * If this value is zero, we're disabling the cell-EWMA algorithm.
  1612. *
  1613. * If this value is negative, we're using the default approach
  1614. * according to either Tor or a parameter set in the consensus.
  1615. */
  1616. double CircuitPriorityHalflife;
  1617. /** Set to true if the TestingTorNetwork configuration option is set.
  1618. * This is used so that options_validate() has a chance to realize that
  1619. * the defaults have changed. */
  1620. int UsingTestNetworkDefaults_;
  1621. /** If 1, we try to use microdescriptors to build circuits. If 0, we don't.
  1622. * If -1, Tor decides. */
  1623. int UseMicrodescriptors;
  1624. /** File where we should write the ControlPort. */
  1625. char *ControlPortWriteToFile;
  1626. /** Should that file be group-readable? */
  1627. int ControlPortFileGroupReadable;
  1628. #define MAX_MAX_CLIENT_CIRCUITS_PENDING 1024
  1629. /** Maximum number of non-open general-purpose origin circuits to allow at
  1630. * once. */
  1631. int MaxClientCircuitsPending;
  1632. /** If 1, we always send optimistic data when it's supported. If 0, we
  1633. * never use it. If -1, we do what the consensus says. */
  1634. int OptimisticData;
  1635. /** If 1, we accept and launch no external network connections, except on
  1636. * control ports. */
  1637. int DisableNetwork;
  1638. /**
  1639. * Parameters for path-bias detection.
  1640. * @{
  1641. * These options override the default behavior of Tor's (**currently
  1642. * experimental**) path bias detection algorithm. To try to find broken or
  1643. * misbehaving guard nodes, Tor looks for nodes where more than a certain
  1644. * fraction of circuits through that guard fail to get built.
  1645. *
  1646. * The PathBiasCircThreshold option controls how many circuits we need to
  1647. * build through a guard before we make these checks. The
  1648. * PathBiasNoticeRate, PathBiasWarnRate and PathBiasExtremeRate options
  1649. * control what fraction of circuits must succeed through a guard so we
  1650. * won't write log messages. If less than PathBiasExtremeRate circuits
  1651. * succeed *and* PathBiasDropGuards is set to 1, we disable use of that
  1652. * guard.
  1653. *
  1654. * When we have seen more than PathBiasScaleThreshold circuits through a
  1655. * guard, we scale our observations by 0.5 (governed by the consensus) so
  1656. * that new observations don't get swamped by old ones.
  1657. *
  1658. * By default, or if a negative value is provided for one of these options,
  1659. * Tor uses reasonable defaults from the networkstatus consensus document.
  1660. * If no defaults are available there, these options default to 150, .70,
  1661. * .50, .30, 0, and 300 respectively.
  1662. */
  1663. int PathBiasCircThreshold;
  1664. double PathBiasNoticeRate;
  1665. double PathBiasWarnRate;
  1666. double PathBiasExtremeRate;
  1667. int PathBiasDropGuards;
  1668. int PathBiasScaleThreshold;
  1669. /** @} */
  1670. /**
  1671. * Parameters for path-bias use detection
  1672. * @{
  1673. * Similar to the above options, these options override the default behavior
  1674. * of Tor's (**currently experimental**) path use bias detection algorithm.
  1675. *
  1676. * Where as the path bias parameters govern thresholds for successfully
  1677. * building circuits, these four path use bias parameters govern thresholds
  1678. * only for circuit usage. Circuits which receive no stream usage are not
  1679. * counted by this detection algorithm. A used circuit is considered
  1680. * successful if it is capable of carrying streams or otherwise receiving
  1681. * well-formed responses to RELAY cells.
  1682. *
  1683. * By default, or if a negative value is provided for one of these options,
  1684. * Tor uses reasonable defaults from the networkstatus consensus document.
  1685. * If no defaults are available there, these options default to 20, .80,
  1686. * .60, and 100, respectively.
  1687. */
  1688. int PathBiasUseThreshold;
  1689. double PathBiasNoticeUseRate;
  1690. double PathBiasExtremeUseRate;
  1691. int PathBiasScaleUseThreshold;
  1692. /** @} */
  1693. int IPv6Exit; /**< Do we support exiting to IPv6 addresses? */
  1694. /** Fraction: */
  1695. double PathsNeededToBuildCircuits;
  1696. /** What expiry time shall we place on our SSL certs? "0" means we
  1697. * should guess a suitable value. */
  1698. int SSLKeyLifetime;
  1699. /** How long (seconds) do we keep a guard before picking a new one? */
  1700. int GuardLifetime;
  1701. /** Is this an exit node? This is a tristate, where "1" means "yes, and use
  1702. * the default exit policy if none is given" and "0" means "no; exit policy
  1703. * is 'reject *'" and "auto" (-1) means "same as 1, but warn the user."
  1704. *
  1705. * XXXX Eventually, the default will be 0. */
  1706. int ExitRelay;
  1707. /** For how long (seconds) do we declare our signing keys to be valid? */
  1708. int SigningKeyLifetime;
  1709. /** For how long (seconds) do we declare our link keys to be valid? */
  1710. int TestingLinkCertLifetime;
  1711. /** For how long (seconds) do we declare our auth keys to be valid? */
  1712. int TestingAuthKeyLifetime;
  1713. /** How long before signing keys expire will we try to make a new one? */
  1714. int TestingSigningKeySlop;
  1715. /** How long before link keys expire will we try to make a new one? */
  1716. int TestingLinkKeySlop;
  1717. /** How long before auth keys expire will we try to make a new one? */
  1718. int TestingAuthKeySlop;
  1719. /** Force use of offline master key features: never generate a master
  1720. * ed25519 identity key except from tor --keygen */
  1721. int OfflineMasterKey;
  1722. enum {
  1723. FORCE_PASSPHRASE_AUTO=0,
  1724. FORCE_PASSPHRASE_ON,
  1725. FORCE_PASSPHRASE_OFF
  1726. } keygen_force_passphrase;
  1727. int use_keygen_passphrase_fd;
  1728. int keygen_passphrase_fd;
  1729. int change_key_passphrase;
  1730. char *master_key_fname;
  1731. /** Autobool: Do we try to retain capabilities if we can? */
  1732. int KeepBindCapabilities;
  1733. /** Maximum total size of unparseable descriptors to log during the
  1734. * lifetime of this Tor process.
  1735. */
  1736. uint64_t MaxUnparseableDescSizeToLog;
  1737. /** Bool (default: 1): Switch for the shared random protocol. Only
  1738. * relevant to a directory authority. If off, the authority won't
  1739. * participate in the protocol. If on (default), a flag is added to the
  1740. * vote indicating participation. */
  1741. int AuthDirSharedRandomness;
  1742. /** If 1, we skip all OOS checks. */
  1743. int DisableOOSCheck;
  1744. /** Autobool: Should we include Ed25519 identities in extend2 cells?
  1745. * If -1, we should do whatever the consensus parameter says. */
  1746. int ExtendByEd25519ID;
  1747. /** Bool (default: 1): When testing routerinfos as a directory authority,
  1748. * do we enforce Ed25519 identity match? */
  1749. /* NOTE: remove this option someday. */
  1750. int AuthDirTestEd25519LinkKeys;
  1751. /** Bool (default: 0): Tells if a %include was used on torrc */
  1752. int IncludeUsed;
  1753. /** The seconds after expiration which we as a relay should keep old
  1754. * consensuses around so that we can generate diffs from them. If 0,
  1755. * use the default. */
  1756. int MaxConsensusAgeForDiffs;
  1757. /** Bool (default: 0). Tells Tor to never try to exec another program.
  1758. */
  1759. int NoExec;
  1760. /** Have the KIST scheduler run every X milliseconds. If less than zero, do
  1761. * not use the KIST scheduler but use the old vanilla scheduler instead. If
  1762. * zero, do what the consensus says and fall back to using KIST as if this is
  1763. * set to "10 msec" if the consensus doesn't say anything. */
  1764. int KISTSchedRunInterval;
  1765. /** A multiplier for the KIST per-socket limit calculation. */
  1766. double KISTSockBufSizeFactor;
  1767. /** The list of scheduler type string ordered by priority that is first one
  1768. * has to be tried first. Default: KIST,KISTLite,Vanilla */
  1769. smartlist_t *Schedulers;
  1770. /* An ordered list of scheduler_types mapped from Schedulers. */
  1771. smartlist_t *SchedulerTypes_;
  1772. /** List of files that were opened by %include in torrc and torrc-defaults */
  1773. smartlist_t *FilesOpenedByIncludes;
  1774. /** If true, Tor shouldn't install any posix signal handlers, since it is
  1775. * running embedded inside another process.
  1776. */
  1777. int DisableSignalHandlers;
  1778. /** Autobool: Is the circuit creation DoS mitigation subsystem enabled? */
  1779. int DoSCircuitCreationEnabled;
  1780. /** Minimum concurrent connection needed from one single address before any
  1781. * defense is used. */
  1782. int DoSCircuitCreationMinConnections;
  1783. /** Circuit rate used to refill the token bucket. */
  1784. int DoSCircuitCreationRate;
  1785. /** Maximum allowed burst of circuits. Reaching that value, the address is
  1786. * detected as malicious and a defense might be used. */
  1787. int DoSCircuitCreationBurst;
  1788. /** When an address is marked as malicous, what defense should be used
  1789. * against it. See the dos_cc_defense_type_t enum. */
  1790. int DoSCircuitCreationDefenseType;
  1791. /** For how much time (in seconds) the defense is applicable for a malicious
  1792. * address. A random time delta is added to the defense time of an address
  1793. * which will be between 1 second and half of this value. */
  1794. int DoSCircuitCreationDefenseTimePeriod;
  1795. /** Autobool: Is the DoS connection mitigation subsystem enabled? */
  1796. int DoSConnectionEnabled;
  1797. /** Maximum concurrent connection allowed per address. */
  1798. int DoSConnectionMaxConcurrentCount;
  1799. /** When an address is reaches the maximum count, what defense should be
  1800. * used against it. See the dos_conn_defense_type_t enum. */
  1801. int DoSConnectionDefenseType;
  1802. /** Autobool: Do we refuse single hop client rendezvous? */
  1803. int DoSRefuseSingleHopClientRendezvous;
  1804. } or_options_t;
  1805. #define LOG_PROTOCOL_WARN (get_protocol_warning_severity_level())
  1806. /** Persistent state for an onion router, as saved to disk. */
  1807. typedef struct {
  1808. uint32_t magic_;
  1809. /** The time at which we next plan to write the state to the disk. Equal to
  1810. * TIME_MAX if there are no savable changes, 0 if there are changes that
  1811. * should be saved right away. */
  1812. time_t next_write;
  1813. /** When was the state last written to disk? */
  1814. time_t LastWritten;
  1815. /** Fields for accounting bandwidth use. */
  1816. time_t AccountingIntervalStart;
  1817. uint64_t AccountingBytesReadInInterval;
  1818. uint64_t AccountingBytesWrittenInInterval;
  1819. int AccountingSecondsActive;
  1820. int AccountingSecondsToReachSoftLimit;
  1821. time_t AccountingSoftLimitHitAt;
  1822. uint64_t AccountingBytesAtSoftLimit;
  1823. uint64_t AccountingExpectedUsage;
  1824. /** A list of Entry Guard-related configuration lines. (pre-prop271) */
  1825. struct config_line_t *EntryGuards;
  1826. /** A list of guard-related configuration lines. (post-prop271) */
  1827. struct config_line_t *Guard;
  1828. struct config_line_t *TransportProxies;
  1829. /** Cached revision counters for active hidden services on this host */
  1830. struct config_line_t *HidServRevCounter;
  1831. /** These fields hold information on the history of bandwidth usage for
  1832. * servers. The "Ends" fields hold the time when we last updated the
  1833. * bandwidth usage. The "Interval" fields hold the granularity, in seconds,
  1834. * of the entries of Values. The "Values" lists hold decimal string
  1835. * representations of the number of bytes read or written in each
  1836. * interval. The "Maxima" list holds decimal strings describing the highest
  1837. * rate achieved during the interval.
  1838. */
  1839. time_t BWHistoryReadEnds;
  1840. int BWHistoryReadInterval;
  1841. smartlist_t *BWHistoryReadValues;
  1842. smartlist_t *BWHistoryReadMaxima;
  1843. time_t BWHistoryWriteEnds;
  1844. int BWHistoryWriteInterval;
  1845. smartlist_t *BWHistoryWriteValues;
  1846. smartlist_t *BWHistoryWriteMaxima;
  1847. time_t BWHistoryDirReadEnds;
  1848. int BWHistoryDirReadInterval;
  1849. smartlist_t *BWHistoryDirReadValues;
  1850. smartlist_t *BWHistoryDirReadMaxima;
  1851. time_t BWHistoryDirWriteEnds;
  1852. int BWHistoryDirWriteInterval;
  1853. smartlist_t *BWHistoryDirWriteValues;
  1854. smartlist_t *BWHistoryDirWriteMaxima;
  1855. /** Build time histogram */
  1856. struct config_line_t * BuildtimeHistogram;
  1857. int TotalBuildTimes;
  1858. int CircuitBuildAbandonedCount;
  1859. /** What version of Tor wrote this state file? */
  1860. char *TorVersion;
  1861. /** Holds any unrecognized values we found in the state file, in the order
  1862. * in which we found them. */
  1863. struct config_line_t *ExtraLines;
  1864. /** When did we last rotate our onion key? "0" for 'no idea'. */
  1865. time_t LastRotatedOnionKey;
  1866. } or_state_t;
  1867. #define MAX_SOCKS_ADDR_LEN 256
  1868. /********************************* circuitbuild.c **********************/
  1869. /** How many hops does a general-purpose circuit have by default? */
  1870. #define DEFAULT_ROUTE_LEN 3
  1871. /* Circuit Build Timeout "public" structures. */
  1872. /** Precision multiplier for the Bw weights */
  1873. #define BW_WEIGHT_SCALE 10000
  1874. #define BW_MIN_WEIGHT_SCALE 1
  1875. #define BW_MAX_WEIGHT_SCALE INT32_MAX
  1876. typedef struct circuit_build_times_s circuit_build_times_t;
  1877. /********************************* config.c ***************************/
  1878. /********************************* connection_edge.c *************************/
  1879. /** Enumerates possible origins of a client-side address mapping. */
  1880. typedef enum {
  1881. /** We're remapping this address because the controller told us to. */
  1882. ADDRMAPSRC_CONTROLLER,
  1883. /** We're remapping this address because of an AutomapHostsOnResolve
  1884. * configuration. */
  1885. ADDRMAPSRC_AUTOMAP,
  1886. /** We're remapping this address because our configuration (via torrc, the
  1887. * command line, or a SETCONF command) told us to. */
  1888. ADDRMAPSRC_TORRC,
  1889. /** We're remapping this address because we have TrackHostExit configured,
  1890. * and we want to remember to use the same exit next time. */
  1891. ADDRMAPSRC_TRACKEXIT,
  1892. /** We're remapping this address because we got a DNS resolution from a
  1893. * Tor server that told us what its value was. */
  1894. ADDRMAPSRC_DNS,
  1895. /** No remapping has occurred. This isn't a possible value for an
  1896. * addrmap_entry_t; it's used as a null value when we need to answer "Why
  1897. * did this remapping happen." */
  1898. ADDRMAPSRC_NONE
  1899. } addressmap_entry_source_t;
  1900. #define addressmap_entry_source_bitfield_t ENUM_BF(addressmap_entry_source_t)
  1901. #define WRITE_STATS_INTERVAL (24*60*60)
  1902. /********************************* dirvote.c ************************/
  1903. typedef struct vote_timing_t vote_timing_t;
  1904. /********************************* microdesc.c *************************/
  1905. typedef struct microdesc_cache_t microdesc_cache_t;
  1906. /********************************* rendcommon.c ***************************/
  1907. typedef struct rend_authorized_client_t rend_authorized_client_t;
  1908. typedef struct rend_encoded_v2_service_descriptor_t
  1909. rend_encoded_v2_service_descriptor_t;
  1910. /** The maximum number of non-circuit-build-timeout failures a hidden
  1911. * service client will tolerate while trying to build a circuit to an
  1912. * introduction point. See also rend_intro_point_t.unreachable_count. */
  1913. #define MAX_INTRO_POINT_REACHABILITY_FAILURES 5
  1914. /** The minimum and maximum number of distinct INTRODUCE2 cells which a
  1915. * hidden service's introduction point will receive before it begins to
  1916. * expire. */
  1917. #define INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS 16384
  1918. /* Double the minimum value so the interval is [min, min * 2]. */
  1919. #define INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS \
  1920. (INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS * 2)
  1921. /** The minimum number of seconds that an introduction point will last
  1922. * before expiring due to old age. (If it receives
  1923. * INTRO_POINT_LIFETIME_INTRODUCTIONS INTRODUCE2 cells, it may expire
  1924. * sooner.)
  1925. *
  1926. * XXX Should this be configurable? */
  1927. #define INTRO_POINT_LIFETIME_MIN_SECONDS (18*60*60)
  1928. /** The maximum number of seconds that an introduction point will last
  1929. * before expiring due to old age.
  1930. *
  1931. * XXX Should this be configurable? */
  1932. #define INTRO_POINT_LIFETIME_MAX_SECONDS (24*60*60)
  1933. /** The maximum number of circuit creation retry we do to an intro point
  1934. * before giving up. We try to reuse intro point that fails during their
  1935. * lifetime so this is a hard limit on the amount of time we do that. */
  1936. #define MAX_INTRO_POINT_CIRCUIT_RETRIES 3
  1937. typedef struct rend_intro_point_t rend_intro_point_t;
  1938. typedef struct rend_service_descriptor_t rend_service_descriptor_t;
  1939. /********************************* routerlist.c ***************************/
  1940. typedef struct dir_server_t dir_server_t;
  1941. #define RELAY_REQUIRED_MIN_BANDWIDTH (75*1024)
  1942. #define BRIDGE_REQUIRED_MIN_BANDWIDTH (50*1024)
  1943. #define ROUTER_MAX_DECLARED_BANDWIDTH INT32_MAX
  1944. typedef struct tor_version_t tor_version_t;
  1945. #endif /* !defined(TOR_OR_H) */