TorNet.py 44 KB

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