or.h 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299
  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. typedef struct ext_or_cmd_t ext_or_cmd_t;
  524. /** Beginning of a RELAY cell payload. */
  525. typedef struct {
  526. uint8_t command; /**< The end-to-end relay command. */
  527. uint16_t recognized; /**< Used to tell whether cell is for us. */
  528. streamid_t stream_id; /**< Which stream is this cell associated with? */
  529. char integrity[4]; /**< Used to tell whether cell is corrupted. */
  530. uint16_t length; /**< How long is the payload body? */
  531. } relay_header_t;
  532. typedef struct socks_request_t socks_request_t;
  533. typedef struct entry_port_cfg_t entry_port_cfg_t;
  534. typedef struct server_port_cfg_t server_port_cfg_t;
  535. /** Minimum length of the random part of an AUTH_CHALLENGE cell. */
  536. #define OR_AUTH_CHALLENGE_LEN 32
  537. /**
  538. * @name Certificate types for CERTS cells.
  539. *
  540. * These values are defined by the protocol, and affect how an X509
  541. * certificate in a CERTS cell is interpreted and used.
  542. *
  543. * @{ */
  544. /** A certificate that authenticates a TLS link key. The subject key
  545. * must match the key used in the TLS handshake; it must be signed by
  546. * the identity key. */
  547. #define OR_CERT_TYPE_TLS_LINK 1
  548. /** A self-signed identity certificate. The subject key must be a
  549. * 1024-bit RSA key. */
  550. #define OR_CERT_TYPE_ID_1024 2
  551. /** A certificate that authenticates a key used in an AUTHENTICATE cell
  552. * in the v3 handshake. The subject key must be a 1024-bit RSA key; it
  553. * must be signed by the identity key */
  554. #define OR_CERT_TYPE_AUTH_1024 3
  555. /* DOCDOC */
  556. #define OR_CERT_TYPE_RSA_ED_CROSSCERT 7
  557. /**@}*/
  558. /** The first supported type of AUTHENTICATE cell. It contains
  559. * a bunch of structures signed with an RSA1024 key. The signed
  560. * structures include a HMAC using negotiated TLS secrets, and a digest
  561. * of all cells sent or received before the AUTHENTICATE cell (including
  562. * the random server-generated AUTH_CHALLENGE cell).
  563. */
  564. #define AUTHTYPE_RSA_SHA256_TLSSECRET 1
  565. /** As AUTHTYPE_RSA_SHA256_TLSSECRET, but instead of using the
  566. * negotiated TLS secrets, uses exported keying material from the TLS
  567. * session as described in RFC 5705.
  568. *
  569. * Not used by today's tors, since everything that supports this
  570. * also supports ED25519_SHA256_5705, which is better.
  571. **/
  572. #define AUTHTYPE_RSA_SHA256_RFC5705 2
  573. /** As AUTHTYPE_RSA_SHA256_RFC5705, but uses an Ed25519 identity key to
  574. * authenticate. */
  575. #define AUTHTYPE_ED25519_SHA256_RFC5705 3
  576. /*
  577. * NOTE: authchallenge_type_is_better() relies on these AUTHTYPE codes
  578. * being sorted in order of preference. If we someday add one with
  579. * a higher numerical value that we don't like as much, we should revise
  580. * authchallenge_type_is_better().
  581. */
  582. /** The length of the part of the AUTHENTICATE cell body that the client and
  583. * server can generate independently (when using RSA_SHA256_TLSSECRET). It
  584. * contains everything except the client's timestamp, the client's randomly
  585. * generated nonce, and the signature. */
  586. #define V3_AUTH_FIXED_PART_LEN (8+(32*6))
  587. /** The length of the part of the AUTHENTICATE cell body that the client
  588. * signs. */
  589. #define V3_AUTH_BODY_LEN (V3_AUTH_FIXED_PART_LEN + 8 + 16)
  590. typedef struct or_handshake_certs_t or_handshake_certs_t;
  591. typedef struct or_handshake_state_t or_handshake_state_t;
  592. /** Length of Extended ORPort connection identifier. */
  593. #define EXT_OR_CONN_ID_LEN DIGEST_LEN /* 20 */
  594. /*
  595. * OR_CONN_HIGHWATER and OR_CONN_LOWWATER moved from connection_or.c so
  596. * channeltls.c can see them too.
  597. */
  598. /** When adding cells to an OR connection's outbuf, keep adding until the
  599. * outbuf is at least this long, or we run out of cells. */
  600. #define OR_CONN_HIGHWATER (32*1024)
  601. /** Add cells to an OR connection's outbuf whenever the outbuf's data length
  602. * drops below this size. */
  603. #define OR_CONN_LOWWATER (16*1024)
  604. typedef struct connection_t connection_t;
  605. typedef struct control_connection_t control_connection_t;
  606. typedef struct dir_connection_t dir_connection_t;
  607. typedef struct edge_connection_t edge_connection_t;
  608. typedef struct entry_connection_t entry_connection_t;
  609. typedef struct listener_connection_t listener_connection_t;
  610. typedef struct or_connection_t or_connection_t;
  611. /** Cast a connection_t subtype pointer to a connection_t **/
  612. #define TO_CONN(c) (&(((c)->base_)))
  613. /** Cast a entry_connection_t subtype pointer to a connection_t **/
  614. #define ENTRY_TO_CONN(c) (TO_CONN(ENTRY_TO_EDGE_CONN(c)))
  615. typedef struct addr_policy_t addr_policy_t;
  616. typedef struct cached_dir_t cached_dir_t;
  617. /** Enum used to remember where a signed_descriptor_t is stored and how to
  618. * manage the memory for signed_descriptor_body. */
  619. typedef enum {
  620. /** The descriptor isn't stored on disk at all: the copy in memory is
  621. * canonical; the saved_offset field is meaningless. */
  622. SAVED_NOWHERE=0,
  623. /** The descriptor is stored in the cached_routers file: the
  624. * signed_descriptor_body is meaningless; the signed_descriptor_len and
  625. * saved_offset are used to index into the mmaped cache file. */
  626. SAVED_IN_CACHE,
  627. /** The descriptor is stored in the cached_routers.new file: the
  628. * signed_descriptor_body and saved_offset fields are both set. */
  629. /* FFFF (We could also mmap the file and grow the mmap as needed, or
  630. * lazy-load the descriptor text by using seek and read. We don't, for
  631. * now.)
  632. */
  633. SAVED_IN_JOURNAL
  634. } saved_location_t;
  635. #define saved_location_bitfield_t ENUM_BF(saved_location_t)
  636. /** Enumeration: what directory object is being downloaded?
  637. * This determines which schedule is selected to perform the download. */
  638. typedef enum {
  639. DL_SCHED_GENERIC = 0,
  640. DL_SCHED_CONSENSUS = 1,
  641. DL_SCHED_BRIDGE = 2,
  642. } download_schedule_t;
  643. #define download_schedule_bitfield_t ENUM_BF(download_schedule_t)
  644. /** Enumeration: is the download schedule for downloading from an authority,
  645. * or from any available directory mirror?
  646. * During bootstrap, "any" means a fallback (or an authority, if there
  647. * are no fallbacks).
  648. * When we have a valid consensus, "any" means any directory server. */
  649. typedef enum {
  650. DL_WANT_ANY_DIRSERVER = 0,
  651. DL_WANT_AUTHORITY = 1,
  652. } download_want_authority_t;
  653. #define download_want_authority_bitfield_t \
  654. ENUM_BF(download_want_authority_t)
  655. /** Enumeration: do we want to increment the schedule position each time a
  656. * connection is attempted (these attempts can be concurrent), or do we want
  657. * to increment the schedule position after a connection fails? */
  658. typedef enum {
  659. DL_SCHED_INCREMENT_FAILURE = 0,
  660. DL_SCHED_INCREMENT_ATTEMPT = 1,
  661. } download_schedule_increment_t;
  662. #define download_schedule_increment_bitfield_t \
  663. ENUM_BF(download_schedule_increment_t)
  664. typedef struct download_status_t download_status_t;
  665. /** If n_download_failures is this high, the download can never happen. */
  666. #define IMPOSSIBLE_TO_DOWNLOAD 255
  667. /** The max size we expect router descriptor annotations we create to
  668. * be. We'll accept larger ones if we see them on disk, but we won't
  669. * create any that are larger than this. */
  670. #define ROUTER_ANNOTATION_BUF_LEN 256
  671. typedef struct signed_descriptor_t signed_descriptor_t;
  672. /** A signed integer representing a country code. */
  673. typedef int16_t country_t;
  674. /** Flags used to summarize the declared protocol versions of a relay,
  675. * so we don't need to parse them again and again. */
  676. typedef struct protover_summary_flags_t {
  677. /** True iff we have a proto line for this router, or a versions line
  678. * from which we could infer the protocols. */
  679. unsigned int protocols_known:1;
  680. /** True iff this router has a version or protocol list that allows it to
  681. * accept EXTEND2 cells. This requires Relay=2. */
  682. unsigned int supports_extend2_cells:1;
  683. /** True iff this router has a protocol list that allows it to negotiate
  684. * ed25519 identity keys on a link handshake with us. This
  685. * requires LinkAuth=3. */
  686. unsigned int supports_ed25519_link_handshake_compat:1;
  687. /** True iff this router has a protocol list that allows it to negotiate
  688. * ed25519 identity keys on a link handshake, at all. This requires some
  689. * LinkAuth=X for X >= 3. */
  690. unsigned int supports_ed25519_link_handshake_any:1;
  691. /** True iff this router has a protocol list that allows it to be an
  692. * introduction point supporting ed25519 authentication key which is part of
  693. * the v3 protocol detailed in proposal 224. This requires HSIntro=4. */
  694. unsigned int supports_ed25519_hs_intro : 1;
  695. /** True iff this router has a protocol list that allows it to be an hidden
  696. * service directory supporting version 3 as seen in proposal 224. This
  697. * requires HSDir=2. */
  698. unsigned int supports_v3_hsdir : 1;
  699. /** True iff this router has a protocol list that allows it to be an hidden
  700. * service rendezvous point supporting version 3 as seen in proposal 224.
  701. * This requires HSRend=2. */
  702. unsigned int supports_v3_rendezvous_point: 1;
  703. } protover_summary_flags_t;
  704. typedef struct routerinfo_t routerinfo_t;
  705. typedef struct extrainfo_t extrainfo_t;
  706. typedef struct routerstatus_t routerstatus_t;
  707. typedef struct microdesc_t microdesc_t;
  708. typedef struct node_t node_t;
  709. typedef struct vote_microdesc_hash_t vote_microdesc_hash_t;
  710. typedef struct vote_routerstatus_t vote_routerstatus_t;
  711. typedef struct document_signature_t document_signature_t;
  712. typedef struct networkstatus_voter_info_t networkstatus_voter_info_t;
  713. typedef struct networkstatus_sr_info_t networkstatus_sr_info_t;
  714. /** Enumerates recognized flavors of a consensus networkstatus document. All
  715. * flavors of a consensus are generated from the same set of votes, but they
  716. * present different types information to different versions of Tor. */
  717. typedef enum {
  718. FLAV_NS = 0,
  719. FLAV_MICRODESC = 1,
  720. } consensus_flavor_t;
  721. /** How many different consensus flavors are there? */
  722. #define N_CONSENSUS_FLAVORS ((int)(FLAV_MICRODESC)+1)
  723. typedef struct networkstatus_t networkstatus_t;
  724. typedef struct ns_detached_signatures_t ns_detached_signatures_t;
  725. /** Allowable types of desc_store_t. */
  726. typedef enum store_type_t {
  727. ROUTER_STORE = 0,
  728. EXTRAINFO_STORE = 1
  729. } store_type_t;
  730. typedef struct desc_store_t desc_store_t;
  731. typedef struct routerlist_t routerlist_t;
  732. typedef struct extend_info_t extend_info_t;
  733. typedef struct authority_cert_t authority_cert_t;
  734. /** Bitfield enum type listing types of information that directory authorities
  735. * can be authoritative about, and that directory caches may or may not cache.
  736. *
  737. * Note that the granularity here is based on authority granularity and on
  738. * cache capabilities. Thus, one particular bit may correspond in practice to
  739. * a few types of directory info, so long as every authority that pronounces
  740. * officially about one of the types prounounces officially about all of them,
  741. * and so long as every cache that caches one of them caches all of them.
  742. */
  743. typedef enum {
  744. NO_DIRINFO = 0,
  745. /** Serves/signs v3 directory information: votes, consensuses, certs */
  746. V3_DIRINFO = 1 << 2,
  747. /** Serves bridge descriptors. */
  748. BRIDGE_DIRINFO = 1 << 4,
  749. /** Serves extrainfo documents. */
  750. EXTRAINFO_DIRINFO=1 << 5,
  751. /** Serves microdescriptors. */
  752. MICRODESC_DIRINFO=1 << 6,
  753. } dirinfo_type_t;
  754. #define ALL_DIRINFO ((dirinfo_type_t)((1<<7)-1))
  755. #define CRYPT_PATH_MAGIC 0x70127012u
  756. struct fast_handshake_state_t;
  757. struct ntor_handshake_state_t;
  758. struct crypto_dh_t;
  759. #define ONION_HANDSHAKE_TYPE_TAP 0x0000
  760. #define ONION_HANDSHAKE_TYPE_FAST 0x0001
  761. #define ONION_HANDSHAKE_TYPE_NTOR 0x0002
  762. #define MAX_ONION_HANDSHAKE_TYPE 0x0002
  763. typedef struct {
  764. uint16_t tag;
  765. union {
  766. struct fast_handshake_state_t *fast;
  767. struct crypto_dh_t *tap;
  768. struct ntor_handshake_state_t *ntor;
  769. } u;
  770. } onion_handshake_state_t;
  771. typedef struct relay_crypto_t relay_crypto_t;
  772. typedef struct crypt_path_t crypt_path_t;
  773. typedef struct crypt_path_reference_t crypt_path_reference_t;
  774. #define CPATH_KEY_MATERIAL_LEN (20*2+16*2)
  775. typedef struct cpath_build_state_t cpath_build_state_t;
  776. struct create_cell_t;
  777. /** Entry in the cell stats list of a circuit; used only if CELL_STATS
  778. * events are enabled. */
  779. typedef struct testing_cell_stats_entry_t {
  780. uint8_t command; /**< cell command number. */
  781. /** Waiting time in centiseconds if this event is for a removed cell,
  782. * or 0 if this event is for adding a cell to the queue. 22 bits can
  783. * store more than 11 hours, enough to assume that a circuit with this
  784. * delay would long have been closed. */
  785. unsigned int waiting_time:22;
  786. unsigned int removed:1; /**< 0 for added to, 1 for removed from queue. */
  787. unsigned int exitward:1; /**< 0 for app-ward, 1 for exit-ward. */
  788. } testing_cell_stats_entry_t;
  789. typedef struct circuit_t circuit_t;
  790. typedef struct origin_circuit_t origin_circuit_t;
  791. typedef struct or_circuit_t or_circuit_t;
  792. /** Largest number of relay_early cells that we can send on a given
  793. * circuit. */
  794. #define MAX_RELAY_EARLY_CELLS_PER_CIRCUIT 8
  795. /**
  796. * Describes the circuit building process in simplified terms based
  797. * on the path bias accounting state for a circuit.
  798. *
  799. * NOTE: These state values are enumerated in the order for which we
  800. * expect circuits to transition through them. If you add states,
  801. * you need to preserve this overall ordering. The various pathbias
  802. * state transition and accounting functions (pathbias_mark_* and
  803. * pathbias_count_*) contain ordinal comparisons to enforce proper
  804. * state transitions for corrections.
  805. *
  806. * This state machine and the associated logic was created to prevent
  807. * miscounting due to unknown cases of circuit reuse. See also tickets
  808. * #6475 and #7802.
  809. */
  810. typedef enum {
  811. /** This circuit is "new". It has not yet completed a first hop
  812. * or been counted by the path bias code. */
  813. PATH_STATE_NEW_CIRC = 0,
  814. /** This circuit has completed one/two hops, and has been counted by
  815. * the path bias logic. */
  816. PATH_STATE_BUILD_ATTEMPTED = 1,
  817. /** This circuit has been completely built */
  818. PATH_STATE_BUILD_SUCCEEDED = 2,
  819. /** Did we try to attach any SOCKS streams or hidserv introductions to
  820. * this circuit?
  821. *
  822. * Note: If we ever implement end-to-end stream timing through test
  823. * stream probes (#5707), we must *not* set this for those probes
  824. * (or any other automatic streams) because the adversary could
  825. * just tag at a later point.
  826. */
  827. PATH_STATE_USE_ATTEMPTED = 3,
  828. /** Did any SOCKS streams or hidserv introductions actually succeed on
  829. * this circuit?
  830. *
  831. * If any streams detatch/fail from this circuit, the code transitions
  832. * the circuit back to PATH_STATE_USE_ATTEMPTED to ensure we probe. See
  833. * pathbias_mark_use_rollback() for that.
  834. */
  835. PATH_STATE_USE_SUCCEEDED = 4,
  836. /**
  837. * This is a special state to indicate that we got a corrupted
  838. * relay cell on a circuit and we don't intend to probe it.
  839. */
  840. PATH_STATE_USE_FAILED = 5,
  841. /**
  842. * This is a special state to indicate that we already counted
  843. * the circuit. Used to guard against potential state machine
  844. * violations.
  845. */
  846. PATH_STATE_ALREADY_COUNTED = 6,
  847. } path_state_t;
  848. #define path_state_bitfield_t ENUM_BF(path_state_t)
  849. #if REND_COOKIE_LEN != DIGEST_LEN
  850. #error "The REND_TOKEN_LEN macro assumes REND_COOKIE_LEN == DIGEST_LEN"
  851. #endif
  852. #define REND_TOKEN_LEN DIGEST_LEN
  853. /** Convert a circuit subtype to a circuit_t. */
  854. #define TO_CIRCUIT(x) (&((x)->base_))
  855. /** @name Isolation flags
  856. Ways to isolate client streams
  857. @{
  858. */
  859. /** Isolate based on destination port */
  860. #define ISO_DESTPORT (1u<<0)
  861. /** Isolate based on destination address */
  862. #define ISO_DESTADDR (1u<<1)
  863. /** Isolate based on SOCKS authentication */
  864. #define ISO_SOCKSAUTH (1u<<2)
  865. /** Isolate based on client protocol choice */
  866. #define ISO_CLIENTPROTO (1u<<3)
  867. /** Isolate based on client address */
  868. #define ISO_CLIENTADDR (1u<<4)
  869. /** Isolate based on session group (always on). */
  870. #define ISO_SESSIONGRP (1u<<5)
  871. /** Isolate based on newnym epoch (always on). */
  872. #define ISO_NYM_EPOCH (1u<<6)
  873. /** Isolate all streams (Internal only). */
  874. #define ISO_STREAM (1u<<7)
  875. /**@}*/
  876. /** Default isolation level for ports. */
  877. #define ISO_DEFAULT (ISO_CLIENTADDR|ISO_SOCKSAUTH|ISO_SESSIONGRP|ISO_NYM_EPOCH)
  878. /** Indicates that we haven't yet set a session group on a port_cfg_t. */
  879. #define SESSION_GROUP_UNSET -1
  880. /** Session group reserved for directory connections */
  881. #define SESSION_GROUP_DIRCONN -2
  882. /** Session group reserved for resolve requests launched by a controller */
  883. #define SESSION_GROUP_CONTROL_RESOLVE -3
  884. /** First automatically allocated session group number */
  885. #define SESSION_GROUP_FIRST_AUTO -4
  886. typedef struct port_cfg_t port_cfg_t;
  887. typedef struct routerset_t routerset_t;
  888. /** A magic value for the (Socks|OR|...)Port options below, telling Tor
  889. * to pick its own port. */
  890. #define CFG_AUTO_PORT 0xc4005e
  891. /** Enumeration of outbound address configuration types:
  892. * Exit-only, OR-only, or both */
  893. typedef enum {OUTBOUND_ADDR_EXIT, OUTBOUND_ADDR_OR,
  894. OUTBOUND_ADDR_EXIT_AND_OR,
  895. OUTBOUND_ADDR_MAX} outbound_addr_t;
  896. struct config_line_t;
  897. /** Configuration options for a Tor process. */
  898. typedef struct {
  899. uint32_t magic_;
  900. /** What should the tor process actually do? */
  901. enum {
  902. CMD_RUN_TOR=0, CMD_LIST_FINGERPRINT, CMD_HASH_PASSWORD,
  903. CMD_VERIFY_CONFIG, CMD_RUN_UNITTESTS, CMD_DUMP_CONFIG,
  904. CMD_KEYGEN,
  905. CMD_KEY_EXPIRATION,
  906. } command;
  907. char *command_arg; /**< Argument for command-line option. */
  908. struct config_line_t *Logs; /**< New-style list of configuration lines
  909. * for logs */
  910. int LogTimeGranularity; /**< Log resolution in milliseconds. */
  911. int LogMessageDomains; /**< Boolean: Should we log the domain(s) in which
  912. * each log message occurs? */
  913. int TruncateLogFile; /**< Boolean: Should we truncate the log file
  914. before we start writing? */
  915. char *SyslogIdentityTag; /**< Identity tag to add for syslog logging. */
  916. char *AndroidIdentityTag; /**< Identity tag to add for Android logging. */
  917. char *DebugLogFile; /**< Where to send verbose log messages. */
  918. char *DataDirectory_option; /**< Where to store long-term data, as
  919. * configured by the user. */
  920. char *DataDirectory; /**< Where to store long-term data, as modified. */
  921. int DataDirectoryGroupReadable; /**< Boolean: Is the DataDirectory g+r? */
  922. char *KeyDirectory_option; /**< Where to store keys, as
  923. * configured by the user. */
  924. char *KeyDirectory; /**< Where to store keys data, as modified. */
  925. int KeyDirectoryGroupReadable; /**< Boolean: Is the KeyDirectory g+r? */
  926. char *CacheDirectory_option; /**< Where to store cached data, as
  927. * configured by the user. */
  928. char *CacheDirectory; /**< Where to store cached data, as modified. */
  929. int CacheDirectoryGroupReadable; /**< Boolean: Is the CacheDirectory g+r? */
  930. char *Nickname; /**< OR only: nickname of this onion router. */
  931. char *Address; /**< OR only: configured address for this onion router. */
  932. char *PidFile; /**< Where to store PID of Tor process. */
  933. routerset_t *ExitNodes; /**< Structure containing nicknames, digests,
  934. * country codes and IP address patterns of ORs to
  935. * consider as exits. */
  936. routerset_t *EntryNodes;/**< Structure containing nicknames, digests,
  937. * country codes and IP address patterns of ORs to
  938. * consider as entry points. */
  939. int StrictNodes; /**< Boolean: When none of our EntryNodes or ExitNodes
  940. * are up, or we need to access a node in ExcludeNodes,
  941. * do we just fail instead? */
  942. routerset_t *ExcludeNodes;/**< Structure containing nicknames, digests,
  943. * country codes and IP address patterns of ORs
  944. * not to use in circuits. But see StrictNodes
  945. * above. */
  946. routerset_t *ExcludeExitNodes;/**< Structure containing nicknames, digests,
  947. * country codes and IP address patterns of
  948. * ORs not to consider as exits. */
  949. /** Union of ExcludeNodes and ExcludeExitNodes */
  950. routerset_t *ExcludeExitNodesUnion_;
  951. int DisableAllSwap; /**< Boolean: Attempt to call mlockall() on our
  952. * process for all current and future memory. */
  953. struct config_line_t *ExitPolicy; /**< Lists of exit policy components. */
  954. int ExitPolicyRejectPrivate; /**< Should we not exit to reserved private
  955. * addresses, and our own published addresses?
  956. */
  957. int ExitPolicyRejectLocalInterfaces; /**< Should we not exit to local
  958. * interface addresses?
  959. * Includes OutboundBindAddresses and
  960. * configured ports. */
  961. int ReducedExitPolicy; /**<Should we use the Reduced Exit Policy? */
  962. struct config_line_t *SocksPolicy; /**< Lists of socks policy components */
  963. struct config_line_t *DirPolicy; /**< Lists of dir policy components */
  964. /** Local address to bind outbound sockets */
  965. struct config_line_t *OutboundBindAddress;
  966. /** Local address to bind outbound relay sockets */
  967. struct config_line_t *OutboundBindAddressOR;
  968. /** Local address to bind outbound exit sockets */
  969. struct config_line_t *OutboundBindAddressExit;
  970. /** Addresses derived from the various OutboundBindAddress lines.
  971. * [][0] is IPv4, [][1] is IPv6
  972. */
  973. tor_addr_t OutboundBindAddresses[OUTBOUND_ADDR_MAX][2];
  974. /** Directory server only: which versions of
  975. * Tor should we tell users to run? */
  976. struct config_line_t *RecommendedVersions;
  977. struct config_line_t *RecommendedClientVersions;
  978. struct config_line_t *RecommendedServerVersions;
  979. struct config_line_t *RecommendedPackages;
  980. /** Whether dirservers allow router descriptors with private IPs. */
  981. int DirAllowPrivateAddresses;
  982. /** Whether routers accept EXTEND cells to routers with private IPs. */
  983. int ExtendAllowPrivateAddresses;
  984. char *User; /**< Name of user to run Tor as. */
  985. /** Ports to listen on for OR connections. */
  986. struct config_line_t *ORPort_lines;
  987. /** Ports to listen on for extended OR connections. */
  988. struct config_line_t *ExtORPort_lines;
  989. /** Ports to listen on for SOCKS connections. */
  990. struct config_line_t *SocksPort_lines;
  991. /** Ports to listen on for transparent pf/netfilter connections. */
  992. struct config_line_t *TransPort_lines;
  993. char *TransProxyType; /**< What kind of transparent proxy
  994. * implementation are we using? */
  995. /** Parsed value of TransProxyType. */
  996. enum {
  997. TPT_DEFAULT,
  998. TPT_PF_DIVERT,
  999. TPT_IPFW,
  1000. TPT_TPROXY,
  1001. } TransProxyType_parsed;
  1002. /** Ports to listen on for transparent natd connections. */
  1003. struct config_line_t *NATDPort_lines;
  1004. /** Ports to listen on for HTTP Tunnel connections. */
  1005. struct config_line_t *HTTPTunnelPort_lines;
  1006. struct config_line_t *ControlPort_lines; /**< Ports to listen on for control
  1007. * connections. */
  1008. /** List of Unix Domain Sockets to listen on for control connections. */
  1009. struct config_line_t *ControlSocket;
  1010. int ControlSocketsGroupWritable; /**< Boolean: Are control sockets g+rw? */
  1011. int UnixSocksGroupWritable; /**< Boolean: Are SOCKS Unix sockets g+rw? */
  1012. /** Ports to listen on for directory connections. */
  1013. struct config_line_t *DirPort_lines;
  1014. /** Ports to listen on for DNS requests. */
  1015. struct config_line_t *DNSPort_lines;
  1016. /* MaxMemInQueues value as input by the user. We clean this up to be
  1017. * MaxMemInQueues. */
  1018. uint64_t MaxMemInQueues_raw;
  1019. uint64_t MaxMemInQueues;/**< If we have more memory than this allocated
  1020. * for queues and buffers, run the OOM handler */
  1021. /** Above this value, consider ourselves low on RAM. */
  1022. uint64_t MaxMemInQueues_low_threshold;
  1023. /** @name port booleans
  1024. *
  1025. * Derived booleans: For server ports and ControlPort, true iff there is a
  1026. * non-listener port on an AF_INET or AF_INET6 address of the given type
  1027. * configured in one of the _lines options above.
  1028. * For client ports, also true if there is a unix socket configured.
  1029. * If you are checking for client ports, you may want to use:
  1030. * SocksPort_set || TransPort_set || NATDPort_set || DNSPort_set ||
  1031. * HTTPTunnelPort_set
  1032. * rather than SocksPort_set.
  1033. *
  1034. * @{
  1035. */
  1036. unsigned int ORPort_set : 1;
  1037. unsigned int SocksPort_set : 1;
  1038. unsigned int TransPort_set : 1;
  1039. unsigned int NATDPort_set : 1;
  1040. unsigned int ControlPort_set : 1;
  1041. unsigned int DirPort_set : 1;
  1042. unsigned int DNSPort_set : 1;
  1043. unsigned int ExtORPort_set : 1;
  1044. unsigned int HTTPTunnelPort_set : 1;
  1045. /**@}*/
  1046. int AssumeReachable; /**< Whether to publish our descriptor regardless. */
  1047. int AuthoritativeDir; /**< Boolean: is this an authoritative directory? */
  1048. int V3AuthoritativeDir; /**< Boolean: is this an authoritative directory
  1049. * for version 3 directories? */
  1050. int VersioningAuthoritativeDir; /**< Boolean: is this an authoritative
  1051. * directory that's willing to recommend
  1052. * versions? */
  1053. int BridgeAuthoritativeDir; /**< Boolean: is this an authoritative directory
  1054. * that aggregates bridge descriptors? */
  1055. /** If set on a bridge relay, it will include this value on a new
  1056. * "bridge-distribution-request" line in its bridge descriptor. */
  1057. char *BridgeDistribution;
  1058. /** If set on a bridge authority, it will answer requests on its dirport
  1059. * for bridge statuses -- but only if the requests use this password. */
  1060. char *BridgePassword;
  1061. /** If BridgePassword is set, this is a SHA256 digest of the basic http
  1062. * authenticator for it. Used so we can do a time-independent comparison. */
  1063. char *BridgePassword_AuthDigest_;
  1064. int UseBridges; /**< Boolean: should we start all circuits with a bridge? */
  1065. struct config_line_t *Bridges; /**< List of bootstrap bridge addresses. */
  1066. struct config_line_t *ClientTransportPlugin; /**< List of client
  1067. transport plugins. */
  1068. struct config_line_t *ServerTransportPlugin; /**< List of client
  1069. transport plugins. */
  1070. /** List of TCP/IP addresses that transports should listen at. */
  1071. struct config_line_t *ServerTransportListenAddr;
  1072. /** List of options that must be passed to pluggable transports. */
  1073. struct config_line_t *ServerTransportOptions;
  1074. int BridgeRelay; /**< Boolean: are we acting as a bridge relay? We make
  1075. * this explicit so we can change how we behave in the
  1076. * future. */
  1077. /** Boolean: if we know the bridge's digest, should we get new
  1078. * descriptors from the bridge authorities or from the bridge itself? */
  1079. int UpdateBridgesFromAuthority;
  1080. int AvoidDiskWrites; /**< Boolean: should we never cache things to disk?
  1081. * Not used yet. */
  1082. int ClientOnly; /**< Boolean: should we never evolve into a server role? */
  1083. int ReducedConnectionPadding; /**< Boolean: Should we try to keep connections
  1084. open shorter and pad them less against
  1085. connection-level traffic analysis? */
  1086. /** Autobool: if auto, then connection padding will be negotiated by client
  1087. * and server. If 0, it will be fully disabled. If 1, the client will still
  1088. * pad to the server regardless of server support. */
  1089. int ConnectionPadding;
  1090. /** To what authority types do we publish our descriptor? Choices are
  1091. * "v1", "v2", "v3", "bridge", or "". */
  1092. smartlist_t *PublishServerDescriptor;
  1093. /** A bitfield of authority types, derived from PublishServerDescriptor. */
  1094. dirinfo_type_t PublishServerDescriptor_;
  1095. /** Boolean: do we publish hidden service descriptors to the HS auths? */
  1096. int PublishHidServDescriptors;
  1097. int FetchServerDescriptors; /**< Do we fetch server descriptors as normal? */
  1098. int FetchHidServDescriptors; /**< and hidden service descriptors? */
  1099. int MinUptimeHidServDirectoryV2; /**< As directory authority, accept hidden
  1100. * service directories after what time? */
  1101. int FetchUselessDescriptors; /**< Do we fetch non-running descriptors too? */
  1102. int AllDirActionsPrivate; /**< Should every directory action be sent
  1103. * through a Tor circuit? */
  1104. /** Run in 'tor2web mode'? (I.e. only make client connections to hidden
  1105. * services, and use a single hop for all hidden-service-related
  1106. * circuits.) */
  1107. int Tor2webMode;
  1108. /** A routerset that should be used when picking RPs for HS circuits. */
  1109. routerset_t *Tor2webRendezvousPoints;
  1110. /** A routerset that should be used when picking middle nodes for HS
  1111. * circuits. */
  1112. routerset_t *HSLayer2Nodes;
  1113. /** A routerset that should be used when picking third-hop nodes for HS
  1114. * circuits. */
  1115. routerset_t *HSLayer3Nodes;
  1116. /** Onion Services in HiddenServiceSingleHopMode make one-hop (direct)
  1117. * circuits between the onion service server, and the introduction and
  1118. * rendezvous points. (Onion service descriptors are still posted using
  1119. * 3-hop paths, to avoid onion service directories blocking the service.)
  1120. * This option makes every hidden service instance hosted by
  1121. * this tor instance a Single Onion Service.
  1122. * HiddenServiceSingleHopMode requires HiddenServiceNonAnonymousMode to be
  1123. * set to 1.
  1124. * Use rend_service_allow_non_anonymous_connection() or
  1125. * rend_service_reveal_startup_time() instead of using this option directly.
  1126. */
  1127. int HiddenServiceSingleHopMode;
  1128. /* Makes hidden service clients and servers non-anonymous on this tor
  1129. * instance. Allows the non-anonymous HiddenServiceSingleHopMode. Enables
  1130. * non-anonymous behaviour in the hidden service protocol.
  1131. * Use rend_service_non_anonymous_mode_enabled() instead of using this option
  1132. * directly.
  1133. */
  1134. int HiddenServiceNonAnonymousMode;
  1135. int ConnLimit; /**< Demanded minimum number of simultaneous connections. */
  1136. int ConnLimit_; /**< Maximum allowed number of simultaneous connections. */
  1137. int ConnLimit_high_thresh; /**< start trying to lower socket usage if we
  1138. * have this many. */
  1139. int ConnLimit_low_thresh; /**< try to get down to here after socket
  1140. * exhaustion. */
  1141. int RunAsDaemon; /**< If true, run in the background. (Unix only) */
  1142. int FascistFirewall; /**< Whether to prefer ORs reachable on open ports. */
  1143. smartlist_t *FirewallPorts; /**< Which ports our firewall allows
  1144. * (strings). */
  1145. /** IP:ports our firewall allows. */
  1146. struct config_line_t *ReachableAddresses;
  1147. struct config_line_t *ReachableORAddresses; /**< IP:ports for OR conns. */
  1148. struct config_line_t *ReachableDirAddresses; /**< IP:ports for Dir conns. */
  1149. int ConstrainedSockets; /**< Shrink xmit and recv socket buffers. */
  1150. uint64_t ConstrainedSockSize; /**< Size of constrained buffers. */
  1151. /** Whether we should drop exit streams from Tors that we don't know are
  1152. * relays. One of "0" (never refuse), "1" (always refuse), or "-1" (do
  1153. * what the consensus says, defaulting to 'refuse' if the consensus says
  1154. * nothing). */
  1155. int RefuseUnknownExits;
  1156. /** Application ports that require all nodes in circ to have sufficient
  1157. * uptime. */
  1158. smartlist_t *LongLivedPorts;
  1159. /** Application ports that are likely to be unencrypted and
  1160. * unauthenticated; we reject requests for them to prevent the
  1161. * user from screwing up and leaking plaintext secrets to an
  1162. * observer somewhere on the Internet. */
  1163. smartlist_t *RejectPlaintextPorts;
  1164. /** Related to RejectPlaintextPorts above, except this config option
  1165. * controls whether we warn (in the log and via a controller status
  1166. * event) every time a risky connection is attempted. */
  1167. smartlist_t *WarnPlaintextPorts;
  1168. /** Should we try to reuse the same exit node for a given host */
  1169. smartlist_t *TrackHostExits;
  1170. int TrackHostExitsExpire; /**< Number of seconds until we expire an
  1171. * addressmap */
  1172. struct config_line_t *AddressMap; /**< List of address map directives. */
  1173. int AutomapHostsOnResolve; /**< If true, when we get a resolve request for a
  1174. * hostname ending with one of the suffixes in
  1175. * <b>AutomapHostsSuffixes</b>, map it to a
  1176. * virtual address. */
  1177. /** List of suffixes for <b>AutomapHostsOnResolve</b>. The special value
  1178. * "." means "match everything." */
  1179. smartlist_t *AutomapHostsSuffixes;
  1180. int RendPostPeriod; /**< How often do we post each rendezvous service
  1181. * descriptor? Remember to publish them independently. */
  1182. int KeepalivePeriod; /**< How often do we send padding cells to keep
  1183. * connections alive? */
  1184. int SocksTimeout; /**< How long do we let a socks connection wait
  1185. * unattached before we fail it? */
  1186. int LearnCircuitBuildTimeout; /**< If non-zero, we attempt to learn a value
  1187. * for CircuitBuildTimeout based on timeout
  1188. * history. Use circuit_build_times_disabled()
  1189. * rather than checking this value directly. */
  1190. int CircuitBuildTimeout; /**< Cull non-open circuits that were born at
  1191. * least this many seconds ago. Used until
  1192. * adaptive algorithm learns a new value. */
  1193. int CircuitsAvailableTimeout; /**< Try to have an open circuit for at
  1194. least this long after last activity */
  1195. int CircuitStreamTimeout; /**< If non-zero, detach streams from circuits
  1196. * and try a new circuit if the stream has been
  1197. * waiting for this many seconds. If zero, use
  1198. * our default internal timeout schedule. */
  1199. int MaxOnionQueueDelay; /*< DOCDOC */
  1200. int NewCircuitPeriod; /**< How long do we use a circuit before building
  1201. * a new one? */
  1202. int MaxCircuitDirtiness; /**< Never use circs that were first used more than
  1203. this interval ago. */
  1204. uint64_t BandwidthRate; /**< How much bandwidth, on average, are we willing
  1205. * to use in a second? */
  1206. uint64_t BandwidthBurst; /**< How much bandwidth, at maximum, are we willing
  1207. * to use in a second? */
  1208. uint64_t MaxAdvertisedBandwidth; /**< How much bandwidth are we willing to
  1209. * tell other nodes we have? */
  1210. uint64_t RelayBandwidthRate; /**< How much bandwidth, on average, are we
  1211. * willing to use for all relayed conns? */
  1212. uint64_t RelayBandwidthBurst; /**< How much bandwidth, at maximum, will we
  1213. * use in a second for all relayed conns? */
  1214. uint64_t PerConnBWRate; /**< Long-term bw on a single TLS conn, if set. */
  1215. uint64_t PerConnBWBurst; /**< Allowed burst on a single TLS conn, if set. */
  1216. int NumCPUs; /**< How many CPUs should we try to use? */
  1217. struct config_line_t *RendConfigLines; /**< List of configuration lines
  1218. * for rendezvous services. */
  1219. struct config_line_t *HidServAuth; /**< List of configuration lines for
  1220. * client-side authorizations for hidden
  1221. * services */
  1222. char *ContactInfo; /**< Contact info to be published in the directory. */
  1223. int HeartbeatPeriod; /**< Log heartbeat messages after this many seconds
  1224. * have passed. */
  1225. int MainloopStats; /**< Log main loop statistics as part of the
  1226. * heartbeat messages. */
  1227. char *HTTPProxy; /**< hostname[:port] to use as http proxy, if any. */
  1228. tor_addr_t HTTPProxyAddr; /**< Parsed IPv4 addr for http proxy, if any. */
  1229. uint16_t HTTPProxyPort; /**< Parsed port for http proxy, if any. */
  1230. char *HTTPProxyAuthenticator; /**< username:password string, if any. */
  1231. char *HTTPSProxy; /**< hostname[:port] to use as https proxy, if any. */
  1232. tor_addr_t HTTPSProxyAddr; /**< Parsed addr for https proxy, if any. */
  1233. uint16_t HTTPSProxyPort; /**< Parsed port for https proxy, if any. */
  1234. char *HTTPSProxyAuthenticator; /**< username:password string, if any. */
  1235. char *Socks4Proxy; /**< hostname:port to use as a SOCKS4 proxy, if any. */
  1236. tor_addr_t Socks4ProxyAddr; /**< Derived from Socks4Proxy. */
  1237. uint16_t Socks4ProxyPort; /**< Derived from Socks4Proxy. */
  1238. char *Socks5Proxy; /**< hostname:port to use as a SOCKS5 proxy, if any. */
  1239. tor_addr_t Socks5ProxyAddr; /**< Derived from Sock5Proxy. */
  1240. uint16_t Socks5ProxyPort; /**< Derived from Socks5Proxy. */
  1241. char *Socks5ProxyUsername; /**< Username for SOCKS5 authentication, if any */
  1242. char *Socks5ProxyPassword; /**< Password for SOCKS5 authentication, if any */
  1243. /** List of configuration lines for replacement directory authorities.
  1244. * If you just want to replace one class of authority at a time,
  1245. * use the "Alternate*Authority" options below instead. */
  1246. struct config_line_t *DirAuthorities;
  1247. /** List of fallback directory servers */
  1248. struct config_line_t *FallbackDir;
  1249. /** Whether to use the default hard-coded FallbackDirs */
  1250. int UseDefaultFallbackDirs;
  1251. /** Weight to apply to all directory authority rates if considering them
  1252. * along with fallbackdirs */
  1253. double DirAuthorityFallbackRate;
  1254. /** If set, use these main (currently v3) directory authorities and
  1255. * not the default ones. */
  1256. struct config_line_t *AlternateDirAuthority;
  1257. /** If set, use these bridge authorities and not the default one. */
  1258. struct config_line_t *AlternateBridgeAuthority;
  1259. struct config_line_t *MyFamily_lines; /**< Declared family for this OR. */
  1260. struct config_line_t *MyFamily; /**< Declared family for this OR,
  1261. normalized */
  1262. struct config_line_t *NodeFamilies; /**< List of config lines for
  1263. * node families */
  1264. smartlist_t *NodeFamilySets; /**< List of parsed NodeFamilies values. */
  1265. struct config_line_t *AuthDirBadExit; /**< Address policy for descriptors to
  1266. * mark as bad exits. */
  1267. struct config_line_t *AuthDirReject; /**< Address policy for descriptors to
  1268. * reject. */
  1269. struct config_line_t *AuthDirInvalid; /**< Address policy for descriptors to
  1270. * never mark as valid. */
  1271. /** @name AuthDir...CC
  1272. *
  1273. * Lists of country codes to mark as BadExit, or Invalid, or to
  1274. * reject entirely.
  1275. *
  1276. * @{
  1277. */
  1278. smartlist_t *AuthDirBadExitCCs;
  1279. smartlist_t *AuthDirInvalidCCs;
  1280. smartlist_t *AuthDirRejectCCs;
  1281. /**@}*/
  1282. int AuthDirListBadExits; /**< True iff we should list bad exits,
  1283. * and vote for all other exits as good. */
  1284. int AuthDirMaxServersPerAddr; /**< Do not permit more than this
  1285. * number of servers per IP address. */
  1286. int AuthDirHasIPv6Connectivity; /**< Boolean: are we on IPv6? */
  1287. int AuthDirPinKeys; /**< Boolean: Do we enforce key-pinning? */
  1288. /** If non-zero, always vote the Fast flag for any relay advertising
  1289. * this amount of capacity or more. */
  1290. uint64_t AuthDirFastGuarantee;
  1291. /** If non-zero, this advertised capacity or more is always sufficient
  1292. * to satisfy the bandwidth requirement for the Guard flag. */
  1293. uint64_t AuthDirGuardBWGuarantee;
  1294. char *AccountingStart; /**< How long is the accounting interval, and when
  1295. * does it start? */
  1296. uint64_t AccountingMax; /**< How many bytes do we allow per accounting
  1297. * interval before hibernation? 0 for "never
  1298. * hibernate." */
  1299. /** How do we determine when our AccountingMax has been reached?
  1300. * "max" for when in or out reaches AccountingMax
  1301. * "sum" for when in plus out reaches AccountingMax
  1302. * "in" for when in reaches AccountingMax
  1303. * "out" for when out reaches AccountingMax */
  1304. char *AccountingRule_option;
  1305. enum { ACCT_MAX, ACCT_SUM, ACCT_IN, ACCT_OUT } AccountingRule;
  1306. /** Base64-encoded hash of accepted passwords for the control system. */
  1307. struct config_line_t *HashedControlPassword;
  1308. /** As HashedControlPassword, but not saved. */
  1309. struct config_line_t *HashedControlSessionPassword;
  1310. int CookieAuthentication; /**< Boolean: do we enable cookie-based auth for
  1311. * the control system? */
  1312. char *CookieAuthFile; /**< Filesystem location of a ControlPort
  1313. * authentication cookie. */
  1314. char *ExtORPortCookieAuthFile; /**< Filesystem location of Extended
  1315. * ORPort authentication cookie. */
  1316. int CookieAuthFileGroupReadable; /**< Boolean: Is the CookieAuthFile g+r? */
  1317. int ExtORPortCookieAuthFileGroupReadable; /**< Boolean: Is the
  1318. * ExtORPortCookieAuthFile g+r? */
  1319. int LeaveStreamsUnattached; /**< Boolean: Does Tor attach new streams to
  1320. * circuits itself (0), or does it expect a controller
  1321. * to cope? (1) */
  1322. int DisablePredictedCircuits; /**< Boolean: does Tor preemptively
  1323. * make circuits in the background (0),
  1324. * or not (1)? */
  1325. /** Process specifier for a controller that ‘owns’ this Tor
  1326. * instance. Tor will terminate if its owning controller does. */
  1327. char *OwningControllerProcess;
  1328. /** FD specifier for a controller that owns this Tor instance. */
  1329. int OwningControllerFD;
  1330. int ShutdownWaitLength; /**< When we get a SIGINT and we're a server, how
  1331. * long do we wait before exiting? */
  1332. char *SafeLogging; /**< Contains "relay", "1", "0" (meaning no scrubbing). */
  1333. /* Derived from SafeLogging */
  1334. enum {
  1335. SAFELOG_SCRUB_ALL, SAFELOG_SCRUB_RELAY, SAFELOG_SCRUB_NONE
  1336. } SafeLogging_;
  1337. int Sandbox; /**< Boolean: should sandboxing be enabled? */
  1338. int SafeSocks; /**< Boolean: should we outright refuse application
  1339. * connections that use socks4 or socks5-with-local-dns? */
  1340. int ProtocolWarnings; /**< Boolean: when other parties screw up the Tor
  1341. * protocol, is it a warn or an info in our logs? */
  1342. int TestSocks; /**< Boolean: when we get a socks connection, do we loudly
  1343. * log whether it was DNS-leaking or not? */
  1344. int HardwareAccel; /**< Boolean: Should we enable OpenSSL hardware
  1345. * acceleration where available? */
  1346. /** Token Bucket Refill resolution in milliseconds. */
  1347. int TokenBucketRefillInterval;
  1348. char *AccelName; /**< Optional hardware acceleration engine name. */
  1349. char *AccelDir; /**< Optional hardware acceleration engine search dir. */
  1350. /** Boolean: Do we try to enter from a smallish number
  1351. * of fixed nodes? */
  1352. int UseEntryGuards_option;
  1353. /** Internal variable to remember whether we're actually acting on
  1354. * UseEntryGuards_option -- when we're a non-anonymous Tor2web client or
  1355. * Single Onion Service, it is always false, otherwise we use the value of
  1356. * UseEntryGuards_option. */
  1357. int UseEntryGuards;
  1358. int NumEntryGuards; /**< How many entry guards do we try to establish? */
  1359. /** If 1, we use any guardfraction information we see in the
  1360. * consensus. If 0, we don't. If -1, let the consensus parameter
  1361. * decide. */
  1362. int UseGuardFraction;
  1363. int NumDirectoryGuards; /**< How many dir guards do we try to establish?
  1364. * If 0, use value from NumEntryGuards. */
  1365. int NumPrimaryGuards; /**< How many primary guards do we want? */
  1366. int RephistTrackTime; /**< How many seconds do we keep rephist info? */
  1367. /** Should we always fetch our dir info on the mirror schedule (which
  1368. * means directly from the authorities) no matter our other config? */
  1369. int FetchDirInfoEarly;
  1370. /** Should we fetch our dir info at the start of the consensus period? */
  1371. int FetchDirInfoExtraEarly;
  1372. int DirCache; /**< Cache all directory documents and accept requests via
  1373. * tunnelled dir conns from clients. If 1, enabled (default);
  1374. * If 0, disabled. */
  1375. char *VirtualAddrNetworkIPv4; /**< Address and mask to hand out for virtual
  1376. * MAPADDRESS requests for IPv4 addresses */
  1377. char *VirtualAddrNetworkIPv6; /**< Address and mask to hand out for virtual
  1378. * MAPADDRESS requests for IPv6 addresses */
  1379. int ServerDNSSearchDomains; /**< Boolean: If set, we don't force exit
  1380. * addresses to be FQDNs, but rather search for them in
  1381. * the local domains. */
  1382. int ServerDNSDetectHijacking; /**< Boolean: If true, check for DNS failure
  1383. * hijacking. */
  1384. int ServerDNSRandomizeCase; /**< Boolean: Use the 0x20-hack to prevent
  1385. * DNS poisoning attacks. */
  1386. char *ServerDNSResolvConfFile; /**< If provided, we configure our internal
  1387. * resolver from the file here rather than from
  1388. * /etc/resolv.conf (Unix) or the registry (Windows). */
  1389. char *DirPortFrontPage; /**< This is a full path to a file with an html
  1390. disclaimer. This allows a server administrator to show
  1391. that they're running Tor and anyone visiting their server
  1392. will know this without any specialized knowledge. */
  1393. int DisableDebuggerAttachment; /**< Currently Linux only specific attempt to
  1394. disable ptrace; needs BSD testing. */
  1395. /** Boolean: if set, we start even if our resolv.conf file is missing
  1396. * or broken. */
  1397. int ServerDNSAllowBrokenConfig;
  1398. /** Boolean: if set, then even connections to private addresses will get
  1399. * rate-limited. */
  1400. int CountPrivateBandwidth;
  1401. smartlist_t *ServerDNSTestAddresses; /**< A list of addresses that definitely
  1402. * should be resolvable. Used for
  1403. * testing our DNS server. */
  1404. int EnforceDistinctSubnets; /**< If true, don't allow multiple routers in the
  1405. * same network zone in the same circuit. */
  1406. int AllowNonRFC953Hostnames; /**< If true, we allow connections to hostnames
  1407. * with weird characters. */
  1408. /** If true, we try resolving hostnames with weird characters. */
  1409. int ServerDNSAllowNonRFC953Hostnames;
  1410. /** If true, we try to download extra-info documents (and we serve them,
  1411. * if we are a cache). For authorities, this is always true. */
  1412. int DownloadExtraInfo;
  1413. /** If true, we're configured to collect statistics on clients
  1414. * requesting network statuses from us as directory. */
  1415. int DirReqStatistics_option;
  1416. /** Internal variable to remember whether we're actually acting on
  1417. * DirReqStatistics_option -- yes if it's set and we're a server, else no. */
  1418. int DirReqStatistics;
  1419. /** If true, the user wants us to collect statistics on port usage. */
  1420. int ExitPortStatistics;
  1421. /** If true, the user wants us to collect connection statistics. */
  1422. int ConnDirectionStatistics;
  1423. /** If true, the user wants us to collect cell statistics. */
  1424. int CellStatistics;
  1425. /** If true, the user wants us to collect padding statistics. */
  1426. int PaddingStatistics;
  1427. /** If true, the user wants us to collect statistics as entry node. */
  1428. int EntryStatistics;
  1429. /** If true, the user wants us to collect statistics as hidden service
  1430. * directory, introduction point, or rendezvous point. */
  1431. int HiddenServiceStatistics_option;
  1432. /** Internal variable to remember whether we're actually acting on
  1433. * HiddenServiceStatistics_option -- yes if it's set and we're a server,
  1434. * else no. */
  1435. int HiddenServiceStatistics;
  1436. /** If true, include statistics file contents in extra-info documents. */
  1437. int ExtraInfoStatistics;
  1438. /** If true, do not believe anybody who tells us that a domain resolves
  1439. * to an internal address, or that an internal address has a PTR mapping.
  1440. * Helps avoid some cross-site attacks. */
  1441. int ClientDNSRejectInternalAddresses;
  1442. /** If true, do not accept any requests to connect to internal addresses
  1443. * over randomly chosen exits. */
  1444. int ClientRejectInternalAddresses;
  1445. /** If true, clients may connect over IPv4. If false, they will avoid
  1446. * connecting over IPv4. We enforce this for OR and Dir connections. */
  1447. int ClientUseIPv4;
  1448. /** If true, clients may connect over IPv6. If false, they will avoid
  1449. * connecting over IPv4. We enforce this for OR and Dir connections.
  1450. * Use fascist_firewall_use_ipv6() instead of accessing this value
  1451. * directly. */
  1452. int ClientUseIPv6;
  1453. /** If true, prefer an IPv6 OR port over an IPv4 one for entry node
  1454. * connections. If auto, bridge clients prefer IPv6, and other clients
  1455. * prefer IPv4. Use node_ipv6_or_preferred() instead of accessing this value
  1456. * directly. */
  1457. int ClientPreferIPv6ORPort;
  1458. /** If true, prefer an IPv6 directory port over an IPv4 one for direct
  1459. * directory connections. If auto, bridge clients prefer IPv6, and other
  1460. * clients prefer IPv4. Use fascist_firewall_prefer_ipv6_dirport() instead of
  1461. * accessing this value directly. */
  1462. int ClientPreferIPv6DirPort;
  1463. /** The length of time that we think a consensus should be fresh. */
  1464. int V3AuthVotingInterval;
  1465. /** The length of time we think it will take to distribute votes. */
  1466. int V3AuthVoteDelay;
  1467. /** The length of time we think it will take to distribute signatures. */
  1468. int V3AuthDistDelay;
  1469. /** The number of intervals we think a consensus should be valid. */
  1470. int V3AuthNIntervalsValid;
  1471. /** Should advertise and sign consensuses with a legacy key, for key
  1472. * migration purposes? */
  1473. int V3AuthUseLegacyKey;
  1474. /** Location of bandwidth measurement file */
  1475. char *V3BandwidthsFile;
  1476. /** Location of guardfraction file */
  1477. char *GuardfractionFile;
  1478. /** Authority only: key=value pairs that we add to our networkstatus
  1479. * consensus vote on the 'params' line. */
  1480. char *ConsensusParams;
  1481. /** Authority only: minimum number of measured bandwidths we must see
  1482. * before we only believe measured bandwidths to assign flags. */
  1483. int MinMeasuredBWsForAuthToIgnoreAdvertised;
  1484. /** The length of time that we think an initial consensus should be fresh.
  1485. * Only altered on testing networks. */
  1486. int TestingV3AuthInitialVotingInterval;
  1487. /** The length of time we think it will take to distribute initial votes.
  1488. * Only altered on testing networks. */
  1489. int TestingV3AuthInitialVoteDelay;
  1490. /** The length of time we think it will take to distribute initial
  1491. * signatures. Only altered on testing networks.*/
  1492. int TestingV3AuthInitialDistDelay;
  1493. /** Offset in seconds added to the starting time for consensus
  1494. voting. Only altered on testing networks. */
  1495. int TestingV3AuthVotingStartOffset;
  1496. /** If an authority has been around for less than this amount of time, it
  1497. * does not believe its reachability information is accurate. Only
  1498. * altered on testing networks. */
  1499. int TestingAuthDirTimeToLearnReachability;
  1500. /** Clients don't download any descriptor this recent, since it will
  1501. * probably not have propagated to enough caches. Only altered on testing
  1502. * networks. */
  1503. int TestingEstimatedDescriptorPropagationTime;
  1504. /** Schedule for when servers should download things in general. Only
  1505. * altered on testing networks. */
  1506. int TestingServerDownloadInitialDelay;
  1507. /** Schedule for when clients should download things in general. Only
  1508. * altered on testing networks. */
  1509. int TestingClientDownloadInitialDelay;
  1510. /** Schedule for when servers should download consensuses. Only altered
  1511. * on testing networks. */
  1512. int TestingServerConsensusDownloadInitialDelay;
  1513. /** Schedule for when clients should download consensuses. Only altered
  1514. * on testing networks. */
  1515. int TestingClientConsensusDownloadInitialDelay;
  1516. /** Schedule for when clients should download consensuses from authorities
  1517. * if they are bootstrapping (that is, they don't have a usable, reasonably
  1518. * live consensus). Only used by clients fetching from a list of fallback
  1519. * directory mirrors.
  1520. *
  1521. * This schedule is incremented by (potentially concurrent) connection
  1522. * attempts, unlike other schedules, which are incremented by connection
  1523. * failures. Only altered on testing networks. */
  1524. int ClientBootstrapConsensusAuthorityDownloadInitialDelay;
  1525. /** Schedule for when clients should download consensuses from fallback
  1526. * directory mirrors if they are bootstrapping (that is, they don't have a
  1527. * usable, reasonably live consensus). Only used by clients fetching from a
  1528. * list of fallback directory mirrors.
  1529. *
  1530. * This schedule is incremented by (potentially concurrent) connection
  1531. * attempts, unlike other schedules, which are incremented by connection
  1532. * failures. Only altered on testing networks. */
  1533. int ClientBootstrapConsensusFallbackDownloadInitialDelay;
  1534. /** Schedule for when clients should download consensuses from authorities
  1535. * if they are bootstrapping (that is, they don't have a usable, reasonably
  1536. * live consensus). Only used by clients which don't have or won't fetch
  1537. * from a list of fallback directory mirrors.
  1538. *
  1539. * This schedule is incremented by (potentially concurrent) connection
  1540. * attempts, unlike other schedules, which are incremented by connection
  1541. * failures. Only altered on testing networks. */
  1542. int ClientBootstrapConsensusAuthorityOnlyDownloadInitialDelay;
  1543. /** Schedule for when clients should download bridge descriptors. Only
  1544. * altered on testing networks. */
  1545. int TestingBridgeDownloadInitialDelay;
  1546. /** Schedule for when clients should download bridge descriptors when they
  1547. * have no running bridges. Only altered on testing networks. */
  1548. int TestingBridgeBootstrapDownloadInitialDelay;
  1549. /** When directory clients have only a few descriptors to request, they
  1550. * batch them until they have more, or until this amount of time has
  1551. * passed. Only altered on testing networks. */
  1552. int TestingClientMaxIntervalWithoutRequest;
  1553. /** How long do we let a directory connection stall before expiring
  1554. * it? Only altered on testing networks. */
  1555. int TestingDirConnectionMaxStall;
  1556. /** How many simultaneous in-progress connections will we make when trying
  1557. * to fetch a consensus before we wait for one to complete, timeout, or
  1558. * error out? Only altered on testing networks. */
  1559. int ClientBootstrapConsensusMaxInProgressTries;
  1560. /** If true, we take part in a testing network. Change the defaults of a
  1561. * couple of other configuration options and allow to change the values
  1562. * of certain configuration options. */
  1563. int TestingTorNetwork;
  1564. /** Minimum value for the Exit flag threshold on testing networks. */
  1565. uint64_t TestingMinExitFlagThreshold;
  1566. /** Minimum value for the Fast flag threshold on testing networks. */
  1567. uint64_t TestingMinFastFlagThreshold;
  1568. /** Relays in a testing network which should be voted Exit
  1569. * regardless of exit policy. */
  1570. routerset_t *TestingDirAuthVoteExit;
  1571. int TestingDirAuthVoteExitIsStrict;
  1572. /** Relays in a testing network which should be voted Guard
  1573. * regardless of uptime and bandwidth. */
  1574. routerset_t *TestingDirAuthVoteGuard;
  1575. int TestingDirAuthVoteGuardIsStrict;
  1576. /** Relays in a testing network which should be voted HSDir
  1577. * regardless of uptime and DirPort. */
  1578. routerset_t *TestingDirAuthVoteHSDir;
  1579. int TestingDirAuthVoteHSDirIsStrict;
  1580. /** Enable CONN_BW events. Only altered on testing networks. */
  1581. int TestingEnableConnBwEvent;
  1582. /** Enable CELL_STATS events. Only altered on testing networks. */
  1583. int TestingEnableCellStatsEvent;
  1584. /** If true, and we have GeoIP data, and we're a bridge, keep a per-country
  1585. * count of how many client addresses have contacted us so that we can help
  1586. * the bridge authority guess which countries have blocked access to us. */
  1587. int BridgeRecordUsageByCountry;
  1588. /** Optionally, IPv4 and IPv6 GeoIP data. */
  1589. char *GeoIPFile;
  1590. char *GeoIPv6File;
  1591. /** Autobool: if auto, then any attempt to Exclude{Exit,}Nodes a particular
  1592. * country code will exclude all nodes in ?? and A1. If true, all nodes in
  1593. * ?? and A1 are excluded. Has no effect if we don't know any GeoIP data. */
  1594. int GeoIPExcludeUnknown;
  1595. /** If true, SIGHUP should reload the torrc. Sometimes controllers want
  1596. * to make this false. */
  1597. int ReloadTorrcOnSIGHUP;
  1598. /* The main parameter for picking circuits within a connection.
  1599. *
  1600. * If this value is positive, when picking a cell to relay on a connection,
  1601. * we always relay from the circuit whose weighted cell count is lowest.
  1602. * Cells are weighted exponentially such that if one cell is sent
  1603. * 'CircuitPriorityHalflife' seconds before another, it counts for half as
  1604. * much.
  1605. *
  1606. * If this value is zero, we're disabling the cell-EWMA algorithm.
  1607. *
  1608. * If this value is negative, we're using the default approach
  1609. * according to either Tor or a parameter set in the consensus.
  1610. */
  1611. double CircuitPriorityHalflife;
  1612. /** Set to true if the TestingTorNetwork configuration option is set.
  1613. * This is used so that options_validate() has a chance to realize that
  1614. * the defaults have changed. */
  1615. int UsingTestNetworkDefaults_;
  1616. /** If 1, we try to use microdescriptors to build circuits. If 0, we don't.
  1617. * If -1, Tor decides. */
  1618. int UseMicrodescriptors;
  1619. /** File where we should write the ControlPort. */
  1620. char *ControlPortWriteToFile;
  1621. /** Should that file be group-readable? */
  1622. int ControlPortFileGroupReadable;
  1623. #define MAX_MAX_CLIENT_CIRCUITS_PENDING 1024
  1624. /** Maximum number of non-open general-purpose origin circuits to allow at
  1625. * once. */
  1626. int MaxClientCircuitsPending;
  1627. /** If 1, we always send optimistic data when it's supported. If 0, we
  1628. * never use it. If -1, we do what the consensus says. */
  1629. int OptimisticData;
  1630. /** If 1, we accept and launch no external network connections, except on
  1631. * control ports. */
  1632. int DisableNetwork;
  1633. /**
  1634. * Parameters for path-bias detection.
  1635. * @{
  1636. * These options override the default behavior of Tor's (**currently
  1637. * experimental**) path bias detection algorithm. To try to find broken or
  1638. * misbehaving guard nodes, Tor looks for nodes where more than a certain
  1639. * fraction of circuits through that guard fail to get built.
  1640. *
  1641. * The PathBiasCircThreshold option controls how many circuits we need to
  1642. * build through a guard before we make these checks. The
  1643. * PathBiasNoticeRate, PathBiasWarnRate and PathBiasExtremeRate options
  1644. * control what fraction of circuits must succeed through a guard so we
  1645. * won't write log messages. If less than PathBiasExtremeRate circuits
  1646. * succeed *and* PathBiasDropGuards is set to 1, we disable use of that
  1647. * guard.
  1648. *
  1649. * When we have seen more than PathBiasScaleThreshold circuits through a
  1650. * guard, we scale our observations by 0.5 (governed by the consensus) so
  1651. * that new observations don't get swamped by old ones.
  1652. *
  1653. * By default, or if a negative value is provided for one of these options,
  1654. * Tor uses reasonable defaults from the networkstatus consensus document.
  1655. * If no defaults are available there, these options default to 150, .70,
  1656. * .50, .30, 0, and 300 respectively.
  1657. */
  1658. int PathBiasCircThreshold;
  1659. double PathBiasNoticeRate;
  1660. double PathBiasWarnRate;
  1661. double PathBiasExtremeRate;
  1662. int PathBiasDropGuards;
  1663. int PathBiasScaleThreshold;
  1664. /** @} */
  1665. /**
  1666. * Parameters for path-bias use detection
  1667. * @{
  1668. * Similar to the above options, these options override the default behavior
  1669. * of Tor's (**currently experimental**) path use bias detection algorithm.
  1670. *
  1671. * Where as the path bias parameters govern thresholds for successfully
  1672. * building circuits, these four path use bias parameters govern thresholds
  1673. * only for circuit usage. Circuits which receive no stream usage are not
  1674. * counted by this detection algorithm. A used circuit is considered
  1675. * successful if it is capable of carrying streams or otherwise receiving
  1676. * well-formed responses to RELAY cells.
  1677. *
  1678. * By default, or if a negative value is provided for one of these options,
  1679. * Tor uses reasonable defaults from the networkstatus consensus document.
  1680. * If no defaults are available there, these options default to 20, .80,
  1681. * .60, and 100, respectively.
  1682. */
  1683. int PathBiasUseThreshold;
  1684. double PathBiasNoticeUseRate;
  1685. double PathBiasExtremeUseRate;
  1686. int PathBiasScaleUseThreshold;
  1687. /** @} */
  1688. int IPv6Exit; /**< Do we support exiting to IPv6 addresses? */
  1689. /** Fraction: */
  1690. double PathsNeededToBuildCircuits;
  1691. /** What expiry time shall we place on our SSL certs? "0" means we
  1692. * should guess a suitable value. */
  1693. int SSLKeyLifetime;
  1694. /** How long (seconds) do we keep a guard before picking a new one? */
  1695. int GuardLifetime;
  1696. /** Is this an exit node? This is a tristate, where "1" means "yes, and use
  1697. * the default exit policy if none is given" and "0" means "no; exit policy
  1698. * is 'reject *'" and "auto" (-1) means "same as 1, but warn the user."
  1699. *
  1700. * XXXX Eventually, the default will be 0. */
  1701. int ExitRelay;
  1702. /** For how long (seconds) do we declare our signing keys to be valid? */
  1703. int SigningKeyLifetime;
  1704. /** For how long (seconds) do we declare our link keys to be valid? */
  1705. int TestingLinkCertLifetime;
  1706. /** For how long (seconds) do we declare our auth keys to be valid? */
  1707. int TestingAuthKeyLifetime;
  1708. /** How long before signing keys expire will we try to make a new one? */
  1709. int TestingSigningKeySlop;
  1710. /** How long before link keys expire will we try to make a new one? */
  1711. int TestingLinkKeySlop;
  1712. /** How long before auth keys expire will we try to make a new one? */
  1713. int TestingAuthKeySlop;
  1714. /** Force use of offline master key features: never generate a master
  1715. * ed25519 identity key except from tor --keygen */
  1716. int OfflineMasterKey;
  1717. enum {
  1718. FORCE_PASSPHRASE_AUTO=0,
  1719. FORCE_PASSPHRASE_ON,
  1720. FORCE_PASSPHRASE_OFF
  1721. } keygen_force_passphrase;
  1722. int use_keygen_passphrase_fd;
  1723. int keygen_passphrase_fd;
  1724. int change_key_passphrase;
  1725. char *master_key_fname;
  1726. /** Autobool: Do we try to retain capabilities if we can? */
  1727. int KeepBindCapabilities;
  1728. /** Maximum total size of unparseable descriptors to log during the
  1729. * lifetime of this Tor process.
  1730. */
  1731. uint64_t MaxUnparseableDescSizeToLog;
  1732. /** Bool (default: 1): Switch for the shared random protocol. Only
  1733. * relevant to a directory authority. If off, the authority won't
  1734. * participate in the protocol. If on (default), a flag is added to the
  1735. * vote indicating participation. */
  1736. int AuthDirSharedRandomness;
  1737. /** If 1, we skip all OOS checks. */
  1738. int DisableOOSCheck;
  1739. /** Autobool: Should we include Ed25519 identities in extend2 cells?
  1740. * If -1, we should do whatever the consensus parameter says. */
  1741. int ExtendByEd25519ID;
  1742. /** Bool (default: 1): When testing routerinfos as a directory authority,
  1743. * do we enforce Ed25519 identity match? */
  1744. /* NOTE: remove this option someday. */
  1745. int AuthDirTestEd25519LinkKeys;
  1746. /** Bool (default: 0): Tells if a %include was used on torrc */
  1747. int IncludeUsed;
  1748. /** The seconds after expiration which we as a relay should keep old
  1749. * consensuses around so that we can generate diffs from them. If 0,
  1750. * use the default. */
  1751. int MaxConsensusAgeForDiffs;
  1752. /** Bool (default: 0). Tells Tor to never try to exec another program.
  1753. */
  1754. int NoExec;
  1755. /** Have the KIST scheduler run every X milliseconds. If less than zero, do
  1756. * not use the KIST scheduler but use the old vanilla scheduler instead. If
  1757. * zero, do what the consensus says and fall back to using KIST as if this is
  1758. * set to "10 msec" if the consensus doesn't say anything. */
  1759. int KISTSchedRunInterval;
  1760. /** A multiplier for the KIST per-socket limit calculation. */
  1761. double KISTSockBufSizeFactor;
  1762. /** The list of scheduler type string ordered by priority that is first one
  1763. * has to be tried first. Default: KIST,KISTLite,Vanilla */
  1764. smartlist_t *Schedulers;
  1765. /* An ordered list of scheduler_types mapped from Schedulers. */
  1766. smartlist_t *SchedulerTypes_;
  1767. /** List of files that were opened by %include in torrc and torrc-defaults */
  1768. smartlist_t *FilesOpenedByIncludes;
  1769. /** If true, Tor shouldn't install any posix signal handlers, since it is
  1770. * running embedded inside another process.
  1771. */
  1772. int DisableSignalHandlers;
  1773. /** Autobool: Is the circuit creation DoS mitigation subsystem enabled? */
  1774. int DoSCircuitCreationEnabled;
  1775. /** Minimum concurrent connection needed from one single address before any
  1776. * defense is used. */
  1777. int DoSCircuitCreationMinConnections;
  1778. /** Circuit rate used to refill the token bucket. */
  1779. int DoSCircuitCreationRate;
  1780. /** Maximum allowed burst of circuits. Reaching that value, the address is
  1781. * detected as malicious and a defense might be used. */
  1782. int DoSCircuitCreationBurst;
  1783. /** When an address is marked as malicous, what defense should be used
  1784. * against it. See the dos_cc_defense_type_t enum. */
  1785. int DoSCircuitCreationDefenseType;
  1786. /** For how much time (in seconds) the defense is applicable for a malicious
  1787. * address. A random time delta is added to the defense time of an address
  1788. * which will be between 1 second and half of this value. */
  1789. int DoSCircuitCreationDefenseTimePeriod;
  1790. /** Autobool: Is the DoS connection mitigation subsystem enabled? */
  1791. int DoSConnectionEnabled;
  1792. /** Maximum concurrent connection allowed per address. */
  1793. int DoSConnectionMaxConcurrentCount;
  1794. /** When an address is reaches the maximum count, what defense should be
  1795. * used against it. See the dos_conn_defense_type_t enum. */
  1796. int DoSConnectionDefenseType;
  1797. /** Autobool: Do we refuse single hop client rendezvous? */
  1798. int DoSRefuseSingleHopClientRendezvous;
  1799. } or_options_t;
  1800. #define LOG_PROTOCOL_WARN (get_protocol_warning_severity_level())
  1801. /** Persistent state for an onion router, as saved to disk. */
  1802. typedef struct {
  1803. uint32_t magic_;
  1804. /** The time at which we next plan to write the state to the disk. Equal to
  1805. * TIME_MAX if there are no savable changes, 0 if there are changes that
  1806. * should be saved right away. */
  1807. time_t next_write;
  1808. /** When was the state last written to disk? */
  1809. time_t LastWritten;
  1810. /** Fields for accounting bandwidth use. */
  1811. time_t AccountingIntervalStart;
  1812. uint64_t AccountingBytesReadInInterval;
  1813. uint64_t AccountingBytesWrittenInInterval;
  1814. int AccountingSecondsActive;
  1815. int AccountingSecondsToReachSoftLimit;
  1816. time_t AccountingSoftLimitHitAt;
  1817. uint64_t AccountingBytesAtSoftLimit;
  1818. uint64_t AccountingExpectedUsage;
  1819. /** A list of Entry Guard-related configuration lines. (pre-prop271) */
  1820. struct config_line_t *EntryGuards;
  1821. /** A list of guard-related configuration lines. (post-prop271) */
  1822. struct config_line_t *Guard;
  1823. struct config_line_t *TransportProxies;
  1824. /** Cached revision counters for active hidden services on this host */
  1825. struct config_line_t *HidServRevCounter;
  1826. /** These fields hold information on the history of bandwidth usage for
  1827. * servers. The "Ends" fields hold the time when we last updated the
  1828. * bandwidth usage. The "Interval" fields hold the granularity, in seconds,
  1829. * of the entries of Values. The "Values" lists hold decimal string
  1830. * representations of the number of bytes read or written in each
  1831. * interval. The "Maxima" list holds decimal strings describing the highest
  1832. * rate achieved during the interval.
  1833. */
  1834. time_t BWHistoryReadEnds;
  1835. int BWHistoryReadInterval;
  1836. smartlist_t *BWHistoryReadValues;
  1837. smartlist_t *BWHistoryReadMaxima;
  1838. time_t BWHistoryWriteEnds;
  1839. int BWHistoryWriteInterval;
  1840. smartlist_t *BWHistoryWriteValues;
  1841. smartlist_t *BWHistoryWriteMaxima;
  1842. time_t BWHistoryDirReadEnds;
  1843. int BWHistoryDirReadInterval;
  1844. smartlist_t *BWHistoryDirReadValues;
  1845. smartlist_t *BWHistoryDirReadMaxima;
  1846. time_t BWHistoryDirWriteEnds;
  1847. int BWHistoryDirWriteInterval;
  1848. smartlist_t *BWHistoryDirWriteValues;
  1849. smartlist_t *BWHistoryDirWriteMaxima;
  1850. /** Build time histogram */
  1851. struct config_line_t * BuildtimeHistogram;
  1852. int TotalBuildTimes;
  1853. int CircuitBuildAbandonedCount;
  1854. /** What version of Tor wrote this state file? */
  1855. char *TorVersion;
  1856. /** Holds any unrecognized values we found in the state file, in the order
  1857. * in which we found them. */
  1858. struct config_line_t *ExtraLines;
  1859. /** When did we last rotate our onion key? "0" for 'no idea'. */
  1860. time_t LastRotatedOnionKey;
  1861. } or_state_t;
  1862. #define MAX_SOCKS_ADDR_LEN 256
  1863. /********************************* circuitbuild.c **********************/
  1864. /** How many hops does a general-purpose circuit have by default? */
  1865. #define DEFAULT_ROUTE_LEN 3
  1866. /* Circuit Build Timeout "public" structures. */
  1867. /** Precision multiplier for the Bw weights */
  1868. #define BW_WEIGHT_SCALE 10000
  1869. #define BW_MIN_WEIGHT_SCALE 1
  1870. #define BW_MAX_WEIGHT_SCALE INT32_MAX
  1871. typedef struct circuit_build_times_s circuit_build_times_t;
  1872. /********************************* config.c ***************************/
  1873. /********************************* connection_edge.c *************************/
  1874. /** Enumerates possible origins of a client-side address mapping. */
  1875. typedef enum {
  1876. /** We're remapping this address because the controller told us to. */
  1877. ADDRMAPSRC_CONTROLLER,
  1878. /** We're remapping this address because of an AutomapHostsOnResolve
  1879. * configuration. */
  1880. ADDRMAPSRC_AUTOMAP,
  1881. /** We're remapping this address because our configuration (via torrc, the
  1882. * command line, or a SETCONF command) told us to. */
  1883. ADDRMAPSRC_TORRC,
  1884. /** We're remapping this address because we have TrackHostExit configured,
  1885. * and we want to remember to use the same exit next time. */
  1886. ADDRMAPSRC_TRACKEXIT,
  1887. /** We're remapping this address because we got a DNS resolution from a
  1888. * Tor server that told us what its value was. */
  1889. ADDRMAPSRC_DNS,
  1890. /** No remapping has occurred. This isn't a possible value for an
  1891. * addrmap_entry_t; it's used as a null value when we need to answer "Why
  1892. * did this remapping happen." */
  1893. ADDRMAPSRC_NONE
  1894. } addressmap_entry_source_t;
  1895. #define addressmap_entry_source_bitfield_t ENUM_BF(addressmap_entry_source_t)
  1896. #define WRITE_STATS_INTERVAL (24*60*60)
  1897. /********************************* dirvote.c ************************/
  1898. typedef struct vote_timing_t vote_timing_t;
  1899. /********************************* microdesc.c *************************/
  1900. typedef struct microdesc_cache_t microdesc_cache_t;
  1901. /********************************* rendcommon.c ***************************/
  1902. typedef struct rend_authorized_client_t rend_authorized_client_t;
  1903. typedef struct rend_encoded_v2_service_descriptor_t
  1904. rend_encoded_v2_service_descriptor_t;
  1905. /** The maximum number of non-circuit-build-timeout failures a hidden
  1906. * service client will tolerate while trying to build a circuit to an
  1907. * introduction point. See also rend_intro_point_t.unreachable_count. */
  1908. #define MAX_INTRO_POINT_REACHABILITY_FAILURES 5
  1909. /** The minimum and maximum number of distinct INTRODUCE2 cells which a
  1910. * hidden service's introduction point will receive before it begins to
  1911. * expire. */
  1912. #define INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS 16384
  1913. /* Double the minimum value so the interval is [min, min * 2]. */
  1914. #define INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS \
  1915. (INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS * 2)
  1916. /** The minimum number of seconds that an introduction point will last
  1917. * before expiring due to old age. (If it receives
  1918. * INTRO_POINT_LIFETIME_INTRODUCTIONS INTRODUCE2 cells, it may expire
  1919. * sooner.)
  1920. *
  1921. * XXX Should this be configurable? */
  1922. #define INTRO_POINT_LIFETIME_MIN_SECONDS (18*60*60)
  1923. /** The maximum number of seconds that an introduction point will last
  1924. * before expiring due to old age.
  1925. *
  1926. * XXX Should this be configurable? */
  1927. #define INTRO_POINT_LIFETIME_MAX_SECONDS (24*60*60)
  1928. /** The maximum number of circuit creation retry we do to an intro point
  1929. * before giving up. We try to reuse intro point that fails during their
  1930. * lifetime so this is a hard limit on the amount of time we do that. */
  1931. #define MAX_INTRO_POINT_CIRCUIT_RETRIES 3
  1932. typedef struct rend_intro_point_t rend_intro_point_t;
  1933. typedef struct rend_service_descriptor_t rend_service_descriptor_t;
  1934. /********************************* routerlist.c ***************************/
  1935. typedef struct dir_server_t dir_server_t;
  1936. #define RELAY_REQUIRED_MIN_BANDWIDTH (75*1024)
  1937. #define BRIDGE_REQUIRED_MIN_BANDWIDTH (50*1024)
  1938. #define ROUTER_MAX_DECLARED_BANDWIDTH INT32_MAX
  1939. typedef struct tor_version_t tor_version_t;
  1940. #endif /* !defined(TOR_OR_H) */