__init__.py 17 KB

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