TorNet.py 44 KB

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