__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. from __future__ import annotations
  2. import getpass
  3. import hashlib
  4. import json
  5. import os
  6. import pkgutil
  7. import re
  8. import sys
  9. import time
  10. import typing as t
  11. import uuid
  12. from contextlib import ExitStack
  13. from io import BytesIO
  14. from itertools import chain
  15. from os.path import basename
  16. from os.path import join
  17. from zlib import adler32
  18. from .._internal import _log
  19. from ..exceptions import NotFound
  20. from ..exceptions import SecurityError
  21. from ..http import parse_cookie
  22. from ..sansio.utils import host_is_trusted
  23. from ..security import gen_salt
  24. from ..utils import send_file
  25. from ..wrappers.request import Request
  26. from ..wrappers.response import Response
  27. from .console import Console
  28. from .tbtools import DebugFrameSummary
  29. from .tbtools import DebugTraceback
  30. from .tbtools import render_console_html
  31. if t.TYPE_CHECKING:
  32. from _typeshed.wsgi import StartResponse
  33. from _typeshed.wsgi import WSGIApplication
  34. from _typeshed.wsgi import WSGIEnvironment
  35. # A week
  36. PIN_TIME = 60 * 60 * 24 * 7
  37. def hash_pin(pin: str) -> str:
  38. return hashlib.sha1(f"{pin} added salt".encode("utf-8", "replace")).hexdigest()[:12]
  39. _machine_id: str | bytes | None = None
  40. def get_machine_id() -> str | bytes | None:
  41. global _machine_id
  42. if _machine_id is not None:
  43. return _machine_id
  44. def _generate() -> str | bytes | None:
  45. linux = b""
  46. # machine-id is stable across boots, boot_id is not.
  47. for filename in "/etc/machine-id", "/proc/sys/kernel/random/boot_id":
  48. try:
  49. with open(filename, "rb") as f:
  50. value = f.readline().strip()
  51. except OSError:
  52. continue
  53. if value:
  54. linux += value
  55. break
  56. # Containers share the same machine id, add some cgroup
  57. # information. This is used outside containers too but should be
  58. # relatively stable across boots.
  59. try:
  60. with open("/proc/self/cgroup", "rb") as f:
  61. linux += f.readline().strip().rpartition(b"/")[2]
  62. except OSError:
  63. pass
  64. if linux:
  65. return linux
  66. # On OS X, use ioreg to get the computer's serial number.
  67. try:
  68. # subprocess may not be available, e.g. Google App Engine
  69. # https://github.com/pallets/werkzeug/issues/925
  70. from subprocess import PIPE
  71. from subprocess import Popen
  72. dump = Popen(
  73. ["ioreg", "-c", "IOPlatformExpertDevice", "-d", "2"], stdout=PIPE
  74. ).communicate()[0]
  75. match = re.search(b'"serial-number" = <([^>]+)', dump)
  76. if match is not None:
  77. return match.group(1)
  78. except (OSError, ImportError):
  79. pass
  80. # On Windows, use winreg to get the machine guid.
  81. if sys.platform == "win32":
  82. import winreg
  83. try:
  84. with winreg.OpenKey(
  85. winreg.HKEY_LOCAL_MACHINE,
  86. "SOFTWARE\\Microsoft\\Cryptography",
  87. 0,
  88. winreg.KEY_READ | winreg.KEY_WOW64_64KEY,
  89. ) as rk:
  90. guid: str | bytes
  91. guid_type: int
  92. guid, guid_type = winreg.QueryValueEx(rk, "MachineGuid")
  93. if guid_type == winreg.REG_SZ:
  94. return guid.encode()
  95. return guid
  96. except OSError:
  97. pass
  98. return None
  99. _machine_id = _generate()
  100. return _machine_id
  101. class _ConsoleFrame:
  102. """Helper class so that we can reuse the frame console code for the
  103. standalone console.
  104. """
  105. def __init__(self, namespace: dict[str, t.Any]):
  106. self.console = Console(namespace)
  107. self.id = 0
  108. def eval(self, code: str) -> t.Any:
  109. return self.console.eval(code)
  110. def get_pin_and_cookie_name(
  111. app: WSGIApplication,
  112. ) -> tuple[str, str] | tuple[None, None]:
  113. """Given an application object this returns a semi-stable 9 digit pin
  114. code and a random key. The hope is that this is stable between
  115. restarts to not make debugging particularly frustrating. If the pin
  116. was forcefully disabled this returns `None`.
  117. Second item in the resulting tuple is the cookie name for remembering.
  118. """
  119. pin = os.environ.get("WERKZEUG_DEBUG_PIN")
  120. rv = None
  121. num = None
  122. # Pin was explicitly disabled
  123. if pin == "off":
  124. return None, None
  125. # Pin was provided explicitly
  126. if pin is not None and pin.replace("-", "").isdecimal():
  127. # If there are separators in the pin, return it directly
  128. if "-" in pin:
  129. rv = pin
  130. else:
  131. num = pin
  132. modname = getattr(app, "__module__", t.cast(object, app).__class__.__module__)
  133. username: str | None
  134. try:
  135. # getuser imports the pwd module, which does not exist in Google
  136. # App Engine. It may also raise a KeyError if the UID does not
  137. # have a username, such as in Docker.
  138. username = getpass.getuser()
  139. except (ImportError, KeyError):
  140. username = None
  141. mod = sys.modules.get(modname)
  142. # This information only exists to make the cookie unique on the
  143. # computer, not as a security feature.
  144. probably_public_bits = [
  145. username,
  146. modname,
  147. getattr(app, "__name__", type(app).__name__),
  148. getattr(mod, "__file__", None),
  149. ]
  150. # This information is here to make it harder for an attacker to
  151. # guess the cookie name. They are unlikely to be contained anywhere
  152. # within the unauthenticated debug page.
  153. private_bits = [str(uuid.getnode()), get_machine_id()]
  154. h = hashlib.sha1()
  155. for bit in chain(probably_public_bits, private_bits):
  156. if not bit:
  157. continue
  158. if isinstance(bit, str):
  159. bit = bit.encode()
  160. h.update(bit)
  161. h.update(b"cookiesalt")
  162. cookie_name = f"__wzd{h.hexdigest()[:20]}"
  163. # If we need to generate a pin we salt it a bit more so that we don't
  164. # end up with the same value and generate out 9 digits
  165. if num is None:
  166. h.update(b"pinsalt")
  167. num = f"{int(h.hexdigest(), 16):09d}"[:9]
  168. # Format the pincode in groups of digits for easier remembering if
  169. # we don't have a result yet.
  170. if rv is None:
  171. for group_size in 5, 4, 3:
  172. if len(num) % group_size == 0:
  173. rv = "-".join(
  174. num[x : x + group_size].rjust(group_size, "0")
  175. for x in range(0, len(num), group_size)
  176. )
  177. break
  178. else:
  179. rv = num
  180. return rv, cookie_name
  181. class DebuggedApplication:
  182. """Enables debugging support for a given application::
  183. from werkzeug.debug import DebuggedApplication
  184. from myapp import app
  185. app = DebuggedApplication(app, evalex=True)
  186. The ``evalex`` argument allows evaluating expressions in any frame
  187. of a traceback. This works by preserving each frame with its local
  188. state. Some state, such as context globals, cannot be restored with
  189. the frame by default. When ``evalex`` is enabled,
  190. ``environ["werkzeug.debug.preserve_context"]`` will be a callable
  191. that takes a context manager, and can be called multiple times.
  192. Each context manager will be entered before evaluating code in the
  193. frame, then exited again, so they can perform setup and cleanup for
  194. each call.
  195. :param app: the WSGI application to run debugged.
  196. :param evalex: enable exception evaluation feature (interactive
  197. debugging). This requires a non-forking server.
  198. :param request_key: The key that points to the request object in this
  199. environment. This parameter is ignored in current
  200. versions.
  201. :param console_path: the URL for a general purpose console.
  202. :param console_init_func: the function that is executed before starting
  203. the general purpose console. The return value
  204. is used as initial namespace.
  205. :param show_hidden_frames: by default hidden traceback frames are skipped.
  206. You can show them by setting this parameter
  207. to `True`.
  208. :param pin_security: can be used to disable the pin based security system.
  209. :param pin_logging: enables the logging of the pin system.
  210. .. versionchanged:: 2.2
  211. Added the ``werkzeug.debug.preserve_context`` environ key.
  212. """
  213. _pin: str
  214. _pin_cookie: str
  215. def __init__(
  216. self,
  217. app: WSGIApplication,
  218. evalex: bool = False,
  219. request_key: str = "werkzeug.request",
  220. console_path: str = "/console",
  221. console_init_func: t.Callable[[], dict[str, t.Any]] | None = None,
  222. show_hidden_frames: bool = False,
  223. pin_security: bool = True,
  224. pin_logging: bool = True,
  225. ) -> None:
  226. if not console_init_func:
  227. console_init_func = None
  228. self.app = app
  229. self.evalex = evalex
  230. self.frames: dict[int, DebugFrameSummary | _ConsoleFrame] = {}
  231. self.frame_contexts: dict[int, list[t.ContextManager[None]]] = {}
  232. self.request_key = request_key
  233. self.console_path = console_path
  234. self.console_init_func = console_init_func
  235. self.show_hidden_frames = show_hidden_frames
  236. self.secret = gen_salt(20)
  237. self._failed_pin_auth = 0
  238. self.pin_logging = pin_logging
  239. if pin_security:
  240. # Print out the pin for the debugger on standard out.
  241. if os.environ.get("WERKZEUG_RUN_MAIN") == "true" and pin_logging:
  242. _log("warning", " * Debugger is active!")
  243. if self.pin is None:
  244. _log("warning", " * Debugger PIN disabled. DEBUGGER UNSECURED!")
  245. else:
  246. _log("info", " * Debugger PIN: %s", self.pin)
  247. else:
  248. self.pin = None
  249. self.trusted_hosts: list[str] = [".localhost", "127.0.0.1"]
  250. """List of domains to allow requests to the debugger from. A leading dot
  251. allows all subdomains. This only allows ``".localhost"`` domains by
  252. default.
  253. .. versionadded:: 3.0.3
  254. """
  255. @property
  256. def pin(self) -> str | None:
  257. if not hasattr(self, "_pin"):
  258. pin_cookie = get_pin_and_cookie_name(self.app)
  259. self._pin, self._pin_cookie = pin_cookie # type: ignore
  260. return self._pin
  261. @pin.setter
  262. def pin(self, value: str) -> None:
  263. self._pin = value
  264. @property
  265. def pin_cookie_name(self) -> str:
  266. """The name of the pin cookie."""
  267. if not hasattr(self, "_pin_cookie"):
  268. pin_cookie = get_pin_and_cookie_name(self.app)
  269. self._pin, self._pin_cookie = pin_cookie # type: ignore
  270. return self._pin_cookie
  271. def debug_application(
  272. self, environ: WSGIEnvironment, start_response: StartResponse
  273. ) -> t.Iterator[bytes]:
  274. """Run the application and conserve the traceback frames."""
  275. contexts: list[t.ContextManager[t.Any]] = []
  276. if self.evalex:
  277. environ["werkzeug.debug.preserve_context"] = contexts.append
  278. app_iter = None
  279. try:
  280. app_iter = self.app(environ, start_response)
  281. yield from app_iter
  282. if hasattr(app_iter, "close"):
  283. app_iter.close()
  284. except Exception as e:
  285. if hasattr(app_iter, "close"):
  286. app_iter.close() # type: ignore
  287. tb = DebugTraceback(e, skip=1, hide=not self.show_hidden_frames)
  288. for frame in tb.all_frames:
  289. self.frames[id(frame)] = frame
  290. self.frame_contexts[id(frame)] = contexts
  291. is_trusted = bool(self.check_pin_trust(environ))
  292. html = tb.render_debugger_html(
  293. evalex=self.evalex and self.check_host_trust(environ),
  294. secret=self.secret,
  295. evalex_trusted=is_trusted,
  296. )
  297. response = Response(html, status=500, mimetype="text/html")
  298. try:
  299. yield from response(environ, start_response)
  300. except Exception:
  301. # if we end up here there has been output but an error
  302. # occurred. in that situation we can do nothing fancy any
  303. # more, better log something into the error log and fall
  304. # back gracefully.
  305. environ["wsgi.errors"].write(
  306. "Debugging middleware caught exception in streamed "
  307. "response at a point where response headers were already "
  308. "sent.\n"
  309. )
  310. environ["wsgi.errors"].write("".join(tb.render_traceback_text()))
  311. def execute_command( # type: ignore[return]
  312. self,
  313. request: Request,
  314. command: str,
  315. frame: DebugFrameSummary | _ConsoleFrame,
  316. ) -> Response:
  317. """Execute a command in a console."""
  318. if not self.check_host_trust(request.environ):
  319. return SecurityError() # type: ignore[return-value]
  320. contexts = self.frame_contexts.get(id(frame), [])
  321. with ExitStack() as exit_stack:
  322. for cm in contexts:
  323. exit_stack.enter_context(cm)
  324. return Response(frame.eval(command), mimetype="text/html")
  325. def display_console(self, request: Request) -> Response:
  326. """Display a standalone shell."""
  327. if not self.check_host_trust(request.environ):
  328. return SecurityError() # type: ignore[return-value]
  329. if 0 not in self.frames:
  330. if self.console_init_func is None:
  331. ns = {}
  332. else:
  333. ns = dict(self.console_init_func())
  334. ns.setdefault("app", self.app)
  335. self.frames[0] = _ConsoleFrame(ns)
  336. is_trusted = bool(self.check_pin_trust(request.environ))
  337. return Response(
  338. render_console_html(secret=self.secret, evalex_trusted=is_trusted),
  339. mimetype="text/html",
  340. )
  341. def get_resource(self, request: Request, filename: str) -> Response:
  342. """Return a static resource from the shared folder."""
  343. path = join("shared", basename(filename))
  344. try:
  345. data = pkgutil.get_data(__package__, path)
  346. except OSError:
  347. return NotFound() # type: ignore[return-value]
  348. else:
  349. if data is None:
  350. return NotFound() # type: ignore[return-value]
  351. etag = str(adler32(data) & 0xFFFFFFFF)
  352. return send_file(
  353. BytesIO(data), request.environ, download_name=filename, etag=etag
  354. )
  355. def check_pin_trust(self, environ: WSGIEnvironment) -> bool | None:
  356. """Checks if the request passed the pin test. This returns `True` if the
  357. request is trusted on a pin/cookie basis and returns `False` if not.
  358. Additionally if the cookie's stored pin hash is wrong it will return
  359. `None` so that appropriate action can be taken.
  360. """
  361. if self.pin is None:
  362. return True
  363. val = parse_cookie(environ).get(self.pin_cookie_name)
  364. if not val or "|" not in val:
  365. return False
  366. ts_str, pin_hash = val.split("|", 1)
  367. try:
  368. ts = int(ts_str)
  369. except ValueError:
  370. return False
  371. if pin_hash != hash_pin(self.pin):
  372. return None
  373. return (time.time() - PIN_TIME) < ts
  374. def check_host_trust(self, environ: WSGIEnvironment) -> bool:
  375. return host_is_trusted(environ.get("HTTP_HOST"), self.trusted_hosts)
  376. def _fail_pin_auth(self) -> None:
  377. time.sleep(5.0 if self._failed_pin_auth > 5 else 0.5)
  378. self._failed_pin_auth += 1
  379. def pin_auth(self, request: Request) -> Response:
  380. """Authenticates with the pin."""
  381. if not self.check_host_trust(request.environ):
  382. return SecurityError() # type: ignore[return-value]
  383. exhausted = False
  384. auth = False
  385. trust = self.check_pin_trust(request.environ)
  386. pin = t.cast(str, self.pin)
  387. # If the trust return value is `None` it means that the cookie is
  388. # set but the stored pin hash value is bad. This means that the
  389. # pin was changed. In this case we count a bad auth and unset the
  390. # cookie. This way it becomes harder to guess the cookie name
  391. # instead of the pin as we still count up failures.
  392. bad_cookie = False
  393. if trust is None:
  394. self._fail_pin_auth()
  395. bad_cookie = True
  396. # If we're trusted, we're authenticated.
  397. elif trust:
  398. auth = True
  399. # If we failed too many times, then we're locked out.
  400. elif self._failed_pin_auth > 10:
  401. exhausted = True
  402. # Otherwise go through pin based authentication
  403. else:
  404. entered_pin = request.args["pin"]
  405. if entered_pin.strip().replace("-", "") == pin.replace("-", ""):
  406. self._failed_pin_auth = 0
  407. auth = True
  408. else:
  409. self._fail_pin_auth()
  410. rv = Response(
  411. json.dumps({"auth": auth, "exhausted": exhausted}),
  412. mimetype="application/json",
  413. )
  414. if auth:
  415. rv.set_cookie(
  416. self.pin_cookie_name,
  417. f"{int(time.time())}|{hash_pin(pin)}",
  418. httponly=True,
  419. samesite="Strict",
  420. secure=request.is_secure,
  421. )
  422. elif bad_cookie:
  423. rv.delete_cookie(self.pin_cookie_name)
  424. return rv
  425. def log_pin_request(self, request: Request) -> Response:
  426. """Log the pin if needed."""
  427. if not self.check_host_trust(request.environ):
  428. return SecurityError() # type: ignore[return-value]
  429. if self.pin_logging and self.pin is not None:
  430. _log(
  431. "info", " * To enable the debugger you need to enter the security pin:"
  432. )
  433. _log("info", " * Debugger pin code: %s", self.pin)
  434. return Response("")
  435. def __call__(
  436. self, environ: WSGIEnvironment, start_response: StartResponse
  437. ) -> t.Iterable[bytes]:
  438. """Dispatch the requests."""
  439. # important: don't ever access a function here that reads the incoming
  440. # form data! Otherwise the application won't have access to that data
  441. # any more!
  442. request = Request(environ)
  443. response = self.debug_application
  444. if request.args.get("__debugger__") == "yes":
  445. cmd = request.args.get("cmd")
  446. arg = request.args.get("f")
  447. secret = request.args.get("s")
  448. frame = self.frames.get(request.args.get("frm", type=int)) # type: ignore
  449. if cmd == "resource" and arg:
  450. response = self.get_resource(request, arg) # type: ignore
  451. elif cmd == "pinauth" and secret == self.secret:
  452. response = self.pin_auth(request) # type: ignore
  453. elif cmd == "printpin" and secret == self.secret:
  454. response = self.log_pin_request(request) # type: ignore
  455. elif (
  456. self.evalex
  457. and cmd is not None
  458. and frame is not None
  459. and self.secret == secret
  460. and self.check_pin_trust(environ)
  461. ):
  462. response = self.execute_command(request, cmd, frame) # type: ignore
  463. elif (
  464. self.evalex
  465. and self.console_path is not None
  466. and request.path == self.console_path
  467. ):
  468. response = self.display_console(request) # type: ignore
  469. return response(environ, start_response)