test_cmdline_args.py 9.5 KB

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