test_cmdline_args.py 8.1 KB

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