TorNet.py 43 KB

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