test_static_vs_dynamic_lesson.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The static against dynamic lesson: its stand-in script runs and shows what the page says, and its rules hold.
  3. docs/wiki/Static-vs-Dynamic-Sites-Hugo-and-WordPress-and-Recon.md teaches recon with a loopback script and gives
  4. a career section. A script that does not run, a tool pointed at a foreign address, or a career section that names
  5. an employer or an invented link would teach the wrong thing.
  6. """
  7. import re
  8. import socket
  9. import subprocess
  10. import sys
  11. import time
  12. import urllib.error
  13. import urllib.request
  14. from pathlib import Path
  15. ROOT = Path(__file__).resolve().parent.parent
  16. PAGE = ROOT / "docs" / "wiki" / "Static-vs-Dynamic-Sites-Hugo-and-WordPress-and-Recon.md"
  17. FENCE = re.compile(r"^```(\w*)\n(.*?)^```$", re.MULTILINE | re.DOTALL)
  18. URL = re.compile(r"https?://[^\s)>\"'`]+")
  19. ADDR = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
  20. def blocks(tag: str) -> list[str]:
  21. return [b for t, b in FENCE.findall(PAGE.read_text(encoding="utf-8")) if t == tag]
  22. def free_port_pair() -> int:
  23. for base in range(20000, 40000, 7):
  24. socks = []
  25. try:
  26. for p in (base, base + 1):
  27. s = socket.socket()
  28. s.bind(("127.0.0.1", p))
  29. socks.append(s)
  30. return base
  31. except OSError:
  32. continue
  33. finally:
  34. for s in socks:
  35. s.close()
  36. raise RuntimeError("no free port pair")
  37. def fetch(url: str):
  38. try:
  39. with urllib.request.urlopen(url, timeout=5) as r:
  40. return r.status, dict(r.headers), r.read().decode()
  41. except urllib.error.HTTPError as e:
  42. return e.code, dict(e.headers), ""
  43. def test_the_stand_in_sites_show_the_signs_the_page_teaches(tmp_path):
  44. scripts = blocks("python")
  45. assert len(scripts) == 1
  46. script = tmp_path / "siteduo.py"
  47. script.write_text(scripts[0], encoding="utf-8")
  48. base = free_port_pair()
  49. proc = subprocess.Popen([sys.executable, "-I", str(script), "--base-port", str(base)], stdout=subprocess.PIPE, text=True, cwd=tmp_path)
  50. try:
  51. assert "static site" in proc.stdout.readline()
  52. assert "dynamic site" in proc.stdout.readline()
  53. time.sleep(0.2)
  54. s_url, d_url = f"http://127.0.0.1:{base}", f"http://127.0.0.1:{base + 1}"
  55. s_code, s_head, s_body = fetch(s_url + "/")
  56. d_code, d_head, d_body = fetch(d_url + "/")
  57. assert s_code == d_code == 200
  58. assert 'name="generator" content="Hugo' in s_body
  59. assert 'name="generator" content="WordPress' in d_body
  60. assert 'rel="https://api.w.org/"' in d_head["Link"] and "Link" not in s_head
  61. assert "X-Powered-By" in d_head and "X-Powered-By" not in s_head
  62. assert s_head["Server"] == d_head["Server"], "the Server header must not tell them apart"
  63. assert fetch(s_url + "/wp-login.php")[0] == 404
  64. assert fetch(d_url + "/wp-login.php")[0] == 200
  65. assert fetch(s_url + "/wp-json/")[0] == 404
  66. assert fetch(d_url + "/wp-json/")[0] == 200
  67. assert "/wp-admin/" in fetch(d_url + "/robots.txt")[2]
  68. assert "/wp-admin/" not in fetch(s_url + "/robots.txt")[2]
  69. finally:
  70. proc.terminate()
  71. proc.wait(timeout=10)
  72. def test_the_script_only_ever_names_the_loopback_address():
  73. code = blocks("python")[0]
  74. addresses = set(ADDR.findall(code))
  75. assert addresses, "the guard collected nothing"
  76. assert addresses == {"127.0.0.1"}
  77. def test_the_guard_bites_on_a_foreign_address():
  78. assert set(ADDR.findall('connect(("192.0.2.1", 80))')) != {"127.0.0.1"}
  79. def test_every_command_in_the_page_targets_loopback_or_a_documentation_domain():
  80. text = PAGE.read_text(encoding="utf-8")
  81. commands = [line for b in blocks("bash") for line in b.splitlines() if re.search(r"\b(curl|whatweb)\b", line)]
  82. assert commands, "the guard collected nothing"
  83. for line in commands:
  84. assert "127.0.0.1" in line, line
  85. # inline recon commands name only a documentation domain
  86. inline = re.findall(r"`((?:openssl s_client -connect|dig) [^`]+)`", text)
  87. assert inline, "the guard collected nothing"
  88. for cmd in inline:
  89. assert "example.com" in cmd, cmd
  90. def test_the_page_states_the_permission_rule_and_marks_the_stand_ins():
  91. text = PAGE.read_text(encoding="utf-8")
  92. assert "written permission" in text
  93. assert "Recon tools are used **only against sites you own" in text
  94. assert "not real Hugo" in text
  95. assert "Unverified draft" in text or "unverified draft" in text
  96. def test_the_page_names_no_employer_and_links_only_known_community_addresses():
  97. text = PAGE.read_text(encoding="utf-8")
  98. readme = (ROOT / "README.md").read_text(encoding="utf-8")
  99. for addr in ("https://discord.chiefgyk3d.com", "https://matrix-invite.chiefgyk3d.com"):
  100. assert addr in readme, addr
  101. assert addr in text or addr.removeprefix("https://") in text
  102. assert "https://infosecmap.com/" in text
  103. assert "Senior Cybersecurity Engineer" in text and "CISSP" in text
  104. assert not invented_invite(text)
  105. def invented_invite(text: str) -> bool:
  106. return any(x in text for x in ("discord.gg", "discord.com/invite", "matrix.to"))
  107. def test_the_guard_bites_on_an_invented_invite():
  108. assert invented_invite("join https://discord.gg/abc")
  109. assert not invented_invite("join https://discord.chiefgyk3d.com")