TorNet.py 43 KB

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