TorNet.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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. # relay -- bool -- are we a relay
  143. # nodenum -- int -- set by chutney -- which unique node index is this?
  144. # dir -- path -- set by chutney -- data directory for this tor
  145. # tor_gencert -- path to tor_gencert binary
  146. # tor -- path to tor binary
  147. # auth_cert_lifetime -- lifetime of authority certs, in months.
  148. # ip -- IP to listen on (used only if authority)
  149. # orport, dirport -- (used only if authority)
  150. # fingerprint -- used only if authority
  151. # dirserver_flags -- used only if authority
  152. # nick -- nickname of this router
  153. ## Environment members set
  154. # fingerprint -- hex router key fingerprint
  155. # nodenum -- int -- set by chutney -- which unique node index is this?
  156. def __init__(self, env):
  157. NodeBuilder.__init__(self, env)
  158. self._env = env
  159. def _createTorrcFile(self, checkOnly=False):
  160. """Write the torrc file for this node. If checkOnly, just make sure
  161. that the formatting is indeed possible.
  162. """
  163. fn_out = self._getTorrcFname()
  164. torrc_template = self._getTorrcTemplate()
  165. output = torrc_template.format(self._env)
  166. if checkOnly:
  167. # XXXX Is it time-cosuming to format? If so, cache here.
  168. return
  169. with open(fn_out, 'w') as f:
  170. f.write(output)
  171. def _getTorrcTemplate(self):
  172. """Return the template used to write the torrc for this node."""
  173. template_path = self._env['torrc_template_path']
  174. return chutney.Templating.Template("$${include:$torrc}",
  175. includePath=template_path)
  176. def _getFreeVars(self):
  177. """Return a set of the free variables in the torrc template for this
  178. node.
  179. """
  180. template = self._getTorrcTemplate()
  181. return template.freevars(self._env)
  182. def checkConfig(self, net):
  183. """Try to format our torrc; raise an exception if we can't.
  184. """
  185. self._createTorrcFile(checkOnly=True)
  186. def preConfig(self, net):
  187. """Called on all nodes before any nodes configure: generates keys as
  188. needed.
  189. """
  190. self._makeDataDir()
  191. if self._env['authority']:
  192. self._genAuthorityKey()
  193. if self._env['relay']:
  194. self._genRouterKey()
  195. def config(self, net):
  196. """Called to configure a node: creates a torrc file for it."""
  197. self._createTorrcFile()
  198. #self._createScripts()
  199. def postConfig(self, net):
  200. """Called on each nodes after all nodes configure."""
  201. #self.net.addNode(self)
  202. pass
  203. def _makeDataDir(self):
  204. """Create the data directory (with keys subdirectory) for this node.
  205. """
  206. datadir = self._env['dir']
  207. mkdir_p(os.path.join(datadir, 'keys'))
  208. def _genAuthorityKey(self):
  209. """Generate an authority identity and signing key for this authority,
  210. if they do not already exist."""
  211. datadir = self._env['dir']
  212. tor_gencert = self._env['tor_gencert']
  213. lifetime = self._env['auth_cert_lifetime']
  214. idfile = os.path.join(datadir,'keys',"authority_identity_key")
  215. skfile = os.path.join(datadir,'keys',"authority_signing_key")
  216. certfile = os.path.join(datadir,'keys',"authority_certificate")
  217. addr = self.expand("${ip}:${dirport}")
  218. passphrase = self._env['auth_passphrase']
  219. if all(os.path.exists(f) for f in [idfile, skfile, certfile]):
  220. return
  221. cmdline = [
  222. tor_gencert,
  223. '--create-identity-key',
  224. '--passphrase-fd', '0',
  225. '-i', idfile,
  226. '-s', skfile,
  227. '-c', certfile,
  228. '-m', str(lifetime),
  229. '-a', addr]
  230. print "Creating identity key %s for %s with %s"%(
  231. idfile,self._env['nick']," ".join(cmdline))
  232. p = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
  233. p.communicate(passphrase+"\n")
  234. assert p.returncode == 0 #XXXX BAD!
  235. def _genRouterKey(self):
  236. """Generate an identity key for this router, unless we already have,
  237. and set up the 'fingerprint' entry in the Environ.
  238. """
  239. datadir = self._env['dir']
  240. tor = self._env['tor']
  241. idfile = os.path.join(datadir,'keys',"identity_key")
  242. cmdline = [
  243. tor,
  244. "--quiet",
  245. "--list-fingerprint",
  246. "--orport", "1",
  247. "--dirserver",
  248. "xyzzy 127.0.0.1:1 ffffffffffffffffffffffffffffffffffffffff",
  249. "--datadirectory", datadir ]
  250. p = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
  251. stdout, stderr = p.communicate()
  252. fingerprint = "".join(stdout.split()[1:])
  253. assert re.match(r'^[A-F0-9]{40}$', fingerprint)
  254. self._env['fingerprint'] = fingerprint
  255. def _getDirServerLine(self):
  256. """Return a DirServer line for this Node. That'll be "" if this is
  257. not an authority."""
  258. if not self._env['authority']:
  259. return ""
  260. datadir = self._env['dir']
  261. certfile = os.path.join(datadir,'keys',"authority_certificate")
  262. v3id = None
  263. with open(certfile, 'r') as f:
  264. for line in f:
  265. if line.startswith("fingerprint"):
  266. v3id = line.split()[1].strip()
  267. break
  268. assert v3id is not None
  269. return "DirServer %s v3ident=%s orport=%s %s %s:%s %s\n" %(
  270. self._env['nick'], v3id, self._env['orport'],
  271. self._env['dirserver_flags'], self._env['ip'], self._env['dirport'],
  272. self._env['fingerprint'])
  273. class LocalNodeController(NodeController):
  274. def __init__(self, env):
  275. NodeController.__init__(self, env)
  276. self._env = env
  277. def getPid(self):
  278. """Assuming that this node has its pidfile in ${dir}/pid, return
  279. the pid of the running process, or None if there is no pid in the
  280. file.
  281. """
  282. pidfile = os.path.join(self._env['dir'], 'pid')
  283. if not os.path.exists(pidfile):
  284. return None
  285. with open(pidfile, 'r') as f:
  286. return int(f.read())
  287. def isRunning(self, pid=None):
  288. """Return true iff this node is running. (If 'pid' is provided, we
  289. assume that the pid provided is the one of this node. Otherwise
  290. we call getPid().
  291. """
  292. if pid is None:
  293. pid = self.getPid()
  294. if pid is None:
  295. return False
  296. try:
  297. os.kill(pid, 0) # "kill 0" == "are you there?"
  298. except OSError, e:
  299. if e.errno == errno.ESRCH:
  300. return False
  301. raise
  302. # okay, so the process exists. Say "True" for now.
  303. # XXXX check if this is really tor!
  304. return True
  305. def check(self, listRunning=True, listNonRunning=False):
  306. """See if this node is running, stopped, or crashed. If it's running
  307. and listRunning is set, print a short statement. If it's
  308. stopped and listNonRunning is set, then print a short statement.
  309. If it's crashed, print a statement. Return True if the
  310. node is running, false otherwise.
  311. """
  312. # XXX Split this into "check" and "print" parts.
  313. pid = self.getPid()
  314. running = self.isRunning(pid)
  315. nick = self._env['nick']
  316. dir = self._env['dir']
  317. if running:
  318. if listRunning:
  319. print "%s is running with PID %s"%(nick,pid)
  320. return True
  321. elif os.path.exists(os.path.join(dir, "core.%s"%pid)):
  322. if listNonRunning:
  323. print "%s seems to have crashed, and left core file core.%s"%(
  324. nick,pid)
  325. return False
  326. else:
  327. if listNonRunning:
  328. print "%s is stopped"%nick
  329. return False
  330. def hup(self):
  331. """Send a SIGHUP to this node, if it's running."""
  332. pid = self.getPid()
  333. running = self.isRunning()
  334. nick = self._env['nick']
  335. if self.isRunning():
  336. print "Sending sighup to %s"%nick
  337. os.kill(pid, signal.SIGHUP)
  338. return True
  339. else:
  340. print "%s is not running"%nick
  341. return False
  342. def start(self):
  343. """Try to start this node; return True if we succeeded or it was
  344. already running, False if we failed."""
  345. if self.isRunning():
  346. print "%s is already running"%self._env['nick']
  347. return True
  348. torrc = self._getTorrcFname()
  349. cmdline = [
  350. self._env['tor'],
  351. "--quiet",
  352. "-f", torrc,
  353. ]
  354. p = subprocess.Popen(cmdline)
  355. # XXXX this requires that RunAsDaemon is set.
  356. p.wait()
  357. if p.returncode != 0:
  358. print "Couldn't launch %s (%s): %s"%(self._env['nick'],
  359. " ".join(cmdline),
  360. p.returncode)
  361. return False
  362. return True
  363. def stop(self, sig=signal.SIGINT):
  364. """Try to stop this node by sending it the signal 'sig'."""
  365. pid = self.getPid()
  366. if not self.isRunning(pid):
  367. print "%s is not running"%self._env['nick']
  368. return
  369. os.kill(pid, sig)
  370. DEFAULTS = {
  371. 'authority' : False,
  372. 'relay' : False,
  373. 'connlimit' : 60,
  374. 'net_base_dir' : 'net',
  375. 'tor' : 'tor',
  376. 'auth_cert_lifetime' : 12,
  377. 'ip' : '127.0.0.1',
  378. 'dirserver_flags' : 'no-v2',
  379. 'chutney_dir' : '.',
  380. 'torrc_fname' : '${dir}/torrc',
  381. 'orport_base' : 6000,
  382. 'dirport_base' : 7000,
  383. 'controlport_base' : 8000,
  384. 'socksport_base' : 9000,
  385. 'dirservers' : "Dirserver bleargh bad torrc file!",
  386. 'core' : True,
  387. }
  388. class TorEnviron(chutney.Templating.Environ):
  389. """Subclass of chutney.Templating.Environ to implement commonly-used
  390. substitutions.
  391. Environment fields provided:
  392. orport, controlport, socksport, dirport:
  393. dir:
  394. nick:
  395. tor_gencert:
  396. auth_passphrase:
  397. torrc_template_path:
  398. Environment fields used:
  399. nodenum
  400. tag
  401. orport_base, controlport_base, socksport_base, dirport_base
  402. chutney_dir
  403. tor
  404. XXXX document the above. Or document all fields in one place?
  405. """
  406. def __init__(self,parent=None,**kwargs):
  407. chutney.Templating.Environ.__init__(self, parent=parent, **kwargs)
  408. def _get_orport(self, my):
  409. return my['orport_base']+my['nodenum']
  410. def _get_controlport(self, my):
  411. return my['controlport_base']+my['nodenum']
  412. def _get_socksport(self, my):
  413. return my['socksport_base']+my['nodenum']
  414. def _get_dirport(self, my):
  415. return my['dirport_base']+my['nodenum']
  416. def _get_dir(self, my):
  417. return os.path.abspath(os.path.join(my['net_base_dir'],
  418. "nodes",
  419. "%03d%s"%(my['nodenum'], my['tag'])))
  420. def _get_nick(self, my):
  421. return "test%03d%s"%(my['nodenum'], my['tag'])
  422. def _get_tor_gencert(self, my):
  423. return my['tor']+"-gencert"
  424. def _get_auth_passphrase(self, my):
  425. return self['nick'] # OMG TEH SECURE!
  426. def _get_torrc_template_path(self, my):
  427. return [ os.path.join(my['chutney_dir'], 'torrc_templates') ]
  428. class Network(object):
  429. """A network of Tor nodes, plus functions to manipulate them
  430. """
  431. def __init__(self,defaultEnviron):
  432. self._nodes = []
  433. self._dfltEnv = defaultEnviron
  434. self._nextnodenum = 0
  435. def _addNode(self, n):
  436. n.setNodenum(self._nextnodenum)
  437. self._nextnodenum += 1
  438. self._nodes.append(n)
  439. def _checkConfig(self):
  440. for n in self._nodes:
  441. n.getBuilder().checkConfig(self)
  442. def configure(self):
  443. network = self
  444. dirserverlines = []
  445. builders = [ n.getBuilder() for n in self._nodes ]
  446. self._checkConfig()
  447. # XXX don't change node names or types or count if anything is
  448. # XXX running!
  449. for b in builders:
  450. b.preConfig(network)
  451. dirserverlines.append(b._getDirServerLine())
  452. self._dfltEnv['dirservers'] = "".join(dirserverlines)
  453. for b in builders:
  454. b.config(network)
  455. for b in builders:
  456. b.postConfig(network)
  457. def status(self):
  458. statuses = [ n.getController().check() for n in self._nodes]
  459. n_ok = len([x for x in statuses if x])
  460. print "%d/%d nodes are running"%(n_ok,len(self._nodes))
  461. def restart(self):
  462. self.stop()
  463. self.start()
  464. def start(self):
  465. print "Starting nodes"
  466. return all([n.getController().start() for n in self._nodes])
  467. def hup(self):
  468. print "Sending SIGHUP to nodes"
  469. return all([n.getController().hup() for n in self._nodes])
  470. def stop(self):
  471. controllers = [ n.getController() for n in self._nodes ]
  472. for sig, desc in [(signal.SIGINT, "SIGINT"),
  473. (signal.SIGINT, "another SIGINT"),
  474. (signal.SIGKILL, "SIGKILL")]:
  475. print "Sending %s to nodes"%desc
  476. for c in controllers:
  477. if c.isRunning():
  478. c.stop(sig=sig)
  479. print "Waiting for nodes to finish."
  480. for n in xrange(15):
  481. time.sleep(1)
  482. if all(not c.isRunning() for c in controllers):
  483. return
  484. sys.stdout.write(".")
  485. sys.stdout.flush()
  486. for c in controllers:
  487. n.check(listNonRunning=False)
  488. def ConfigureNodes(nodelist):
  489. network = _THE_NETWORK
  490. for n in nodelist:
  491. network._addNode(n)
  492. def usage(network):
  493. return "\n".join(["Usage: chutney {command} {networkfile}",
  494. "Known commands are: %s" % (
  495. " ".join(x for x in dir(network) if not x.startswith("_")))])
  496. def runConfigFile(verb, f):
  497. _GLOBALS = dict(_BASE_ENVIRON= _BASE_ENVIRON,
  498. Node=Node,
  499. ConfigureNodes=ConfigureNodes,
  500. _THE_NETWORK=_THE_NETWORK)
  501. exec f in _GLOBALS
  502. network = _GLOBALS['_THE_NETWORK']
  503. if not hasattr(network, verb):
  504. print usage(network)
  505. print "Error: I don't know how to %s." % verb
  506. return
  507. getattr(network,verb)()
  508. def main():
  509. global _BASE_ENVIRON
  510. global _THE_NETWORK
  511. _BASE_ENVIRON = TorEnviron(chutney.Templating.Environ(**DEFAULTS))
  512. _THE_NETWORK = Network(_BASE_ENVIRON)
  513. if len(sys.argv) < 3:
  514. print usage(_THE_NETWORK)
  515. print "Error: Not enough arguments given."
  516. sys.exit(1)
  517. f = open(sys.argv[2])
  518. runConfigFile(sys.argv[1], f)
  519. if __name__ == '__main__':
  520. main()