TorNet.py 43 KB

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