TorNet.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. #!/usr/bin/python
  2. #
  3. # Copyright 2011 Nick Mathewson, Michael Stone
  4. #
  5. # You may do anything with this work that copyright law would normally
  6. # restrict, so long as you retain the above notice(s) and this license
  7. # in all redistributed copies and derived works. There is no warranty.
  8. from __future__ import with_statement
  9. # Get verbose tracebacks, so we can diagnose better.
  10. import cgitb
  11. cgitb.enable(format="plain")
  12. import os
  13. import signal
  14. import subprocess
  15. import sys
  16. import re
  17. import errno
  18. import time
  19. import chutney.Templating
  20. def mkdir_p(d, mode=0777):
  21. """Create directory 'd' and all of its parents as needed. Unlike
  22. os.makedirs, does not give an error if d already exists.
  23. """
  24. try:
  25. os.makedirs(d,mode=mode)
  26. except OSError, e:
  27. if e.errno == errno.EEXIST:
  28. return
  29. raise
  30. class Node(object):
  31. """A Node represents a Tor node or a set of Tor nodes. It's created
  32. in a network configuration file.
  33. This class is responsible for holding the user's selected node
  34. configuration, and figuring out how the node needs to be
  35. configured and launched.
  36. """
  37. ## Fields:
  38. # _parent
  39. # _env
  40. # _builder
  41. # _controller
  42. ########
  43. # Users are expected to call these:
  44. def __init__(self, parent=None, **kwargs):
  45. self._parent = parent
  46. self._env = self._createEnviron(parent, kwargs)
  47. self._builder = None
  48. self._controller = None
  49. def getN(self, N):
  50. return [ Node(self) for _ in xrange(N) ]
  51. def specialize(self, **kwargs):
  52. return Node(parent=self, **kwargs)
  53. ######
  54. # Chutney uses these:
  55. def getBuilder(self):
  56. """Return a NodeBuilder instance to set up this node (that is, to
  57. write all the files that need to be in place so that this
  58. node can be run by a NodeController).
  59. """
  60. if self._builder is None:
  61. self._builder = LocalNodeBuilder(self._env)
  62. return self._builder
  63. def getController(self):
  64. """Return a NodeController instance to control this node (that is,
  65. to start it, stop it, see if it's running, etc.)
  66. """
  67. if self._controller is None:
  68. self._controller = LocalNodeController(self._env)
  69. return self._controller
  70. def setNodenum(self, num):
  71. """Assign a value to the 'nodenum' element of this node. Each node
  72. in a network gets its own nodenum.
  73. """
  74. self._env['nodenum'] = num
  75. #####
  76. # These are internal:
  77. def _createEnviron(self, parent, argdict):
  78. """Return an Environ that delegates to the parent node's Environ (if
  79. there is a parent node), or to the default environment.
  80. """
  81. if parent:
  82. parentenv = parent._env
  83. else:
  84. parentenv = self._getDefaultEnviron()
  85. return TorEnviron(parentenv, **argdict)
  86. def _getDefaultEnviron(self):
  87. """Return the default environment. Any variables that we can't find
  88. set for any particular node, we look for here.
  89. """
  90. return _BASE_ENVIRON
  91. class _NodeCommon(object):
  92. """Internal helper class for functionality shared by some NodeBuilders
  93. and some NodeControllers."""
  94. # XXXX maybe this should turn into a mixin.
  95. def __init__(self, env):
  96. self._env = env
  97. def expand(self, pat, includePath=(".",)):
  98. return chutney.Templating.Template(pat, includePath).format(self._env)
  99. def _getTorrcFname(self):
  100. """Return the name of the file where we'll be writing torrc"""
  101. return self.expand("${torrc_fname}")
  102. class NodeBuilder(_NodeCommon):
  103. """Abstract base class. A NodeBuilder is responsible for doing all the
  104. one-time prep needed to set up a node in a network.
  105. """
  106. def __init__(self, env):
  107. _NodeCommon.__init__(self, env)
  108. def checkConfig(self, net):
  109. """Try to format our torrc; raise an exception if we can't.
  110. """
  111. def preConfig(self, net):
  112. """Called on all nodes before any nodes configure: generates keys as
  113. needed.
  114. """
  115. def config(self, net):
  116. """Called to configure a node: creates a torrc file for it."""
  117. def postConfig(self, net):
  118. """Called on each nodes after all nodes configure."""
  119. class NodeController(_NodeCommon):
  120. """Abstract base class. A NodeController is responsible for running a
  121. node on the network.
  122. """
  123. def __init__(self, env):
  124. _NodeCommon.__init__(self, env)
  125. def check(self, listRunning=True, listNonRunning=False):
  126. """See if this node is running, stopped, or crashed. If it's running
  127. and listRunning is set, print a short statement. If it's
  128. stopped and listNonRunning is set, then print a short statement.
  129. If it's crashed, print a statement. Return True if the
  130. node is running, false otherwise.
  131. """
  132. def start(self):
  133. """Try to start this node; return True if we succeeded or it was
  134. already running, False if we failed."""
  135. def stop(self, sig=signal.SIGINT):
  136. """Try to stop this node by sending it the signal 'sig'."""
  137. class LocalNodeBuilder(NodeBuilder):
  138. ## Environment members used:
  139. # torrc -- which torrc file to use
  140. # torrc_template_path -- path to search for torrc files and include files
  141. # authority -- bool -- are we an authority?
  142. # bridgeauthority -- bool -- are we a bridge authority?
  143. # relay -- bool -- are we a relay?
  144. # bridge -- bool -- are we a bridge?
  145. # nodenum -- int -- set by chutney -- which unique node index is this?
  146. # dir -- path -- set by chutney -- data directory for this tor
  147. # tor_gencert -- path to tor_gencert binary
  148. # tor -- path to tor binary
  149. # auth_cert_lifetime -- lifetime of authority certs, in months.
  150. # ip -- IP to listen on (used only if authority)
  151. # orport, dirport -- (used only if authority)
  152. # fingerprint -- used only if authority
  153. # dirserver_flags -- used only if authority
  154. # nick -- nickname of this router
  155. ## Environment members set
  156. # fingerprint -- hex router key fingerprint
  157. # nodenum -- int -- set by chutney -- which unique node index is this?
  158. def __init__(self, env):
  159. NodeBuilder.__init__(self, env)
  160. self._env = env
  161. def _createTorrcFile(self, checkOnly=False):
  162. """Write the torrc file for this node. If checkOnly, just make sure
  163. that the formatting is indeed possible.
  164. """
  165. fn_out = self._getTorrcFname()
  166. torrc_template = self._getTorrcTemplate()
  167. output = torrc_template.format(self._env)
  168. if checkOnly:
  169. # XXXX Is it time-cosuming to format? If so, cache here.
  170. return
  171. with open(fn_out, 'w') as f:
  172. f.write(output)
  173. def _getTorrcTemplate(self):
  174. """Return the template used to write the torrc for this node."""
  175. template_path = self._env['torrc_template_path']
  176. return chutney.Templating.Template("$${include:$torrc}",
  177. includePath=template_path)
  178. def _getFreeVars(self):
  179. """Return a set of the free variables in the torrc template for this
  180. node.
  181. """
  182. template = self._getTorrcTemplate()
  183. return template.freevars(self._env)
  184. def checkConfig(self, net):
  185. """Try to format our torrc; raise an exception if we can't.
  186. """
  187. self._createTorrcFile(checkOnly=True)
  188. def preConfig(self, net):
  189. """Called on all nodes before any nodes configure: generates keys as
  190. needed.
  191. """
  192. self._makeDataDir()
  193. if self._env['authority']:
  194. self._genAuthorityKey()
  195. if self._env['relay']:
  196. self._genRouterKey()
  197. def config(self, net):
  198. """Called to configure a node: creates a torrc file for it."""
  199. self._createTorrcFile()
  200. #self._createScripts()
  201. def postConfig(self, net):
  202. """Called on each nodes after all nodes configure."""
  203. #self.net.addNode(self)
  204. pass
  205. def _makeDataDir(self):
  206. """Create the data directory (with keys subdirectory) for this node.
  207. """
  208. datadir = self._env['dir']
  209. mkdir_p(os.path.join(datadir, 'keys'))
  210. def _genAuthorityKey(self):
  211. """Generate an authority identity and signing key for this authority,
  212. if they do not already exist."""
  213. datadir = self._env['dir']
  214. tor_gencert = self._env['tor_gencert']
  215. lifetime = self._env['auth_cert_lifetime']
  216. idfile = os.path.join(datadir,'keys',"authority_identity_key")
  217. skfile = os.path.join(datadir,'keys',"authority_signing_key")
  218. certfile = os.path.join(datadir,'keys',"authority_certificate")
  219. addr = self.expand("${ip}:${dirport}")
  220. passphrase = self._env['auth_passphrase']
  221. if all(os.path.exists(f) for f in [idfile, skfile, certfile]):
  222. return
  223. cmdline = [
  224. tor_gencert,
  225. '--create-identity-key',
  226. '--passphrase-fd', '0',
  227. '-i', idfile,
  228. '-s', skfile,
  229. '-c', certfile,
  230. '-m', str(lifetime),
  231. '-a', addr]
  232. print "Creating identity key %s for %s with %s"%(
  233. idfile,self._env['nick']," ".join(cmdline))
  234. p = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
  235. p.communicate(passphrase+"\n")
  236. assert p.returncode == 0 #XXXX BAD!
  237. def _genRouterKey(self):
  238. """Generate an identity key for this router, unless we already have,
  239. and set up the 'fingerprint' entry in the Environ.
  240. """
  241. datadir = self._env['dir']
  242. tor = self._env['tor']
  243. idfile = os.path.join(datadir,'keys',"identity_key")
  244. cmdline = [
  245. tor,
  246. "--quiet",
  247. "--list-fingerprint",
  248. "--orport", "1",
  249. "--dirserver",
  250. "xyzzy 127.0.0.1:1 ffffffffffffffffffffffffffffffffffffffff",
  251. "--datadirectory", datadir ]
  252. p = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
  253. stdout, stderr = p.communicate()
  254. fingerprint = "".join(stdout.split()[1:])
  255. assert re.match(r'^[A-F0-9]{40}$', fingerprint)
  256. self._env['fingerprint'] = fingerprint
  257. def _getAltAuthLines(self):
  258. """Return a combination of AlternateDirAuthority,
  259. AlternateHSAuthority and AlternateBridgeAuthority lines for
  260. this Node, appropriately. Non-authorities return ""."""
  261. if not self._env['authority']:
  262. return ""
  263. datadir = self._env['dir']
  264. certfile = os.path.join(datadir,'keys',"authority_certificate")
  265. v3id = None
  266. with open(certfile, 'r') as f:
  267. for line in f:
  268. if line.startswith("fingerprint"):
  269. v3id = line.split()[1].strip()
  270. break
  271. assert v3id is not None
  272. if self._env['bridgeauthority']:
  273. # Bridge authorities return AlternateBridgeAuthority with
  274. # the 'bridge' flag set.
  275. options = ("AlternateBridgeAuthority",)
  276. self._env['dirserver_flags'] += " bridge"
  277. else:
  278. # Directory authorities return AlternateDirAuthority with
  279. # the 'hs' and 'v3ident' flags set.
  280. options = ("AlternateDirAuthority",)
  281. self._env['dirserver_flags'] += " hs v3ident=%s" % v3id
  282. authlines = ""
  283. for authopt in options:
  284. authlines += "%s %s orport=%s %s %s:%s %s\n" %(
  285. authopt, self._env['nick'], self._env['orport'],
  286. self._env['dirserver_flags'], self._env['ip'],
  287. self._env['dirport'], self._env['fingerprint'])
  288. return authlines
  289. def _getBridgeLines(self):
  290. """Return potential Bridge line for this Node. Non-bridge
  291. relays return "".
  292. """
  293. if not self._env['bridge']:
  294. return ""
  295. return "Bridge %s:%s\n" % (self._env['ip'], self._env['orport'])
  296. class LocalNodeController(NodeController):
  297. def __init__(self, env):
  298. NodeController.__init__(self, env)
  299. self._env = env
  300. def getPid(self):
  301. """Assuming that this node has its pidfile in ${dir}/pid, return
  302. the pid of the running process, or None if there is no pid in the
  303. file.
  304. """
  305. pidfile = os.path.join(self._env['dir'], 'pid')
  306. if not os.path.exists(pidfile):
  307. return None
  308. with open(pidfile, 'r') as f:
  309. return int(f.read())
  310. def isRunning(self, pid=None):
  311. """Return true iff this node is running. (If 'pid' is provided, we
  312. assume that the pid provided is the one of this node. Otherwise
  313. we call getPid().
  314. """
  315. if pid is None:
  316. pid = self.getPid()
  317. if pid is None:
  318. return False
  319. try:
  320. os.kill(pid, 0) # "kill 0" == "are you there?"
  321. except OSError, e:
  322. if e.errno == errno.ESRCH:
  323. return False
  324. raise
  325. # okay, so the process exists. Say "True" for now.
  326. # XXXX check if this is really tor!
  327. return True
  328. def check(self, listRunning=True, listNonRunning=False):
  329. """See if this node is running, stopped, or crashed. If it's running
  330. and listRunning is set, print a short statement. If it's
  331. stopped and listNonRunning is set, then print a short statement.
  332. If it's crashed, print a statement. Return True if the
  333. node is running, false otherwise.
  334. """
  335. # XXX Split this into "check" and "print" parts.
  336. pid = self.getPid()
  337. running = self.isRunning(pid)
  338. nick = self._env['nick']
  339. dir = self._env['dir']
  340. if running:
  341. if listRunning:
  342. print "%s is running with PID %s"%(nick,pid)
  343. return True
  344. elif os.path.exists(os.path.join(dir, "core.%s"%pid)):
  345. if listNonRunning:
  346. print "%s seems to have crashed, and left core file core.%s"%(
  347. nick,pid)
  348. return False
  349. else:
  350. if listNonRunning:
  351. print "%s is stopped"%nick
  352. return False
  353. def hup(self):
  354. """Send a SIGHUP to this node, if it's running."""
  355. pid = self.getPid()
  356. running = self.isRunning()
  357. nick = self._env['nick']
  358. if self.isRunning():
  359. print "Sending sighup to %s"%nick
  360. os.kill(pid, signal.SIGHUP)
  361. return True
  362. else:
  363. print "%s is not running"%nick
  364. return False
  365. def start(self):
  366. """Try to start this node; return True if we succeeded or it was
  367. already running, False if we failed."""
  368. if self.isRunning():
  369. print "%s is already running"%self._env['nick']
  370. return True
  371. torrc = self._getTorrcFname()
  372. cmdline = [
  373. self._env['tor'],
  374. "--quiet",
  375. "-f", torrc,
  376. ]
  377. p = subprocess.Popen(cmdline)
  378. # XXXX this requires that RunAsDaemon is set.
  379. p.wait()
  380. if p.returncode != 0:
  381. print "Couldn't launch %s (%s): %s"%(self._env['nick'],
  382. " ".join(cmdline),
  383. p.returncode)
  384. return False
  385. return True
  386. def stop(self, sig=signal.SIGINT):
  387. """Try to stop this node by sending it the signal 'sig'."""
  388. pid = self.getPid()
  389. if not self.isRunning(pid):
  390. print "%s is not running"%self._env['nick']
  391. return
  392. os.kill(pid, sig)
  393. DEFAULTS = {
  394. 'authority' : False,
  395. 'bridgeauthority' : False,
  396. 'relay' : False,
  397. 'bridge' : False,
  398. 'connlimit' : 60,
  399. 'net_base_dir' : 'net',
  400. 'tor' : 'tor',
  401. 'auth_cert_lifetime' : 12,
  402. 'ip' : '127.0.0.1',
  403. 'dirserver_flags' : 'no-v2',
  404. 'chutney_dir' : '.',
  405. 'torrc_fname' : '${dir}/torrc',
  406. 'orport_base' : 5000,
  407. 'dirport_base' : 7000,
  408. 'controlport_base' : 8000,
  409. 'socksport_base' : 9000,
  410. 'authorities' : "AlternateDirAuthority bleargh bad torrc file!",
  411. 'bridges' : "Bridge bleargh bad torrc file!",
  412. 'core' : True,
  413. }
  414. class TorEnviron(chutney.Templating.Environ):
  415. """Subclass of chutney.Templating.Environ to implement commonly-used
  416. substitutions.
  417. Environment fields provided:
  418. orport, controlport, socksport, dirport:
  419. dir:
  420. nick:
  421. tor_gencert:
  422. auth_passphrase:
  423. torrc_template_path:
  424. Environment fields used:
  425. nodenum
  426. tag
  427. orport_base, controlport_base, socksport_base, dirport_base
  428. chutney_dir
  429. tor
  430. XXXX document the above. Or document all fields in one place?
  431. """
  432. def __init__(self,parent=None,**kwargs):
  433. chutney.Templating.Environ.__init__(self, parent=parent, **kwargs)
  434. def _get_orport(self, my):
  435. return my['orport_base']+my['nodenum']
  436. def _get_controlport(self, my):
  437. return my['controlport_base']+my['nodenum']
  438. def _get_socksport(self, my):
  439. return my['socksport_base']+my['nodenum']
  440. def _get_dirport(self, my):
  441. return my['dirport_base']+my['nodenum']
  442. def _get_dir(self, my):
  443. return os.path.abspath(os.path.join(my['net_base_dir'],
  444. "nodes",
  445. "%03d%s"%(my['nodenum'], my['tag'])))
  446. def _get_nick(self, my):
  447. return "test%03d%s"%(my['nodenum'], my['tag'])
  448. def _get_tor_gencert(self, my):
  449. return my['tor']+"-gencert"
  450. def _get_auth_passphrase(self, my):
  451. return self['nick'] # OMG TEH SECURE!
  452. def _get_torrc_template_path(self, my):
  453. return [ os.path.join(my['chutney_dir'], 'torrc_templates') ]
  454. class Network(object):
  455. """A network of Tor nodes, plus functions to manipulate them
  456. """
  457. def __init__(self,defaultEnviron):
  458. self._nodes = []
  459. self._dfltEnv = defaultEnviron
  460. self._nextnodenum = 0
  461. def _addNode(self, n):
  462. n.setNodenum(self._nextnodenum)
  463. self._nextnodenum += 1
  464. self._nodes.append(n)
  465. def _checkConfig(self):
  466. for n in self._nodes:
  467. n.getBuilder().checkConfig(self)
  468. def configure(self):
  469. network = self
  470. altauthlines = []
  471. bridgelines = []
  472. builders = [ n.getBuilder() for n in self._nodes ]
  473. self._checkConfig()
  474. # XXX don't change node names or types or count if anything is
  475. # XXX running!
  476. for b in builders:
  477. b.preConfig(network)
  478. altauthlines.append(b._getAltAuthLines())
  479. bridgelines.append(b._getBridgeLines())
  480. self._dfltEnv['authorities'] = "".join(altauthlines)
  481. self._dfltEnv['bridges'] = "".join(bridgelines)
  482. for b in builders:
  483. b.config(network)
  484. for b in builders:
  485. b.postConfig(network)
  486. def status(self):
  487. statuses = [ n.getController().check() for n in self._nodes]
  488. n_ok = len([x for x in statuses if x])
  489. print "%d/%d nodes are running"%(n_ok,len(self._nodes))
  490. def restart(self):
  491. self.stop()
  492. self.start()
  493. def start(self):
  494. print "Starting nodes"
  495. return all([n.getController().start() for n in self._nodes])
  496. def hup(self):
  497. print "Sending SIGHUP to nodes"
  498. return all([n.getController().hup() for n in self._nodes])
  499. def stop(self):
  500. controllers = [ n.getController() for n in self._nodes ]
  501. for sig, desc in [(signal.SIGINT, "SIGINT"),
  502. (signal.SIGINT, "another SIGINT"),
  503. (signal.SIGKILL, "SIGKILL")]:
  504. print "Sending %s to nodes"%desc
  505. for c in controllers:
  506. if c.isRunning():
  507. c.stop(sig=sig)
  508. print "Waiting for nodes to finish."
  509. for n in xrange(15):
  510. time.sleep(1)
  511. if all(not c.isRunning() for c in controllers):
  512. return
  513. sys.stdout.write(".")
  514. sys.stdout.flush()
  515. for c in controllers:
  516. n.check(listNonRunning=False)
  517. def ConfigureNodes(nodelist):
  518. network = _THE_NETWORK
  519. for n in nodelist:
  520. network._addNode(n)
  521. def usage(network):
  522. return "\n".join(["Usage: chutney {command} {networkfile}",
  523. "Known commands are: %s" % (
  524. " ".join(x for x in dir(network) if not x.startswith("_")))])
  525. def runConfigFile(verb, f):
  526. _GLOBALS = dict(_BASE_ENVIRON= _BASE_ENVIRON,
  527. Node=Node,
  528. ConfigureNodes=ConfigureNodes,
  529. _THE_NETWORK=_THE_NETWORK)
  530. exec f in _GLOBALS
  531. network = _GLOBALS['_THE_NETWORK']
  532. if not hasattr(network, verb):
  533. print usage(network)
  534. print "Error: I don't know how to %s." % verb
  535. return
  536. getattr(network,verb)()
  537. def main():
  538. global _BASE_ENVIRON
  539. global _THE_NETWORK
  540. _BASE_ENVIRON = TorEnviron(chutney.Templating.Environ(**DEFAULTS))
  541. _THE_NETWORK = Network(_BASE_ENVIRON)
  542. if len(sys.argv) < 3:
  543. print usage(_THE_NETWORK)
  544. print "Error: Not enough arguments given."
  545. sys.exit(1)
  546. f = open(sys.argv[2])
  547. runConfigFile(sys.argv[1], f)
  548. if __name__ == '__main__':
  549. main()