TorNet.py 44 KB

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