__init__.py 17 KB

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