TorNet.py 46 KB

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