TorNet.py 44 KB

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