test_cmdline_args.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. #!/usr/bin/python
  2. import binascii
  3. import hashlib
  4. import os
  5. import re
  6. import shutil
  7. import subprocess
  8. import sys
  9. import tempfile
  10. import unittest
  11. TOR = "./src/or/tor"
  12. TOP_SRCDIR = "."
  13. if len(sys.argv) > 1:
  14. TOR = sys.argv[1]
  15. del sys.argv[1]
  16. if len(sys.argv) > 1:
  17. TOP_SRCDIR = sys.argv[1]
  18. del sys.argv[1]
  19. class UnexpectedSuccess(Exception):
  20. pass
  21. class UnexpectedFailure(Exception):
  22. pass
  23. def contents(fn):
  24. f = open(fn)
  25. try:
  26. return f.read()
  27. finally:
  28. f.close()
  29. def run_tor(args, failure=False):
  30. p = subprocess.Popen([TOR] + args, stdout=subprocess.PIPE)
  31. output, _ = p.communicate()
  32. result = p.poll()
  33. if result and not failure:
  34. raise UnexpectedFailure()
  35. elif not result and failure:
  36. raise UnexpectedSuccess()
  37. return output
  38. def spaceify_fp(fp):
  39. for i in xrange(0, len(fp), 4):
  40. yield fp[i:i+4]
  41. def lines(s):
  42. out = s.split("\n")
  43. if out and out[-1] == '':
  44. del out[-1]
  45. return out
  46. def strip_log_junk(line):
  47. m = re.match(r'([^\[]+\[[a-z]*\] *)(.*)', line)
  48. if not m:
  49. return ""+line
  50. return m.group(2).strip()
  51. def randstring(entropy_bytes):
  52. s = os.urandom(entropy_bytes)
  53. return binascii.b2a_hex(s)
  54. def findLineContaining(lines, s):
  55. for ln in lines:
  56. if s in ln:
  57. return True
  58. return False
  59. class CmdlineTests(unittest.TestCase):
  60. def test_version(self):
  61. out = run_tor(["--version"])
  62. self.failUnless(out.startswith("Tor version "))
  63. self.assertEquals(len(lines(out)), 1)
  64. def test_quiet(self):
  65. out = run_tor(["--quiet", "--quumblebluffin", "1"], failure=True)
  66. self.assertEquals(out, "")
  67. def test_help(self):
  68. out = run_tor(["--help"], failure=False)
  69. out2 = run_tor(["-h"], failure=False)
  70. self.assert_(out.startswith("Copyright (c) 2001"))
  71. self.assert_(out.endswith(
  72. "tor -f <torrc> [args]\n"
  73. "See man page for options, or https://www.torproject.org/ for documentation.\n"))
  74. self.assert_(out == out2)
  75. def test_hush(self):
  76. torrc = tempfile.NamedTemporaryFile(delete=False)
  77. torrc.close()
  78. try:
  79. out = run_tor(["--hush", "-f", torrc.name,
  80. "--quumblebluffin", "1"], failure=True)
  81. finally:
  82. os.unlink(torrc.name)
  83. self.assertEquals(len(lines(out)), 2)
  84. ln = [ strip_log_junk(l) for l in lines(out) ]
  85. self.assertEquals(ln[0], "Failed to parse/validate config: Unknown option 'quumblebluffin'. Failing.")
  86. self.assertEquals(ln[1], "Reading config failed--see warnings above.")
  87. def test_missing_argument(self):
  88. out = run_tor(["--hush", "--hash-password"], failure=True)
  89. self.assertEquals(len(lines(out)), 2)
  90. ln = [ strip_log_junk(l) for l in lines(out) ]
  91. self.assertEquals(ln[0], "Command-line option '--hash-password' with no value. Failing.")
  92. def test_hash_password(self):
  93. out = run_tor(["--hash-password", "woodwose"])
  94. result = lines(out)[-1]
  95. self.assertEquals(result[:3], "16:")
  96. self.assertEquals(len(result), 61)
  97. r = binascii.a2b_hex(result[3:])
  98. self.assertEquals(len(r), 29)
  99. salt, how, hashed = r[:8], r[8], r[9:]
  100. self.assertEquals(len(hashed), 20)
  101. count = (16 + (ord(how) & 15)) << ((ord(how) >> 4) + 6)
  102. stuff = salt + "woodwose"
  103. repetitions = count // len(stuff) + 1
  104. inp = stuff * repetitions
  105. inp = inp[:count]
  106. self.assertEquals(hashlib.sha1(inp).digest(), hashed)
  107. def test_digests(self):
  108. main_c = os.path.join(TOP_SRCDIR, "src", "or", "main.c")
  109. if os.stat(TOR).st_mtime < os.stat(main_c).st_mtime:
  110. self.skipTest(TOR+" not up to date")
  111. out = run_tor(["--digests"])
  112. main_line = [ l for l in lines(out) if l.endswith("/main.c") ]
  113. digest, name = main_line[0].split()
  114. actual = hashlib.sha1(open(main_c).read()).hexdigest()
  115. self.assertEquals(digest, actual)
  116. def test_dump_options(self):
  117. default_torrc = tempfile.NamedTemporaryFile(delete=False)
  118. torrc = tempfile.NamedTemporaryFile(delete=False)
  119. torrc.write("SocksPort 9999")
  120. torrc.close()
  121. default_torrc.write("SafeLogging 0")
  122. default_torrc.close()
  123. out_sh = out_nb = out_fl = None
  124. opts = [ "-f", torrc.name,
  125. "--defaults-torrc", default_torrc.name ]
  126. try:
  127. out_sh = run_tor(["--dump-config", "short"]+opts)
  128. out_nb = run_tor(["--dump-config", "non-builtin"]+opts)
  129. out_fl = run_tor(["--dump-config", "full"]+opts)
  130. out_nr = run_tor(["--dump-config", "bliznert"]+opts,
  131. failure=True)
  132. out_verif = run_tor(["--verify-config"]+opts)
  133. finally:
  134. os.unlink(torrc.name)
  135. os.unlink(default_torrc.name)
  136. self.assertEquals(len(lines(out_sh)), 2)
  137. self.assert_(lines(out_sh)[0].startswith("DataDirectory "))
  138. self.assertEquals(lines(out_sh)[1:],
  139. [ "SocksPort 9999" ])
  140. self.assertEquals(len(lines(out_nb)), 2)
  141. self.assertEquals(lines(out_nb),
  142. [ "SafeLogging 0",
  143. "SocksPort 9999" ])
  144. out_fl = lines(out_fl)
  145. self.assert_(len(out_fl) > 100)
  146. self.assert_("SocksPort 9999" in out_fl)
  147. self.assert_("SafeLogging 0" in out_fl)
  148. self.assert_("ClientOnly 0" in out_fl)
  149. self.assert_(out_verif.endswith("Configuration was valid\n"))
  150. def test_list_fingerprint(self):
  151. tmpdir = tempfile.mkdtemp(prefix='ttca_')
  152. torrc = tempfile.NamedTemporaryFile(delete=False)
  153. torrc.write("ORPort 9999\n")
  154. torrc.write("DataDirectory %s\n"%tmpdir)
  155. torrc.write("Nickname tippi")
  156. torrc.close()
  157. opts = ["-f", torrc.name]
  158. try:
  159. out = run_tor(["--list-fingerprint"]+opts)
  160. fp = contents(os.path.join(tmpdir, "fingerprint"))
  161. finally:
  162. os.unlink(torrc.name)
  163. shutil.rmtree(tmpdir)
  164. out = lines(out)
  165. lastlog = strip_log_junk(out[-2])
  166. lastline = out[-1]
  167. fp = fp.strip()
  168. nn_fp = fp.split()[0]
  169. space_fp = " ".join(spaceify_fp(fp.split()[1]))
  170. self.assertEquals(lastlog,
  171. "Your Tor server's identity key fingerprint is '%s'"%fp)
  172. self.assertEquals(lastline, "tippi %s"%space_fp)
  173. self.assertEquals(nn_fp, "tippi")
  174. def test_list_options(self):
  175. out = lines(run_tor(["--list-torrc-options"]))
  176. self.assert_(len(out)>100)
  177. self.assert_(out[0] <= 'AccountingMax')
  178. self.assert_("UseBridges" in out)
  179. self.assert_("SocksPort" in out)
  180. def test_cmdline_args(self):
  181. default_torrc = tempfile.NamedTemporaryFile(delete=False)
  182. torrc = tempfile.NamedTemporaryFile(delete=False)
  183. torrc.write("SocksPort 9999\n")
  184. torrc.write("SocksPort 9998\n")
  185. torrc.write("ORPort 9000\n")
  186. torrc.write("ORPort 9001\n")
  187. torrc.write("Nickname eleventeen\n")
  188. torrc.write("ControlPort 9500\n")
  189. torrc.close()
  190. default_torrc.write("")
  191. default_torrc.close()
  192. out_sh = out_nb = out_fl = None
  193. opts = [ "-f", torrc.name,
  194. "--defaults-torrc", default_torrc.name,
  195. "--dump-config", "short" ]
  196. try:
  197. out_1 = run_tor(opts)
  198. out_2 = run_tor(opts+["+ORPort", "9003",
  199. "SocksPort", "9090",
  200. "/ControlPort",
  201. "/TransPort",
  202. "+ExtORPort", "9005"])
  203. finally:
  204. os.unlink(torrc.name)
  205. os.unlink(default_torrc.name)
  206. out_1 = [ l for l in lines(out_1) if not l.startswith("DataDir") ]
  207. out_2 = [ l for l in lines(out_2) if not l.startswith("DataDir") ]
  208. self.assertEquals(out_1,
  209. ["ControlPort 9500",
  210. "Nickname eleventeen",
  211. "ORPort 9000",
  212. "ORPort 9001",
  213. "SocksPort 9999",
  214. "SocksPort 9998"])
  215. self.assertEquals(out_2,
  216. ["ExtORPort 9005",
  217. "Nickname eleventeen",
  218. "ORPort 9000",
  219. "ORPort 9001",
  220. "ORPort 9003",
  221. "SocksPort 9090"])
  222. def test_missing_torrc(self):
  223. fname = "nonexistent_file_"+randstring(8)
  224. out = run_tor(["-f", fname, "--verify-config"], failure=True)
  225. ln = [ strip_log_junk(l) for l in lines(out) ]
  226. self.assert_("Unable to open configuration file" in ln[-2])
  227. self.assert_("Reading config failed" in ln[-1])
  228. out = run_tor(["-f", fname, "--verify-config", "--ignore-missing-torrc"])
  229. ln = [ strip_log_junk(l) for l in lines(out) ]
  230. self.assert_(findLineContaining(ln, ", using reasonable defaults"))
  231. self.assert_("Configuration was valid" in ln[-1])
  232. if __name__ == '__main__':
  233. unittest.main()