__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.debug
  4. ~~~~~~~~~~~~~~
  5. WSGI application traceback debugger.
  6. :copyright: 2007 Pallets
  7. :license: BSD-3-Clause
  8. """
  9. import getpass
  10. import hashlib
  11. import json
  12. import mimetypes
  13. import os
  14. import pkgutil
  15. import re
  16. import sys
  17. import time
  18. import uuid
  19. from itertools import chain
  20. from os.path import basename
  21. from os.path import join
  22. from .._compat import text_type
  23. from .._internal import _log
  24. from ..http import parse_cookie
  25. from ..security import gen_salt
  26. from ..wrappers import BaseRequest as Request
  27. from ..wrappers import BaseResponse as Response
  28. from .console import Console
  29. from .tbtools import get_current_traceback
  30. from .tbtools import render_console_html
  31. # A week
  32. PIN_TIME = 60 * 60 * 24 * 7
  33. def hash_pin(pin):
  34. if isinstance(pin, text_type):
  35. pin = pin.encode("utf-8", "replace")
  36. return hashlib.md5(pin + b"shittysalt").hexdigest()[:12]
  37. _machine_id = None
  38. def get_machine_id():
  39. global _machine_id
  40. if _machine_id is not None:
  41. return _machine_id
  42. def _generate():
  43. linux = b""
  44. # machine-id is stable across boots, boot_id is not.
  45. for filename in "/etc/machine-id", "/proc/sys/kernel/random/boot_id":
  46. try:
  47. with open(filename, "rb") as f:
  48. value = f.readline().strip()
  49. except IOError:
  50. continue
  51. if value:
  52. linux += value
  53. break
  54. # Containers share the same machine id, add some cgroup
  55. # information. This is used outside containers too but should be
  56. # relatively stable across boots.
  57. try:
  58. with open("/proc/self/cgroup", "rb") as f:
  59. linux += f.readline().strip().rpartition(b"/")[2]
  60. except IOError:
  61. pass
  62. if linux:
  63. return linux
  64. # On OS X, use ioreg to get the computer's serial number.
  65. try:
  66. # subprocess may not be available, e.g. Google App Engine
  67. # https://github.com/pallets/werkzeug/issues/925
  68. from subprocess import Popen, PIPE
  69. dump = Popen(
  70. ["ioreg", "-c", "IOPlatformExpertDevice", "-d", "2"], stdout=PIPE
  71. ).communicate()[0]
  72. match = re.search(b'"serial-number" = <([^>]+)', dump)
  73. if match is not None:
  74. return match.group(1)
  75. except (OSError, ImportError):
  76. pass
  77. # On Windows, use winreg to get the machine guid.
  78. try:
  79. import winreg as wr
  80. except ImportError:
  81. try:
  82. import _winreg as wr
  83. except ImportError:
  84. wr = None
  85. if wr is not None:
  86. try:
  87. with wr.OpenKey(
  88. wr.HKEY_LOCAL_MACHINE,
  89. "SOFTWARE\\Microsoft\\Cryptography",
  90. 0,
  91. wr.KEY_READ | wr.KEY_WOW64_64KEY,
  92. ) as rk:
  93. guid, guid_type = wr.QueryValueEx(rk, "MachineGuid")
  94. if guid_type == wr.REG_SZ:
  95. return guid.encode("utf-8")
  96. return guid
  97. except WindowsError:
  98. pass
  99. _machine_id = _generate()
  100. return _machine_id
  101. class _ConsoleFrame(object):
  102. """Helper class so that we can reuse the frame console code for the
  103. standalone console.
  104. """
  105. def __init__(self, namespace):
  106. self.console = Console(namespace)
  107. self.id = 0
  108. def get_pin_and_cookie_name(app):
  109. """Given an application object this returns a semi-stable 9 digit pin
  110. code and a random key. The hope is that this is stable between
  111. restarts to not make debugging particularly frustrating. If the pin
  112. was forcefully disabled this returns `None`.
  113. Second item in the resulting tuple is the cookie name for remembering.
  114. """
  115. pin = os.environ.get("WERKZEUG_DEBUG_PIN")
  116. rv = None
  117. num = None
  118. # Pin was explicitly disabled
  119. if pin == "off":
  120. return None, None
  121. # Pin was provided explicitly
  122. if pin is not None and pin.replace("-", "").isdigit():
  123. # If there are separators in the pin, return it directly
  124. if "-" in pin:
  125. rv = pin
  126. else:
  127. num = pin
  128. modname = getattr(app, "__module__", app.__class__.__module__)
  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__", app.__class__.__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.md5()
  150. for bit in chain(probably_public_bits, private_bits):
  151. if not bit:
  152. continue
  153. if isinstance(bit, text_type):
  154. bit = bit.encode("utf-8")
  155. h.update(bit)
  156. h.update(b"cookiesalt")
  157. cookie_name = "__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 = ("%09d" % int(h.hexdigest(), 16))[: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(object):
  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 ths
  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. def __init__(
  200. self,
  201. app,
  202. evalex=False,
  203. request_key="werkzeug.request",
  204. console_path="/console",
  205. console_init_func=None,
  206. show_hidden_frames=False,
  207. pin_security=True,
  208. pin_logging=True,
  209. ):
  210. if not console_init_func:
  211. console_init_func = None
  212. self.app = app
  213. self.evalex = evalex
  214. self.frames = {}
  215. self.tracebacks = {}
  216. self.request_key = request_key
  217. self.console_path = console_path
  218. self.console_init_func = console_init_func
  219. self.show_hidden_frames = show_hidden_frames
  220. self.secret = gen_salt(20)
  221. self._failed_pin_auth = 0
  222. self.pin_logging = pin_logging
  223. if pin_security:
  224. # Print out the pin for the debugger on standard out.
  225. if os.environ.get("WERKZEUG_RUN_MAIN") == "true" and pin_logging:
  226. _log("warning", " * Debugger is active!")
  227. if self.pin is None:
  228. _log("warning", " * Debugger PIN disabled. DEBUGGER UNSECURED!")
  229. else:
  230. _log("info", " * Debugger PIN: %s" % self.pin)
  231. else:
  232. self.pin = None
  233. @property
  234. def pin(self):
  235. if not hasattr(self, "_pin"):
  236. self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app)
  237. return self._pin
  238. @pin.setter
  239. def pin(self, value):
  240. self._pin = value
  241. @property
  242. def pin_cookie_name(self):
  243. """The name of the pin cookie."""
  244. if not hasattr(self, "_pin_cookie"):
  245. self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app)
  246. return self._pin_cookie
  247. def debug_application(self, environ, start_response):
  248. """Run the application and conserve the traceback frames."""
  249. app_iter = None
  250. try:
  251. app_iter = self.app(environ, start_response)
  252. for item in app_iter:
  253. yield item
  254. if hasattr(app_iter, "close"):
  255. app_iter.close()
  256. except Exception:
  257. if hasattr(app_iter, "close"):
  258. app_iter.close()
  259. traceback = get_current_traceback(
  260. skip=1,
  261. show_hidden_frames=self.show_hidden_frames,
  262. ignore_system_exceptions=True,
  263. )
  264. for frame in traceback.frames:
  265. self.frames[frame.id] = frame
  266. self.tracebacks[traceback.id] = traceback
  267. try:
  268. start_response(
  269. "500 INTERNAL SERVER ERROR",
  270. [
  271. ("Content-Type", "text/html; charset=utf-8"),
  272. # Disable Chrome's XSS protection, the debug
  273. # output can cause false-positives.
  274. ("X-XSS-Protection", "0"),
  275. ],
  276. )
  277. except Exception:
  278. # if we end up here there has been output but an error
  279. # occurred. in that situation we can do nothing fancy any
  280. # more, better log something into the error log and fall
  281. # back gracefully.
  282. environ["wsgi.errors"].write(
  283. "Debugging middleware caught exception in streamed "
  284. "response at a point where response headers were already "
  285. "sent.\n"
  286. )
  287. else:
  288. is_trusted = bool(self.check_pin_trust(environ))
  289. yield traceback.render_full(
  290. evalex=self.evalex, evalex_trusted=is_trusted, secret=self.secret
  291. ).encode("utf-8", "replace")
  292. traceback.log(environ["wsgi.errors"])
  293. def execute_command(self, request, command, frame):
  294. """Execute a command in a console."""
  295. return Response(frame.console.eval(command), mimetype="text/html")
  296. def display_console(self, request):
  297. """Display a standalone shell."""
  298. if 0 not in self.frames:
  299. if self.console_init_func is None:
  300. ns = {}
  301. else:
  302. ns = dict(self.console_init_func())
  303. ns.setdefault("app", self.app)
  304. self.frames[0] = _ConsoleFrame(ns)
  305. is_trusted = bool(self.check_pin_trust(request.environ))
  306. return Response(
  307. render_console_html(secret=self.secret, evalex_trusted=is_trusted),
  308. mimetype="text/html",
  309. )
  310. def paste_traceback(self, request, traceback):
  311. """Paste the traceback and return a JSON response."""
  312. rv = traceback.paste()
  313. return Response(json.dumps(rv), mimetype="application/json")
  314. def get_resource(self, request, filename):
  315. """Return a static resource from the shared folder."""
  316. filename = join("shared", basename(filename))
  317. try:
  318. data = pkgutil.get_data(__package__, filename)
  319. except OSError:
  320. data = None
  321. if data is not None:
  322. mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
  323. return Response(data, mimetype=mimetype)
  324. return Response("Not Found", status=404)
  325. def check_pin_trust(self, environ):
  326. """Checks if the request passed the pin test. This returns `True` if the
  327. request is trusted on a pin/cookie basis and returns `False` if not.
  328. Additionally if the cookie's stored pin hash is wrong it will return
  329. `None` so that appropriate action can be taken.
  330. """
  331. if self.pin is None:
  332. return True
  333. val = parse_cookie(environ).get(self.pin_cookie_name)
  334. if not val or "|" not in val:
  335. return False
  336. ts, pin_hash = val.split("|", 1)
  337. if not ts.isdigit():
  338. return False
  339. if pin_hash != hash_pin(self.pin):
  340. return None
  341. return (time.time() - PIN_TIME) < int(ts)
  342. def _fail_pin_auth(self):
  343. time.sleep(5.0 if self._failed_pin_auth > 5 else 0.5)
  344. self._failed_pin_auth += 1
  345. def pin_auth(self, request):
  346. """Authenticates with the pin."""
  347. exhausted = False
  348. auth = False
  349. trust = self.check_pin_trust(request.environ)
  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.get("pin")
  368. if entered_pin.strip().replace("-", "") == self.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. "%s|%s" % (int(time.time()), hash_pin(self.pin)),
  381. httponly=True,
  382. )
  383. elif bad_cookie:
  384. rv.delete_cookie(self.pin_cookie_name)
  385. return rv
  386. def log_pin_request(self):
  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__(self, environ, start_response):
  395. """Dispatch the requests."""
  396. # important: don't ever access a function here that reads the incoming
  397. # form data! Otherwise the application won't have access to that data
  398. # any more!
  399. request = Request(environ)
  400. response = self.debug_application
  401. if request.args.get("__debugger__") == "yes":
  402. cmd = request.args.get("cmd")
  403. arg = request.args.get("f")
  404. secret = request.args.get("s")
  405. traceback = self.tracebacks.get(request.args.get("tb", type=int))
  406. frame = self.frames.get(request.args.get("frm", type=int))
  407. if cmd == "resource" and arg:
  408. response = self.get_resource(request, arg)
  409. elif cmd == "paste" and traceback is not None and secret == self.secret:
  410. response = self.paste_traceback(request, traceback)
  411. elif cmd == "pinauth" and secret == self.secret:
  412. response = self.pin_auth(request)
  413. elif cmd == "printpin" and secret == self.secret:
  414. response = self.log_pin_request()
  415. elif (
  416. self.evalex
  417. and cmd is not None
  418. and frame is not None
  419. and self.secret == secret
  420. and self.check_pin_trust(environ)
  421. ):
  422. response = self.execute_command(request, cmd, frame)
  423. elif (
  424. self.evalex
  425. and self.console_path is not None
  426. and request.path == self.console_path
  427. ):
  428. response = self.display_console(request)
  429. return response(environ, start_response)