TorNet.py 44 KB

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