TorNet.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  1. #!/usr/bin/env python2
  2. #
  3. # Copyright 2011 Nick Mathewson, Michael Stone
  4. # Copyright 2013 The Tor Project
  5. #
  6. # You may do anything with this work that copyright law would normally
  7. # restrict, so long as you retain the above notice(s) and this license
  8. # in all redistributed copies and derived works. There is no warranty.
  9. from __future__ import print_function
  10. from __future__ import with_statement
  11. import cgitb
  12. import os
  13. import signal
  14. import subprocess
  15. import sys
  16. import re
  17. import errno
  18. import time
  19. import shutil
  20. import chutney.Templating
  21. import chutney.Traffic
  22. _BASE_ENVIRON = None
  23. _TORRC_OPTIONS = None
  24. _THE_NETWORK = None
  25. # Get verbose tracebacks, so we can diagnose better.
  26. cgitb.enable(format="plain")
  27. def mkdir_p(d, mode=511):
  28. """Create directory 'd' and all of its parents as needed. Unlike
  29. os.makedirs, does not give an error if d already exists.
  30. 511 is the decimal representation of the octal number 0777. Since
  31. python2 only supports 0777 and python3 only supports 0o777, we can use
  32. neither.
  33. """
  34. try:
  35. os.makedirs(d, mode=mode)
  36. except OSError as e:
  37. if e.errno == errno.EEXIST:
  38. return
  39. raise
  40. class Node(object):
  41. """A Node represents a Tor node or a set of Tor nodes. It's created
  42. in a network configuration file.
  43. This class is responsible for holding the user's selected node
  44. configuration, and figuring out how the node needs to be
  45. configured and launched.
  46. """
  47. # Fields:
  48. # _parent
  49. # _env
  50. # _builder
  51. # _controller
  52. ########
  53. # Users are expected to call these:
  54. def __init__(self, parent=None, **kwargs):
  55. self._parent = parent
  56. self._env = self._createEnviron(parent, kwargs)
  57. self._builder = None
  58. self._controller = None
  59. def getN(self, N):
  60. return [Node(self) for _ in range(N)]
  61. def specialize(self, **kwargs):
  62. return Node(parent=self, **kwargs)
  63. ######
  64. # Chutney uses these:
  65. def getBuilder(self):
  66. """Return a NodeBuilder instance to set up this node (that is, to
  67. write all the files that need to be in place so that this
  68. node can be run by a NodeController).
  69. """
  70. if self._builder is None:
  71. self._builder = LocalNodeBuilder(self._env)
  72. return self._builder
  73. def getController(self):
  74. """Return a NodeController instance to control this node (that is,
  75. to start it, stop it, see if it's running, etc.)
  76. """
  77. if self._controller is None:
  78. self._controller = LocalNodeController(self._env)
  79. return self._controller
  80. def setNodenum(self, num):
  81. """Assign a value to the 'nodenum' element of this node. Each node
  82. in a network gets its own nodenum.
  83. """
  84. self._env['nodenum'] = num
  85. #####
  86. # These are internal:
  87. def _createEnviron(self, parent, argdict):
  88. """Return an Environ that delegates to the parent node's Environ (if
  89. there is a parent node), or to the default environment.
  90. """
  91. if parent:
  92. parentenv = parent._env
  93. else:
  94. parentenv = self._getDefaultEnviron()
  95. return TorEnviron(parentenv, **argdict)
  96. def _getDefaultEnviron(self):
  97. """Return the default environment. Any variables that we can't find
  98. set for any particular node, we look for here.
  99. """
  100. return _BASE_ENVIRON
  101. class _NodeCommon(object):
  102. """Internal helper class for functionality shared by some NodeBuilders
  103. and some NodeControllers."""
  104. # XXXX maybe this should turn into a mixin.
  105. def __init__(self, env):
  106. self._env = env
  107. def expand(self, pat, includePath=(".",)):
  108. return chutney.Templating.Template(pat, includePath).format(self._env)
  109. def _getTorrcFname(self):
  110. """Return the name of the file where we'll be writing torrc"""
  111. return self.expand("${torrc_fname}")
  112. class NodeBuilder(_NodeCommon):
  113. """Abstract base class. A NodeBuilder is responsible for doing all the
  114. one-time prep needed to set up a node in a network.
  115. """
  116. def __init__(self, env):
  117. _NodeCommon.__init__(self, env)
  118. def checkConfig(self, net):
  119. """Try to format our torrc; raise an exception if we can't.
  120. """
  121. def preConfig(self, net):
  122. """Called on all nodes before any nodes configure: generates keys as
  123. needed.
  124. """
  125. def config(self, net):
  126. """Called to configure a node: creates a torrc file for it."""
  127. def postConfig(self, net):
  128. """Called on each nodes after all nodes configure."""
  129. class NodeController(_NodeCommon):
  130. """Abstract base class. A NodeController is responsible for running a
  131. node on the network.
  132. """
  133. def __init__(self, env):
  134. _NodeCommon.__init__(self, env)
  135. def check(self, listRunning=True, listNonRunning=False):
  136. """See if this node is running, stopped, or crashed. If it's running
  137. and listRunning is set, print a short statement. If it's
  138. stopped and listNonRunning is set, then print a short statement.
  139. If it's crashed, print a statement. Return True if the
  140. node is running, false otherwise.
  141. """
  142. def start(self):
  143. """Try to start this node; return True if we succeeded or it was
  144. already running, False if we failed."""
  145. def stop(self, sig=signal.SIGINT):
  146. """Try to stop this node by sending it the signal 'sig'."""
  147. class LocalNodeBuilder(NodeBuilder):
  148. # Environment members used:
  149. # torrc -- which torrc file to use
  150. # torrc_template_path -- path to search for torrc files and include files
  151. # authority -- bool -- are we an authority?
  152. # bridgeauthority -- bool -- are we a bridge authority?
  153. # relay -- bool -- are we a relay?
  154. # bridge -- bool -- are we a bridge?
  155. # hs -- bool -- are we a hidden service?
  156. # nodenum -- int -- set by chutney -- which unique node index is this?
  157. # dir -- path -- set by chutney -- data directory for this tor
  158. # tor_gencert -- path to tor_gencert binary
  159. # tor -- path to tor binary
  160. # auth_cert_lifetime -- lifetime of authority certs, in months.
  161. # ip -- IP to listen on (used only if authority or bridge)
  162. # ipv6_addr -- IPv6 address to listen on (used only if ipv6 bridge)
  163. # orport, dirport -- (used only if authority)
  164. # fingerprint -- used only if authority
  165. # dirserver_flags -- used only if authority
  166. # nick -- nickname of this router
  167. # Environment members set
  168. # fingerprint -- hex router key fingerprint
  169. # nodenum -- int -- set by chutney -- which unique node index is this?
  170. def __init__(self, env):
  171. NodeBuilder.__init__(self, env)
  172. self._env = env
  173. def _createTorrcFile(self, checkOnly=False):
  174. """Write the torrc file for this node, disabling any options
  175. that are not supported by env's tor binary using comments.
  176. If checkOnly, just make sure that the formatting is indeed
  177. possible.
  178. """
  179. fn_out = self._getTorrcFname()
  180. torrc_template = self._getTorrcTemplate()
  181. output = torrc_template.format(self._env)
  182. if checkOnly:
  183. # XXXX Is it time-consuming to format? If so, cache here.
  184. return
  185. # now filter the options we're about to write, commenting out
  186. # the options that the current tor binary doesn't support
  187. tor = self._env['tor']
  188. # find the options the current tor binary supports, and cache them
  189. if tor not in _TORRC_OPTIONS:
  190. # Note: some versions of tor (e.g. 0.2.4.23) require
  191. # --list-torrc-options to be the first argument
  192. cmdline = [
  193. tor,
  194. "--list-torrc-options",
  195. "--hush"]
  196. try:
  197. opts = subprocess.check_output(cmdline, bufsize=-1,
  198. universal_newlines=True)
  199. except OSError as e:
  200. # only catch file not found error
  201. if e.errno == errno.ENOENT:
  202. print("Cannot find tor binary %r. Use "
  203. "CHUTNEY_TOR environment variable to set the "
  204. "path, or put the binary into $PATH." % tor)
  205. sys.exit(0)
  206. else:
  207. raise
  208. # check we received a list of options, and nothing else
  209. assert re.match(r'(^\w+$)+', opts, flags=re.MULTILINE)
  210. torrc_opts = opts.split()
  211. # cache the options for this tor binary's path
  212. _TORRC_OPTIONS[tor] = torrc_opts
  213. else:
  214. torrc_opts = _TORRC_OPTIONS[tor]
  215. # check if each option is supported before writing it
  216. # TODO: what about unsupported values?
  217. # e.g. tor 0.2.4.23 doesn't support TestingV3AuthInitialVoteDelay 2
  218. # but later version do. I say throw this one to the user.
  219. with open(fn_out, 'w') as f:
  220. # we need to do case-insensitive option comparison
  221. # even if this is a static whitelist,
  222. # so we convert to lowercase as close to the loop as possible
  223. lower_opts = [opt.lower() for opt in torrc_opts]
  224. # keep ends when splitting lines, so we can write them out
  225. # using writelines() without messing around with "\n"s
  226. for line in output.splitlines(True):
  227. # check if the first word on the line is a supported option,
  228. # preserving empty lines and comment lines
  229. sline = line.strip()
  230. if (len(sline) == 0 or
  231. sline[0] == '#' or
  232. sline.split()[0].lower() in lower_opts):
  233. f.writelines([line])
  234. else:
  235. # well, this could get spammy
  236. # TODO: warn once per option per tor binary
  237. # TODO: print tor version?
  238. print(("The tor binary at %r does not support the "
  239. "option in the torrc line:\n"
  240. "%r") % (tor, line.strip()))
  241. # we could decide to skip these lines entirely
  242. # TODO: write tor version?
  243. f.writelines(["# " + tor + " unsupported: " + line])
  244. def _getTorrcTemplate(self):
  245. """Return the template used to write the torrc for this node."""
  246. template_path = self._env['torrc_template_path']
  247. return chutney.Templating.Template("$${include:$torrc}",
  248. includePath=template_path)
  249. def _getFreeVars(self):
  250. """Return a set of the free variables in the torrc template for this
  251. node.
  252. """
  253. template = self._getTorrcTemplate()
  254. return template.freevars(self._env)
  255. def checkConfig(self, net):
  256. """Try to format our torrc; raise an exception if we can't.
  257. """
  258. self._createTorrcFile(checkOnly=True)
  259. def preConfig(self, net):
  260. """Called on all nodes before any nodes configure: generates keys and
  261. hidden service directories as needed.
  262. """
  263. self._makeDataDir()
  264. if self._env['authority']:
  265. self._genAuthorityKey()
  266. if self._env['relay']:
  267. self._genRouterKey()
  268. if self._env['hs']:
  269. self._makeHiddenServiceDir()
  270. def config(self, net):
  271. """Called to configure a node: creates a torrc file for it."""
  272. self._createTorrcFile()
  273. # self._createScripts()
  274. def postConfig(self, net):
  275. """Called on each nodes after all nodes configure."""
  276. # self.net.addNode(self)
  277. pass
  278. def _makeDataDir(self):
  279. """Create the data directory (with keys subdirectory) for this node.
  280. """
  281. datadir = self._env['dir']
  282. mkdir_p(os.path.join(datadir, 'keys'))
  283. def _makeHiddenServiceDir(self):
  284. """Create the hidden service subdirectory for this node.
  285. The directory name is stored under the 'hs_directory' environment
  286. key. It is combined with the 'dir' data directory key to yield the
  287. path to the hidden service directory.
  288. 448 is the decimal representation of the octal number 0700. Since
  289. python2 only supports 0700 and python3 only supports 0o700, we can
  290. use neither.
  291. """
  292. datadir = self._env['dir']
  293. mkdir_p(os.path.join(datadir, self._env['hs_directory']), 448)
  294. def _genAuthorityKey(self):
  295. """Generate an authority identity and signing key for this authority,
  296. if they do not already exist."""
  297. datadir = self._env['dir']
  298. tor_gencert = self._env['tor_gencert']
  299. lifetime = self._env['auth_cert_lifetime']
  300. idfile = os.path.join(datadir, 'keys', "authority_identity_key")
  301. skfile = os.path.join(datadir, 'keys', "authority_signing_key")
  302. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  303. addr = self.expand("${ip}:${dirport}")
  304. passphrase = self._env['auth_passphrase']
  305. if all(os.path.exists(f) for f in [idfile, skfile, certfile]):
  306. return
  307. cmdline = [
  308. tor_gencert,
  309. '--create-identity-key',
  310. '--passphrase-fd', '0',
  311. '-i', idfile,
  312. '-s', skfile,
  313. '-c', certfile,
  314. '-m', str(lifetime),
  315. '-a', addr]
  316. print("Creating identity key %s for %s with %s" % (
  317. idfile, self._env['nick'], " ".join(cmdline)))
  318. try:
  319. p = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
  320. except OSError as e:
  321. # only catch file not found error
  322. if e.errno == errno.ENOENT:
  323. print("Cannot find tor-gencert binary %r. Use "
  324. "CHUTNEY_TOR_GENCERT environment variable to set the "
  325. "path, or put the binary into $PATH." % tor_gencert)
  326. sys.exit(0)
  327. else:
  328. raise
  329. p.communicate(passphrase + "\n")
  330. assert p.returncode == 0 # XXXX BAD!
  331. def _genRouterKey(self):
  332. """Generate an identity key for this router, unless we already have,
  333. and set up the 'fingerprint' entry in the Environ.
  334. """
  335. datadir = self._env['dir']
  336. tor = self._env['tor']
  337. torrc = self._getTorrcFname()
  338. cmdline = [
  339. tor,
  340. "--quiet",
  341. "--ignore-missing-torrc",
  342. "-f", torrc,
  343. "--list-fingerprint",
  344. "--orport", "1",
  345. "--datadirectory", datadir]
  346. try:
  347. p = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
  348. except OSError as e:
  349. # only catch file not found error
  350. if e.errno == errno.ENOENT:
  351. print("Cannot find tor binary %r. Use "
  352. "CHUTNEY_TOR environment variable to set the "
  353. "path, or put the binary into $PATH." % tor)
  354. sys.exit(0)
  355. else:
  356. raise
  357. stdout, stderr = p.communicate()
  358. fingerprint = "".join((stdout.rstrip().split('\n')[-1]).split()[1:])
  359. if not re.match(r'^[A-F0-9]{40}$', fingerprint):
  360. print(("Error when calling %r. It gave %r as a fingerprint "
  361. " and %r on stderr.") % (" ".join(cmdline), stdout, stderr))
  362. sys.exit(1)
  363. self._env['fingerprint'] = fingerprint
  364. def _getAltAuthLines(self, hasbridgeauth=False):
  365. """Return a combination of AlternateDirAuthority,
  366. AlternateHSAuthority and AlternateBridgeAuthority lines for
  367. this Node, appropriately. Non-authorities return ""."""
  368. if not self._env['authority']:
  369. return ""
  370. datadir = self._env['dir']
  371. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  372. v3id = None
  373. with open(certfile, 'r') as f:
  374. for line in f:
  375. if line.startswith("fingerprint"):
  376. v3id = line.split()[1].strip()
  377. break
  378. assert v3id is not None
  379. if self._env['bridgeauthority']:
  380. # Bridge authorities return AlternateBridgeAuthority with
  381. # the 'bridge' flag set.
  382. options = ("AlternateBridgeAuthority",)
  383. self._env['dirserver_flags'] += " bridge"
  384. else:
  385. # Directory authorities return AlternateDirAuthority with
  386. # the 'hs' and 'v3ident' flags set.
  387. # XXXX This next line is needed for 'bridges' but breaks
  388. # 'basic'
  389. if hasbridgeauth:
  390. options = ("AlternateDirAuthority",)
  391. else:
  392. options = ("DirAuthority",)
  393. self._env['dirserver_flags'] += " hs v3ident=%s" % v3id
  394. authlines = ""
  395. for authopt in options:
  396. authlines += "%s %s orport=%s %s %s:%s %s\n" % (
  397. authopt, self._env['nick'], self._env['orport'],
  398. self._env['dirserver_flags'], self._env['ip'],
  399. self._env['dirport'], self._env['fingerprint'])
  400. return authlines
  401. def _getBridgeLines(self):
  402. """Return potential Bridge line for this Node. Non-bridge
  403. relays return "".
  404. """
  405. if not self._env['bridge']:
  406. return ""
  407. bridgelines = "Bridge %s:%s\n" % (self._env['ip'],
  408. self._env['orport'])
  409. if self._env['ipv6_addr'] is not None:
  410. bridgelines += "Bridge %s:%s\n" % (self._env['ipv6_addr'],
  411. self._env['orport'])
  412. return bridgelines
  413. class LocalNodeController(NodeController):
  414. def __init__(self, env):
  415. NodeController.__init__(self, env)
  416. self._env = env
  417. def getPid(self):
  418. """Assuming that this node has its pidfile in ${dir}/pid, return
  419. the pid of the running process, or None if there is no pid in the
  420. file.
  421. """
  422. pidfile = os.path.join(self._env['dir'], 'pid')
  423. if not os.path.exists(pidfile):
  424. return None
  425. with open(pidfile, 'r') as f:
  426. return int(f.read())
  427. def isRunning(self, pid=None):
  428. """Return true iff this node is running. (If 'pid' is provided, we
  429. assume that the pid provided is the one of this node. Otherwise
  430. we call getPid().
  431. """
  432. if pid is None:
  433. pid = self.getPid()
  434. if pid is None:
  435. return False
  436. try:
  437. os.kill(pid, 0) # "kill 0" == "are you there?"
  438. except OSError as e:
  439. if e.errno == errno.ESRCH:
  440. return False
  441. raise
  442. # okay, so the process exists. Say "True" for now.
  443. # XXXX check if this is really tor!
  444. return True
  445. def check(self, listRunning=True, listNonRunning=False):
  446. """See if this node is running, stopped, or crashed. If it's running
  447. and listRunning is set, print a short statement. If it's
  448. stopped and listNonRunning is set, then print a short statement.
  449. If it's crashed, print a statement. Return True if the
  450. node is running, false otherwise.
  451. """
  452. # XXX Split this into "check" and "print" parts.
  453. pid = self.getPid()
  454. nick = self._env['nick']
  455. datadir = self._env['dir']
  456. corefile = "core.%s" % pid
  457. if self.isRunning(pid):
  458. if listRunning:
  459. print("%s is running with PID %s" % (nick, pid))
  460. return True
  461. elif os.path.exists(os.path.join(datadir, corefile)):
  462. if listNonRunning:
  463. print("%s seems to have crashed, and left core file %s" % (
  464. nick, corefile))
  465. return False
  466. else:
  467. if listNonRunning:
  468. print("%s is stopped" % nick)
  469. return False
  470. def hup(self):
  471. """Send a SIGHUP to this node, if it's running."""
  472. pid = self.getPid()
  473. nick = self._env['nick']
  474. if self.isRunning(pid):
  475. print("Sending sighup to %s" % nick)
  476. os.kill(pid, signal.SIGHUP)
  477. return True
  478. else:
  479. print("%s is not running" % nick)
  480. return False
  481. def start(self):
  482. """Try to start this node; return True if we succeeded or it was
  483. already running, False if we failed."""
  484. if self.isRunning():
  485. print("%s is already running" % self._env['nick'])
  486. return True
  487. tor_path = self._env['tor']
  488. torrc = self._getTorrcFname()
  489. cmdline = [
  490. tor_path,
  491. "--quiet",
  492. "-f", torrc,
  493. ]
  494. try:
  495. p = subprocess.Popen(cmdline)
  496. except OSError as e:
  497. # only catch file not found error
  498. if e.errno == errno.ENOENT:
  499. print("Cannot find tor binary %r. Use CHUTNEY_TOR "
  500. "environment variable to set the path, or put the "
  501. "binary into $PATH." % tor_path)
  502. sys.exit(0)
  503. else:
  504. raise
  505. if self.waitOnLaunch():
  506. # this requires that RunAsDaemon is set
  507. p.wait()
  508. else:
  509. # this does not require RunAsDaemon to be set, but is slower.
  510. #
  511. # poll() only catches failures before the call itself
  512. # so let's sleep a little first
  513. # this does, of course, slow down process launch
  514. # which can require an adjustment to the voting interval
  515. #
  516. # avoid writing a newline or space when polling
  517. # so output comes out neatly
  518. sys.stdout.write('.')
  519. sys.stdout.flush()
  520. time.sleep(self._env['poll_launch_time'])
  521. p.poll()
  522. if p.returncode is not None and p.returncode != 0:
  523. if self._env['poll_launch_time'] is None:
  524. print("Couldn't launch %s (%s): %s" % (self._env['nick'],
  525. " ".join(cmdline),
  526. p.returncode))
  527. else:
  528. print("Couldn't poll %s (%s) "
  529. "after waiting %s seconds for launch"
  530. ": %s" % (self._env['nick'],
  531. " ".join(cmdline),
  532. self._env['poll_launch_time'],
  533. p.returncode))
  534. return False
  535. return True
  536. def stop(self, sig=signal.SIGINT):
  537. """Try to stop this node by sending it the signal 'sig'."""
  538. pid = self.getPid()
  539. if not self.isRunning(pid):
  540. print("%s is not running" % self._env['nick'])
  541. return
  542. os.kill(pid, sig)
  543. def cleanup_lockfile(self):
  544. lf = self._env['lockfile']
  545. if not self.isRunning() and os.path.exists(lf):
  546. print('Removing stale lock file for {0} ...'.format(
  547. self._env['nick']))
  548. os.remove(lf)
  549. def waitOnLaunch(self):
  550. """Check whether we can wait() for the tor process to launch"""
  551. # TODO: is this the best place for this code?
  552. # RunAsDaemon default is 0
  553. runAsDaemon = False
  554. with open(self._getTorrcFname(), 'r') as f:
  555. for line in f.readlines():
  556. stline = line.strip()
  557. # if the line isn't all whitespace or blank
  558. if len(stline) > 0:
  559. splline = stline.split()
  560. # if the line has at least two tokens on it
  561. if (len(splline) > 0 and
  562. splline[0].lower() == "RunAsDaemon".lower() and
  563. splline[1] == "1"):
  564. # use the RunAsDaemon value from the torrc
  565. # TODO: multiple values?
  566. runAsDaemon = True
  567. if runAsDaemon:
  568. # we must use wait() instead of poll()
  569. self._env['poll_launch_time'] = None
  570. return True
  571. else:
  572. # we must use poll() instead of wait()
  573. if self._env['poll_launch_time'] is None:
  574. self._env['poll_launch_time'] = \
  575. self._env['poll_launch_time_default']
  576. return False
  577. DEFAULTS = {
  578. 'authority': False,
  579. 'bridgeauthority': False,
  580. 'hasbridgeauth': False,
  581. 'relay': False,
  582. 'bridge': False,
  583. 'hs': False,
  584. 'hs_directory': 'hidden_service',
  585. 'hs-hostname': None,
  586. 'connlimit': 60,
  587. 'net_base_dir': os.environ.get('CHUTNEY_DATA_DIR', 'net'),
  588. 'tor': os.environ.get('CHUTNEY_TOR', 'tor'),
  589. 'tor-gencert': os.environ.get('CHUTNEY_TOR_GENCERT', None),
  590. 'auth_cert_lifetime': 12,
  591. 'ip': '127.0.0.1',
  592. 'ipv6_addr': None,
  593. 'dirserver_flags': 'no-v2',
  594. 'chutney_dir': '.',
  595. 'torrc_fname': '${dir}/torrc',
  596. 'orport_base': 5000,
  597. 'dirport_base': 7000,
  598. 'controlport_base': 8000,
  599. 'socksport_base': 9000,
  600. 'authorities': "AlternateDirAuthority bleargh bad torrc file!",
  601. 'bridges': "Bridge bleargh bad torrc file!",
  602. 'core': True,
  603. # poll_launch_time: None means wait on launch (requires RunAsDaemon),
  604. # otherwise, poll after that many seconds (can be fractional/decimal)
  605. 'poll_launch_time': None,
  606. # Used when poll_launch_time is None, but RunAsDaemon is not set
  607. # Set low so that we don't interfere with the voting interval
  608. 'poll_launch_time_default': 0.1,
  609. # the number of bytes of random data we send on each connection
  610. 'data_bytes': int(os.environ.get('CHUTNEY_DATA_BYTES', 10 * 1024)),
  611. # the number of times each client will connect
  612. 'connection_count': int(os.environ.get('CHUTNEY_CONNECTIONS', 1)),
  613. # Do we want every client to connect to every HS, or one client
  614. # to connect to each HS?
  615. # (Clients choose an exit at random, so this doesn't apply to exits.)
  616. 'hs_multi_client': int(os.environ.get('CHUTNEY_HS_MULTI_CLIENT', 0)),
  617. }
  618. class TorEnviron(chutney.Templating.Environ):
  619. """Subclass of chutney.Templating.Environ to implement commonly-used
  620. substitutions.
  621. Environment fields provided:
  622. orport, controlport, socksport, dirport:
  623. dir:
  624. nick:
  625. tor_gencert:
  626. auth_passphrase:
  627. torrc_template_path:
  628. hs_hostname:
  629. Environment fields used:
  630. nodenum
  631. tag
  632. orport_base, controlport_base, socksport_base, dirport_base
  633. tor-gencert (note hyphen)
  634. chutney_dir
  635. tor
  636. dir
  637. hs_directory
  638. nick (debugging only)
  639. hs-hostname (note hyphen)
  640. XXXX document the above. Or document all fields in one place?
  641. """
  642. def __init__(self, parent=None, **kwargs):
  643. chutney.Templating.Environ.__init__(self, parent=parent, **kwargs)
  644. def _get_orport(self, my):
  645. return my['orport_base'] + my['nodenum']
  646. def _get_controlport(self, my):
  647. return my['controlport_base'] + my['nodenum']
  648. def _get_socksport(self, my):
  649. return my['socksport_base'] + my['nodenum']
  650. def _get_dirport(self, my):
  651. return my['dirport_base'] + my['nodenum']
  652. def _get_dir(self, my):
  653. return os.path.abspath(os.path.join(my['net_base_dir'],
  654. "nodes",
  655. "%03d%s" % (
  656. my['nodenum'], my['tag'])))
  657. def _get_nick(self, my):
  658. return "test%03d%s" % (my['nodenum'], my['tag'])
  659. def _get_tor_gencert(self, my):
  660. return my['tor-gencert'] or '{0}-gencert'.format(my['tor'])
  661. def _get_auth_passphrase(self, my):
  662. return self['nick'] # OMG TEH SECURE!
  663. def _get_torrc_template_path(self, my):
  664. return [os.path.join(my['chutney_dir'], 'torrc_templates')]
  665. def _get_lockfile(self, my):
  666. return os.path.join(self['dir'], 'lock')
  667. # A hs generates its key on first run,
  668. # so check for it at the last possible moment,
  669. # but cache it in memory to avoid repeatedly reading the file
  670. # XXXX - this is not like the other functions in this class,
  671. # as it reads from a file created by the hidden service
  672. def _get_hs_hostname(self, my):
  673. if my['hs-hostname'] is None:
  674. datadir = my['dir']
  675. # a file containing a single line with the hs' .onion address
  676. hs_hostname_file = os.path.join(datadir, my['hs_directory'],
  677. 'hostname')
  678. try:
  679. with open(hs_hostname_file, 'r') as hostnamefp:
  680. hostname = hostnamefp.read()
  681. # the hostname file ends with a newline
  682. hostname = hostname.strip()
  683. my['hs-hostname'] = hostname
  684. except IOError as e:
  685. print("Error: hs %r error %d: %r opening hostname file '%r'" %
  686. (my['nick'], e.errno, e.strerror, hs_hostname_file))
  687. return my['hs-hostname']
  688. class Network(object):
  689. """A network of Tor nodes, plus functions to manipulate them
  690. """
  691. def __init__(self, defaultEnviron):
  692. self._nodes = []
  693. self._dfltEnv = defaultEnviron
  694. self._nextnodenum = 0
  695. def _addNode(self, n):
  696. n.setNodenum(self._nextnodenum)
  697. self._nextnodenum += 1
  698. self._nodes.append(n)
  699. def move_aside_nodes(self):
  700. nodesdir = os.path.join(os.getcwd(), 'net', 'nodes')
  701. if not os.path.exists(nodesdir):
  702. return
  703. newdir = newdirbase = "%s.%d" % (nodesdir, time.time())
  704. i = 0
  705. while os.path.exists(newdir):
  706. i += 1
  707. newdir = "%s.%d" % (newdirbase, i)
  708. print("NOTE: renaming %r to %r" % (nodesdir, newdir))
  709. os.rename(nodesdir, newdir)
  710. def _checkConfig(self):
  711. for n in self._nodes:
  712. n.getBuilder().checkConfig(self)
  713. def configure(self):
  714. # shutil.rmtree(os.path.join(os.getcwd(),'net','nodes'),ignore_errors=True)
  715. self.move_aside_nodes()
  716. network = self
  717. altauthlines = []
  718. bridgelines = []
  719. builders = [n.getBuilder() for n in self._nodes]
  720. self._checkConfig()
  721. # XXX don't change node names or types or count if anything is
  722. # XXX running!
  723. for b in builders:
  724. b.preConfig(network)
  725. altauthlines.append(b._getAltAuthLines(
  726. self._dfltEnv['hasbridgeauth']))
  727. bridgelines.append(b._getBridgeLines())
  728. self._dfltEnv['authorities'] = "".join(altauthlines)
  729. self._dfltEnv['bridges'] = "".join(bridgelines)
  730. for b in builders:
  731. b.config(network)
  732. for b in builders:
  733. b.postConfig(network)
  734. def status(self):
  735. statuses = [n.getController().check() for n in self._nodes]
  736. n_ok = len([x for x in statuses if x])
  737. print("%d/%d nodes are running" % (n_ok, len(self._nodes)))
  738. return n_ok == len(self._nodes)
  739. def restart(self):
  740. self.stop()
  741. self.start()
  742. def start(self):
  743. if self._dfltEnv['poll_launch_time'] is not None:
  744. # format polling correctly - avoid printing a newline
  745. sys.stdout.write("Starting nodes")
  746. sys.stdout.flush()
  747. else:
  748. print("Starting nodes")
  749. rv = all([n.getController().start() for n in self._nodes])
  750. # now print a newline unconditionally - this stops poll()ing
  751. # output from being squashed together, at the cost of a blank
  752. # line in wait()ing output
  753. print("")
  754. return rv
  755. def hup(self):
  756. print("Sending SIGHUP to nodes")
  757. return all([n.getController().hup() for n in self._nodes])
  758. def stop(self):
  759. controllers = [n.getController() for n in self._nodes]
  760. for sig, desc in [(signal.SIGINT, "SIGINT"),
  761. (signal.SIGINT, "another SIGINT"),
  762. (signal.SIGKILL, "SIGKILL")]:
  763. print("Sending %s to nodes" % desc)
  764. for c in controllers:
  765. if c.isRunning():
  766. c.stop(sig=sig)
  767. print("Waiting for nodes to finish.")
  768. for n in range(15):
  769. time.sleep(1)
  770. if all(not c.isRunning() for c in controllers):
  771. # check for stale lock file when Tor crashes
  772. for c in controllers:
  773. c.cleanup_lockfile()
  774. return
  775. sys.stdout.write(".")
  776. sys.stdout.flush()
  777. for c in controllers:
  778. c.check(listNonRunning=False)
  779. def verify(self):
  780. print("Verifying data transmission:")
  781. status = self._verify_traffic()
  782. print("Transmission: %s" % ("Success" if status else "Failure"))
  783. if not status:
  784. # TODO: allow the debug flag to be passed as an argument to
  785. # src/test/test-network.sh and chutney
  786. print("Set 'debug_flag = True' in Traffic.py to diagnose.")
  787. return status
  788. def _verify_traffic(self):
  789. """Verify (parts of) the network by sending traffic through it
  790. and verify what is received."""
  791. LISTEN_PORT = 4747 # FIXME: Do better! Note the default exit policy.
  792. # HSs must have a HiddenServiceDir with
  793. # "HiddenServicePort <HS_PORT> 127.0.0.1:<LISTEN_PORT>"
  794. HS_PORT = 5858
  795. # The amount of data to send between each source-sink pair,
  796. # each time the source connects.
  797. # We create a source-sink pair for each (bridge) client to an exit,
  798. # and a source-sink pair for a (bridge) client to each hidden service
  799. DATALEN = self._dfltEnv['data_bytes']
  800. # Print a dot each time a sink verifies this much data
  801. DOTDATALEN = 5 * 1024 * 1024 # Octets.
  802. TIMEOUT = 3 # Seconds.
  803. # Calculate the amount of random data we should use
  804. randomlen = self._calculate_randomlen(DATALEN)
  805. reps = self._calculate_reps(DATALEN, randomlen)
  806. # sanity check
  807. if reps == 0:
  808. DATALEN = 0
  809. # Get the random data
  810. if randomlen > 0:
  811. # print a dot after every DOTDATALEN data is verified, rounding up
  812. dot_reps = self._calculate_reps(DOTDATALEN, randomlen)
  813. # make sure we get at least one dot per transmission
  814. dot_reps = min(reps, dot_reps)
  815. with open('/dev/urandom', 'r') as randfp:
  816. tmpdata = randfp.read(randomlen)
  817. else:
  818. dot_reps = 0
  819. tmpdata = {}
  820. # now make the connections
  821. bind_to = ('127.0.0.1', LISTEN_PORT)
  822. tt = chutney.Traffic.TrafficTester(bind_to, tmpdata, TIMEOUT, reps,
  823. dot_reps)
  824. client_list = filter(lambda n:
  825. n._env['tag'] == 'c' or n._env['tag'] == 'bc',
  826. self._nodes)
  827. exit_list = filter(lambda n:
  828. ('exit' in n._env.keys()) and n._env['exit'] == 1,
  829. self._nodes)
  830. hs_list = filter(lambda n:
  831. n._env['tag'] == 'h',
  832. self._nodes)
  833. if len(client_list) == 0:
  834. print(" Unable to verify network: no client nodes available")
  835. return False
  836. if len(exit_list) == 0 and len(hs_list) == 0:
  837. print(" Unable to verify network: no exit/hs nodes available")
  838. print(" Exit nodes must be declared 'relay=1, exit=1'")
  839. print(" HS nodes must be declared 'tag=\"hs\"'")
  840. return False
  841. print("Connecting:")
  842. # the number of tor nodes in paths which will send DATALEN data
  843. # if a node is used in two paths, we count it twice
  844. # this is a lower bound, as cannabilised circuits are one node longer
  845. total_path_node_count = 0
  846. total_path_node_count += self._configure_exits(tt, bind_to, tmpdata,
  847. reps, client_list,
  848. exit_list, LISTEN_PORT)
  849. total_path_node_count += self._configure_hs(tt, tmpdata, reps,
  850. client_list, hs_list,
  851. HS_PORT, LISTEN_PORT)
  852. print("Transmitting Data:")
  853. start_time = time.clock()
  854. status = tt.run()
  855. end_time = time.clock()
  856. # if we fail, don't report the bandwidth
  857. if not status:
  858. return status
  859. # otherwise, report bandwidth used, if sufficient data was transmitted
  860. self._report_bandwidth(DATALEN, total_path_node_count,
  861. start_time, end_time)
  862. return status
  863. # In order to performance test a tor network, we need to transmit
  864. # several hundred megabytes of data or more. Passing around this
  865. # much data in Python has its own performance impacts, so we provide
  866. # a smaller amount of random data instead, and repeat it to DATALEN
  867. def _calculate_randomlen(self, datalen):
  868. MAX_RANDOMLEN = 128 * 1024 # Octets.
  869. if datalen > MAX_RANDOMLEN:
  870. return MAX_RANDOMLEN
  871. else:
  872. return datalen
  873. def _calculate_reps(self, datalen, replen):
  874. # sanity checks
  875. if datalen == 0 or replen == 0:
  876. return 0
  877. # effectively rounds datalen up to the nearest replen
  878. if replen < datalen:
  879. return (datalen + replen - 1) / replen
  880. else:
  881. return 1
  882. # if there are any exits, each client / bridge client transmits
  883. # via 4 nodes (including the client) to an arbitrary exit
  884. # Each client binds directly to 127.0.0.1:LISTEN_PORT via an Exit relay
  885. def _configure_exits(self, tt, bind_to, tmpdata, reps, client_list,
  886. exit_list, LISTEN_PORT):
  887. CLIENT_EXIT_PATH_NODES = 4
  888. connection_count = self._dfltEnv['connection_count']
  889. exit_path_node_count = 0
  890. if len(exit_list) > 0:
  891. exit_path_node_count += (len(client_list) *
  892. CLIENT_EXIT_PATH_NODES *
  893. connection_count)
  894. for op in client_list:
  895. print(" Exit to %s:%d via client %s:%s"
  896. % ('127.0.0.1', LISTEN_PORT,
  897. 'localhost', op._env['socksport']))
  898. for i in range(connection_count):
  899. proxy = ('localhost', int(op._env['socksport']))
  900. tt.add(chutney.Traffic.Source(tt, bind_to, tmpdata, proxy,
  901. reps))
  902. return exit_path_node_count
  903. # The HS redirects .onion connections made to hs_hostname:HS_PORT
  904. # to the Traffic Tester's 127.0.0.1:LISTEN_PORT
  905. # an arbitrary client / bridge client transmits via 8 nodes
  906. # (including the client and hs) to each hidden service
  907. # Instead of binding directly to LISTEN_PORT via an Exit relay,
  908. # we bind to hs_hostname:HS_PORT via a hidden service connection
  909. def _configure_hs(self, tt, tmpdata, reps, client_list, hs_list, HS_PORT,
  910. LISTEN_PORT):
  911. CLIENT_HS_PATH_NODES = 8
  912. connection_count = self._dfltEnv['connection_count']
  913. hs_path_node_count = (len(hs_list) * CLIENT_HS_PATH_NODES *
  914. connection_count)
  915. # Each client in hs_client_list connects to each hs
  916. if self._dfltEnv['hs_multi_client']:
  917. hs_client_list = client_list
  918. hs_path_node_count *= len(client_list)
  919. else:
  920. # only use the first client in the list
  921. hs_client_list = client_list[:1]
  922. # Setup the connections from each client in hs_client_list to each hs
  923. for hs in hs_list:
  924. hs_bind_to = (hs._env['hs_hostname'], HS_PORT)
  925. for client in hs_client_list:
  926. print(" HS to %s:%d (%s:%d) via client %s:%s"
  927. % (hs._env['hs_hostname'], HS_PORT,
  928. '127.0.0.1', LISTEN_PORT,
  929. 'localhost', client._env['socksport']))
  930. for i in range(connection_count):
  931. proxy = ('localhost', int(client._env['socksport']))
  932. tt.add(chutney.Traffic.Source(tt, hs_bind_to, tmpdata,
  933. proxy, reps))
  934. return hs_path_node_count
  935. # calculate the single stream bandwidth and overall tor bandwidth
  936. # the single stream bandwidth is the bandwidth of the
  937. # slowest stream of all the simultaneously transmitted streams
  938. # the overall bandwidth estimates the simultaneous bandwidth between
  939. # all tor nodes over all simultaneous streams, assuming:
  940. # * minimum path lengths (no cannibalized circuits)
  941. # * unlimited network bandwidth (that is, localhost)
  942. # * tor performance is CPU-limited
  943. # This be used to estimate the bandwidth capacity of a CPU-bound
  944. # tor relay running on this machine
  945. def _report_bandwidth(self, data_length, total_path_node_count,
  946. start_time, end_time):
  947. # otherwise, if we sent at least 5 MB cumulative total, and
  948. # it took us at least a second to send, report bandwidth
  949. MIN_BWDATA = 5 * 1024 * 1024 # Octets.
  950. MIN_ELAPSED_TIME = 1.0 # Seconds.
  951. cumulative_data_sent = total_path_node_count * data_length
  952. elapsed_time = end_time - start_time
  953. if (cumulative_data_sent >= MIN_BWDATA and
  954. elapsed_time >= MIN_ELAPSED_TIME):
  955. # Report megabytes per second
  956. BWDIVISOR = 1024*1024
  957. single_stream_bandwidth = (data_length / elapsed_time / BWDIVISOR)
  958. overall_bandwidth = (cumulative_data_sent / elapsed_time /
  959. BWDIVISOR)
  960. print("Single Stream Bandwidth: %.2f MBytes/s"
  961. % single_stream_bandwidth)
  962. print("Overall tor Bandwidth: %.2f MBytes/s"
  963. % overall_bandwidth)
  964. def ConfigureNodes(nodelist):
  965. network = _THE_NETWORK
  966. for n in nodelist:
  967. network._addNode(n)
  968. if n._env['bridgeauthority']:
  969. network._dfltEnv['hasbridgeauth'] = True
  970. def usage(network):
  971. return "\n".join(["Usage: chutney {command} {networkfile}",
  972. "Known commands are: %s" % (
  973. " ".join(x for x in dir(network)
  974. if not x.startswith("_")))])
  975. def exit_on_error(err_msg):
  976. print("Error: {0}\n".format(err_msg))
  977. print(usage(_THE_NETWORK))
  978. sys.exit(1)
  979. def runConfigFile(verb, data):
  980. _GLOBALS = dict(_BASE_ENVIRON=_BASE_ENVIRON,
  981. Node=Node,
  982. ConfigureNodes=ConfigureNodes,
  983. _THE_NETWORK=_THE_NETWORK)
  984. exec(data, _GLOBALS)
  985. network = _GLOBALS['_THE_NETWORK']
  986. if not hasattr(network, verb):
  987. print(usage(network))
  988. print("Error: I don't know how to %s." % verb)
  989. return
  990. return getattr(network, verb)()
  991. def parseArgs():
  992. if len(sys.argv) < 3:
  993. exit_on_error("Not enough arguments given.")
  994. if not os.path.isfile(sys.argv[2]):
  995. exit_on_error("Cannot find networkfile: {0}.".format(sys.argv[2]))
  996. return {'network_cfg': sys.argv[2], 'action': sys.argv[1]}
  997. def main():
  998. global _BASE_ENVIRON
  999. global _TORRC_OPTIONS
  1000. global _THE_NETWORK
  1001. _BASE_ENVIRON = TorEnviron(chutney.Templating.Environ(**DEFAULTS))
  1002. # _TORRC_OPTIONS gets initialised on demand as a map of
  1003. # "/path/to/tor" => ["SupportedOption1", "SupportedOption2", ...]
  1004. # Or it can be pre-populated as a static whitelist of options
  1005. _TORRC_OPTIONS = dict()
  1006. _THE_NETWORK = Network(_BASE_ENVIRON)
  1007. args = parseArgs()
  1008. f = open(args['network_cfg'])
  1009. result = runConfigFile(args['action'], f)
  1010. if result is False:
  1011. return -1
  1012. return 0
  1013. if __name__ == '__main__':
  1014. sys.exit(main())