middleware.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. #!/usr/bin/env python
  2. # Licensed to Cloudera, Inc. under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. Cloudera, Inc. licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. from __future__ import absolute_import
  18. from builtins import object
  19. import inspect
  20. import json
  21. import logging
  22. import mimetypes
  23. import os.path
  24. import re
  25. import socket
  26. import sys
  27. import tempfile
  28. import time
  29. import traceback
  30. import kerberos
  31. import django.db
  32. import django.views.static
  33. import django_prometheus
  34. from django.conf import settings
  35. from django.contrib import messages
  36. from django.contrib.auth import REDIRECT_FIELD_NAME, BACKEND_SESSION_KEY, authenticate, load_backend, login
  37. from django.contrib.auth.middleware import RemoteUserMiddleware
  38. from django.core import exceptions
  39. from django.http import HttpResponseNotAllowed, HttpResponseForbidden
  40. from django.urls import resolve
  41. from django.http import HttpResponseRedirect, HttpResponse
  42. from django.utils.deprecation import MiddlewareMixin
  43. from hadoop import cluster
  44. from dashboard.conf import IS_ENABLED as DASHBOARD_ENABLED
  45. from useradmin.models import User
  46. import desktop.views
  47. from desktop import appmanager, metrics
  48. from desktop.auth.backend import is_admin, find_or_create_user, ensure_has_a_group, rewrite_user
  49. from desktop.conf import AUTH, HTTP_ALLOWED_METHODS, ENABLE_PROMETHEUS, KNOX, DJANGO_DEBUG_MODE, AUDIT_EVENT_LOG_DIR, \
  50. SERVER_USER, REDIRECT_WHITELIST, SECURE_CONTENT_SECURITY_POLICY, has_connectors
  51. from desktop.context_processors import get_app_name
  52. from desktop.lib import apputil, i18n, fsmanager
  53. from desktop.lib.django_util import JsonResponse, render, render_json
  54. from desktop.lib.exceptions import StructuredException
  55. from desktop.lib.exceptions_renderable import PopupException
  56. from desktop.lib.view_util import is_ajax
  57. from desktop.log import get_audit_logger
  58. from desktop.log.access import access_log, log_page_hit, access_warn
  59. from libsaml.conf import CDP_LOGOUT_URL
  60. if sys.version_info[0] > 2:
  61. from django.utils.translation import gettext as _
  62. from django.utils.http import url_has_allowed_host_and_scheme
  63. from urllib.parse import quote
  64. else:
  65. from django.utils.translation import ugettext as _
  66. from django.utils.http import is_safe_url as url_has_allowed_host_and_scheme, urlquote as quote
  67. LOG = logging.getLogger(__name__)
  68. MIDDLEWARE_HEADER = "X-Hue-Middleware-Response"
  69. # Views inside Django that don't require login
  70. # (see LoginAndPermissionMiddleware)
  71. DJANGO_VIEW_AUTH_WHITELIST = [
  72. django.views.static.serve,
  73. desktop.views.is_alive,
  74. ]
  75. if ENABLE_PROMETHEUS.get():
  76. DJANGO_VIEW_AUTH_WHITELIST.append(django_prometheus.exports.ExportToDjangoView)
  77. class AjaxMiddleware(MiddlewareMixin):
  78. """
  79. Middleware that augments request to set request.ajax
  80. for either is_ajax() (looks at HTTP headers) or ?format=json
  81. GET parameters.
  82. """
  83. def process_request(self, request):
  84. request.ajax = is_ajax(request) or request.GET.get("format", "") == "json"
  85. return None
  86. class ExceptionMiddleware(MiddlewareMixin):
  87. """
  88. If exceptions know how to render themselves, use that.
  89. """
  90. def process_exception(self, request, exception):
  91. tb = traceback.format_exc()
  92. logging.info("Processing exception: %s: %s" % (
  93. i18n.smart_unicode(exception), i18n.smart_unicode(tb))
  94. )
  95. if isinstance(exception, PopupException):
  96. return exception.response(request)
  97. if isinstance(exception, StructuredException):
  98. if request.ajax:
  99. response = render_json(exception.response_data)
  100. response[MIDDLEWARE_HEADER] = 'EXCEPTION'
  101. response.status_code = getattr(exception, 'error_code', 500)
  102. return response
  103. else:
  104. response = render("error.mako", request, {
  105. 'error': exception.response_data.get("message"),
  106. 'is_embeddable': request.GET.get('is_embeddable', False),
  107. })
  108. response.status_code = getattr(exception, 'error_code', 500)
  109. return response
  110. return None
  111. class ClusterMiddleware(MiddlewareMixin):
  112. """
  113. Manages setting request.fs and request.jt
  114. """
  115. def process_view(self, request, view_func, view_args, view_kwargs):
  116. """
  117. Sets request.fs and request.jt on every request to point to the configured filesystem.
  118. """
  119. request.fs_ref = request.GET.get('fs', view_kwargs.get('fs', 'default'))
  120. if "fs" in view_kwargs:
  121. del view_kwargs["fs"]
  122. request.fs = None
  123. if request.user.is_authenticated:
  124. request.fs = fsmanager.get_filesystem(request.fs_ref)
  125. if request.fs is not None:
  126. request.fs.setuser(request.user.username)
  127. else:
  128. LOG.warning("request.fs user was not set")
  129. else:
  130. LOG.warning("request.fs was not set for anonymous user")
  131. # Deprecated
  132. request.jt = None
  133. class NotificationMiddleware(MiddlewareMixin):
  134. """
  135. Manages setting request.info and request.error
  136. """
  137. def process_view(self, request, view_func, view_args, view_kwargs):
  138. def message(title, detail=None):
  139. if detail is None:
  140. detail = ''
  141. else:
  142. detail = '<br/>%s' % detail
  143. return '%s %s' % (title, detail)
  144. def info(title, detail=None):
  145. messages.info(request, message(title, detail))
  146. def error(title, detail=None):
  147. messages.error(request, message(title, detail))
  148. def warn(title, detail=None):
  149. messages.warning(request, message(title, detail))
  150. request.info = info
  151. request.error = error
  152. request.warn = warn
  153. class AppSpecificMiddleware(object):
  154. @classmethod
  155. def augment_request_with_app(cls, request, view_func):
  156. """Inject the app name into the request for use in later-stage middleware"""
  157. if not hasattr(request, "_desktop_app"):
  158. module = inspect.getmodule(view_func)
  159. request._desktop_app = apputil.get_app_for_module(module)
  160. if not request._desktop_app and not module.__name__.startswith('django.'):
  161. logging.debug("no app for view func: %s in %s" % (view_func, module))
  162. def __init__(self):
  163. self.middlewares_by_app = {}
  164. for app in appmanager.DESKTOP_APPS:
  165. self.middlewares_by_app[app.name] = self._load_app_middleware(app)
  166. def _get_middlewares(self, app, type):
  167. return self.middlewares_by_app.get(app, {}).get(type, [])
  168. def process_view(self, request, view_func, view_args, view_kwargs):
  169. self.augment_request_with_app(request, view_func)
  170. if not request._desktop_app:
  171. return None
  172. # Run the middlewares
  173. ret = None
  174. for middleware in self._get_middlewares(request._desktop_app, 'view'):
  175. ret = middleware(request, view_func, view_args, view_kwargs)
  176. if ret: return ret # Short circuit
  177. return ret
  178. def process_response(self, request, response):
  179. # We have the app that we stuffed in there
  180. if not hasattr(request, '_desktop_app'):
  181. logging.debug("No desktop_app known for request.")
  182. return response
  183. for middleware in reversed(self._get_middlewares(request._desktop_app, 'response')):
  184. response = middleware(request, response)
  185. return response
  186. def process_exception(self, request, exception):
  187. # We have the app that we stuffed in there
  188. if not hasattr(request, '_desktop_app'):
  189. logging.debug("No desktop_app known for exception.")
  190. return None
  191. # Run the middlewares
  192. ret = None
  193. for middleware in self._get_middlewares(request._desktop_app, 'exception'):
  194. ret = middleware(request, exception)
  195. if ret: return ret # short circuit
  196. return ret
  197. def _load_app_middleware(cls, app):
  198. app_settings = app.settings
  199. if not app_settings:
  200. return
  201. mw_classes = app_settings.__dict__.get('MIDDLEWARE_CLASSES', [])
  202. result = {'view': [], 'response': [], 'exception': []}
  203. for middleware_path in mw_classes:
  204. # This code brutally lifted from django.core.handlers
  205. try:
  206. dot = middleware_path.rindex('.')
  207. except ValueError:
  208. raise exceptions.ImproperlyConfigured(_('%(module)s isn\'t a middleware module.') % {'module': middleware_path})
  209. mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
  210. try:
  211. mod = __import__(mw_module, {}, {}, [''])
  212. except ImportError as e:
  213. raise exceptions.ImproperlyConfigured(
  214. _('Error importing middleware %(module)s: "%(error)s".') % {'module': mw_module, 'error': e}
  215. )
  216. try:
  217. mw_class = getattr(mod, mw_classname)
  218. except AttributeError:
  219. raise exceptions.ImproperlyConfigured(
  220. _('Middleware module "%(module)s" does not define a "%(class)s" class.') % {'module': mw_module, 'class': mw_classname}
  221. )
  222. try:
  223. mw_instance = mw_class()
  224. except exceptions.MiddlewareNotUsed:
  225. continue
  226. # End brutal code lift
  227. # We need to make sure we don't have a process_request function because we don't know what
  228. # application will handle the request at the point process_request is called
  229. if hasattr(mw_instance, 'process_request'):
  230. raise exceptions.ImproperlyConfigured(_('AppSpecificMiddleware module "%(module)s" has a process_request function' + \
  231. ' which is impossible.') % {'module': middleware_path})
  232. if hasattr(mw_instance, 'process_view'):
  233. result['view'].append(mw_instance.process_view)
  234. if hasattr(mw_instance, 'process_response'):
  235. result['response'].insert(0, mw_instance.process_response)
  236. if hasattr(mw_instance, 'process_exception'):
  237. result['exception'].insert(0, mw_instance.process_exception)
  238. return result
  239. class LoginAndPermissionMiddleware(MiddlewareMixin):
  240. """
  241. Middleware that forces all views (except those that opt out) through authentication.
  242. """
  243. def process_request(self, request):
  244. # When local user login, oidc middleware refresh token if oidc_id_token_expiration doesn't exists!
  245. if request.session.get('_auth_user_backend', '') == 'desktop.auth.backend.AllowFirstUserDjangoBackend' \
  246. and 'desktop.auth.backend.OIDCBackend' in AUTH.BACKEND.get():
  247. request.session['oidc_id_token_expiration'] = time.time() + 300
  248. def process_view(self, request, view_func, view_args, view_kwargs):
  249. """
  250. We also perform access logging in ``process_view()`` since we have the view function,
  251. which tells us the log level. The downside is that we don't have the status code,
  252. which isn't useful for status logging anyways.
  253. """
  254. request.ts = time.time()
  255. request.view_func = view_func
  256. access_log_level = getattr(view_func, 'access_log_level', None)
  257. # Skip loop for oidc
  258. if request.path in ['/oidc/authenticate/', '/oidc/callback/', '/oidc/logout/', '/hue/oidc_failed/']:
  259. return None
  260. if AUTH.AUTO_LOGIN_ENABLED.get() and request.path.startswith('/api/token/auth'):
  261. pass # allow /api/token/auth can create user or make it active
  262. elif request.path.startswith('/api/'):
  263. return None
  264. # Skip views not requiring login
  265. # If the view has "opted out" of login required, skip
  266. if hasattr(view_func, "login_notrequired"):
  267. log_page_hit(request, view_func, level=access_log_level or logging.DEBUG)
  268. return None
  269. # There are certain django views which are also opt-out, but
  270. # it would be evil to go add attributes to them
  271. if view_func in DJANGO_VIEW_AUTH_WHITELIST:
  272. log_page_hit(request, view_func, level=access_log_level or logging.DEBUG)
  273. return None
  274. # If user is logged in, check that he has permissions to access the app
  275. if request.user.is_active and request.user.is_authenticated:
  276. AppSpecificMiddleware.augment_request_with_app(request, view_func)
  277. # Until Django 1.3 which resolves returning the URL name, just do a match of the name of the view
  278. try:
  279. access_view = 'access_view:%s:%s' % (request._desktop_app, resolve(request.path)[0].__name__)
  280. except Exception as e:
  281. access_log(request, 'error checking view perm: %s' % e, level=access_log_level)
  282. access_view = ''
  283. app_accessed = request._desktop_app
  284. app_libs_whitelist = ["desktop", "home", "home2", "about", "hue", "editor", "notebook", "indexer", "404", "500", "403"]
  285. if has_connectors():
  286. app_libs_whitelist.append('metadata')
  287. if DASHBOARD_ENABLED.get():
  288. app_libs_whitelist.append('dashboard')
  289. # Accessing an app can access an underlying other app.
  290. # e.g. impala or spark uses code from beeswax and so accessing impala shows up as beeswax here.
  291. # Here we trust the URL to be the real app we need to check the perms.
  292. ui_app_accessed = get_app_name(request)
  293. if app_accessed != ui_app_accessed and ui_app_accessed not in ('logs', 'accounts', 'login'):
  294. app_accessed = ui_app_accessed
  295. if app_accessed and \
  296. app_accessed not in app_libs_whitelist and \
  297. not (
  298. is_admin(request.user) or
  299. request.user.has_hue_permission(action="access", app=app_accessed) or
  300. request.user.has_hue_permission(action=access_view, app=app_accessed)
  301. ) and \
  302. not (app_accessed == '__debug__' and DJANGO_DEBUG_MODE.get()):
  303. access_log(request, 'permission denied', level=access_log_level)
  304. return PopupException(
  305. _("You do not have permission to access the %(app_name)s application.") % {'app_name': app_accessed.capitalize()},
  306. error_code=401
  307. ).response(request)
  308. else:
  309. if not hasattr(request, 'view_func'):
  310. log_page_hit(request, view_func, level=access_log_level)
  311. return None
  312. if AUTH.AUTO_LOGIN_ENABLED.get():
  313. # Auto-create the hue/hue user if not already present
  314. user = find_or_create_user(username='hue', password='hue')
  315. ensure_has_a_group(user)
  316. user = rewrite_user(user)
  317. user.is_active = True
  318. user.save()
  319. user = authenticate(request, username='hue', password='hue')
  320. if user is not None:
  321. login(request, user)
  322. return None
  323. logging.info("Redirecting to login page: %s", request.get_full_path())
  324. access_log(request, 'login redirection', level=access_log_level)
  325. no_idle_backends = [
  326. "desktop.auth.backend.SpnegoDjangoBackend",
  327. "desktop.auth.backend.KnoxSpnegoDjangoBackend"
  328. ]
  329. if CDP_LOGOUT_URL.get() == "":
  330. no_idle_backends.append("libsaml.backend.SAML2Backend")
  331. if request.ajax and all(no_idle_backend not in AUTH.BACKEND.get() for no_idle_backend in no_idle_backends):
  332. # Send back a magic header which causes Hue.Request to interpose itself
  333. # in the ajax request and make the user login before resubmitting the
  334. # request.
  335. response = HttpResponse("/* login required */", content_type="text/javascript")
  336. response[MIDDLEWARE_HEADER] = 'LOGIN_REQUIRED'
  337. return response
  338. else:
  339. if request.GET.get('is_embeddable'):
  340. return JsonResponse({
  341. 'url': "%s?%s=%s" % (
  342. settings.LOGIN_URL,
  343. REDIRECT_FIELD_NAME,
  344. quote('/hue' + request.get_full_path().replace('is_embeddable=true', '').replace('&&', '&'))
  345. )
  346. }) # Remove embeddable so redirect from & to login works. Login page is not embeddable
  347. else:
  348. return HttpResponseRedirect("%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME, quote(request.get_full_path())))
  349. def process_response(self, request, response):
  350. if hasattr(request, 'ts') and hasattr(request, 'view_func'):
  351. log_page_hit(request, request.view_func, level=logging.INFO, start_time=request.ts, response=response)
  352. return response
  353. class JsonMessage(object):
  354. def __init__(self, **kwargs):
  355. self.kwargs = kwargs
  356. def __str__(self):
  357. return json.dumps(self.kwargs)
  358. class AuditLoggingMiddleware(MiddlewareMixin):
  359. def __init__(self, get_response):
  360. self.get_response = get_response
  361. self.impersonator = SERVER_USER.get()
  362. if not AUDIT_EVENT_LOG_DIR.get():
  363. LOG.info('Unloading AuditLoggingMiddleware')
  364. raise exceptions.MiddlewareNotUsed
  365. def process_response(self, request, response):
  366. response['audited'] = False
  367. try:
  368. if hasattr(request, 'audit') and request.audit is not None:
  369. self._log_message(request, response)
  370. response['audited'] = True
  371. except Exception as e:
  372. LOG.error('Could not audit the request: %s' % e)
  373. return response
  374. def _log_message(self, request, response=None):
  375. audit_logger = get_audit_logger()
  376. audit_logger.debug(JsonMessage(**{
  377. 'username': self._get_username(request),
  378. 'impersonator': self.impersonator,
  379. 'ipAddress': self._get_client_ip(request),
  380. 'operation': request.audit['operation'],
  381. 'operationText': request.audit.get('operationText', ''),
  382. 'eventTime': self._milliseconds_since_epoch(),
  383. 'allowed': self._get_allowed(request, response),
  384. 'service': get_app_name(request),
  385. 'url': request.path
  386. }))
  387. def _get_client_ip(self, request):
  388. x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
  389. if x_forwarded_for:
  390. x_forwarded_for = x_forwarded_for.split(',')[0]
  391. return request.META.get('HTTP_CLIENT_IP') or x_forwarded_for or request.META.get('REMOTE_ADDR')
  392. def _get_username(self, request):
  393. username = 'anonymous'
  394. if request.audit.get('username', None):
  395. username = request.audit.get('username')
  396. elif hasattr(request, 'user') and not request.user.is_anonymous:
  397. username = request.user.get_username()
  398. return username
  399. def _milliseconds_since_epoch(self):
  400. return int(time.time() * 1000)
  401. def _get_allowed(self, request, response=None):
  402. allowed = response.status_code != 401
  403. if 'allowed' in request.audit:
  404. return request.audit['allowed']
  405. return allowed
  406. try:
  407. import tidylib
  408. _has_tidylib = True
  409. except Exception as ex:
  410. # The exception type is not ImportError. It's actually an OSError.
  411. logging.warn("Failed to import tidylib (for debugging). Is libtidy installed?")
  412. _has_tidylib = False
  413. class HtmlValidationMiddleware(MiddlewareMixin):
  414. """
  415. If configured, validate output html for every response.
  416. """
  417. def __init__(self, get_response):
  418. self.get_response = get_response
  419. self._logger = logging.getLogger('HtmlValidationMiddleware')
  420. if not _has_tidylib:
  421. logging.error("HtmlValidationMiddleware not activatived: Failed to import tidylib.")
  422. return
  423. # Things that we don't care about
  424. self._to_ignore = (
  425. re.compile('- Warning: <.*> proprietary attribute "data-'),
  426. re.compile('- Warning: trimming empty'),
  427. re.compile('- Info:'),
  428. )
  429. # Find the directory to write tidy html output
  430. try:
  431. self._outdir = os.path.join(tempfile.gettempdir(), 'hue_html_validation')
  432. if not os.path.isdir(self._outdir):
  433. os.mkdir(self._outdir, 0o755)
  434. except Exception as ex:
  435. self._logger.exception('Failed to get temp directory: %s', (ex,))
  436. self._outdir = tempfile.mkdtemp(prefix='hue_html_validation-')
  437. # Options to pass to libtidy. See
  438. # http://tidy.sourceforge.net/docs/quickref.html
  439. self._options = {
  440. 'show-warnings': 1,
  441. 'output-html': 0,
  442. 'output-xhtml': 1,
  443. 'char-encoding': 'utf8',
  444. 'output-encoding': 'utf8',
  445. 'indent': 1,
  446. 'wrap': 0,
  447. }
  448. def process_response(self, request, response):
  449. if not _has_tidylib or not self._is_html(request, response):
  450. return response
  451. html, errors = tidylib.tidy_document(response.content,
  452. self._options,
  453. keep_doc=True)
  454. if not errors:
  455. return response
  456. # Filter out what we care about
  457. err_list = errors.rstrip().split('\n')
  458. err_list = self._filter_warnings(err_list)
  459. if not err_list:
  460. return response
  461. try:
  462. fn = resolve(request.path)[0]
  463. fn_name = '%s.%s' % (fn.__module__, fn.__name__)
  464. except:
  465. LOG.exception('failed to resolve url')
  466. fn_name = '<unresolved_url>'
  467. # Write the two versions of html out for offline debugging
  468. filename = os.path.join(self._outdir, fn_name)
  469. result = "HTML tidy result: %s [%s]:" \
  470. "\n\t%s" \
  471. "\nPlease see %s.orig %s.tidy\n-------" % \
  472. (request.path, fn_name, '\n\t'.join(err_list), filename, filename)
  473. file(filename + '.orig', 'w').write(i18n.smart_str(response.content))
  474. file(filename + '.tidy', 'w').write(i18n.smart_str(html))
  475. file(filename + '.info', 'w').write(i18n.smart_str(result))
  476. self._logger.error(result)
  477. return response
  478. def _filter_warnings(self, err_list):
  479. """A hacky way to filter out things that we don't care about."""
  480. res = []
  481. for err in err_list:
  482. for ignore in self._to_ignore:
  483. if ignore.search(err):
  484. break
  485. else:
  486. res.append(err)
  487. return res
  488. def _is_html(self, request, response):
  489. return not is_ajax(request) and \
  490. 'html' in response['Content-Type'] and \
  491. 200 <= response.status_code < 300
  492. class ProxyMiddleware(MiddlewareMixin):
  493. def __init__(self, get_response):
  494. self.get_response = get_response
  495. if not 'desktop.auth.backend.AllowAllBackend' in AUTH.BACKEND.get():
  496. LOG.info('Unloading ProxyMiddleware')
  497. raise exceptions.MiddlewareNotUsed
  498. def process_response(self, request, response):
  499. return response
  500. def process_request(self, request):
  501. view_func = resolve(request.path)[0]
  502. if view_func in DJANGO_VIEW_AUTH_WHITELIST:
  503. return
  504. # AuthenticationMiddleware is required so that request.user exists.
  505. if not hasattr(request, 'user'):
  506. raise exceptions.ImproperlyConfigured(
  507. "The Django remote user auth middleware requires the"
  508. " authentication middleware to be installed. Edit your"
  509. " MIDDLEWARE_CLASSES setting to insert"
  510. " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
  511. " before the SpnegoUserMiddleware class.")
  512. if request.GET.get('user.name'):
  513. try:
  514. username = request.GET.get('user.name')
  515. user = authenticate(username=username, password='')
  516. if user:
  517. request.user = user
  518. login(request, user)
  519. msg = 'Successful login for user: %s' % request.user.username
  520. else:
  521. msg = 'Failed login for user: %s' % request.user.username
  522. request.audit = {
  523. 'operation': 'USER_LOGIN',
  524. 'username': request.user.username,
  525. 'operationText': msg
  526. }
  527. return
  528. except:
  529. LOG.exception('Unexpected error when authenticating')
  530. return
  531. def clean_username(self, username, request):
  532. """
  533. Allows the backend to clean the username, if the backend defines a
  534. clean_username method.
  535. """
  536. backend_str = request.session[BACKEND_SESSION_KEY]
  537. backend = load_backend(backend_str)
  538. try:
  539. username = backend.clean_username(username)
  540. except AttributeError:
  541. pass
  542. return username
  543. class SpnegoMiddleware(MiddlewareMixin):
  544. """
  545. Based on the WSGI SPNEGO middlware class posted here:
  546. http://code.activestate.com/recipes/576992/
  547. """
  548. def __init__(self, get_response):
  549. self.get_response = get_response
  550. if not set(AUTH.BACKEND.get()).intersection(
  551. set(['desktop.auth.backend.SpnegoDjangoBackend', 'desktop.auth.backend.KnoxSpnegoDjangoBackend'])
  552. ):
  553. LOG.info('Unloading SpnegoMiddleware')
  554. raise exceptions.MiddlewareNotUsed
  555. def process_request(self, request):
  556. """
  557. The process_request() method needs to communicate some state to the
  558. process_response() method. The two options for this are to return an
  559. HttpResponse object or to modify the META headers in the request object. In
  560. order to ensure that all of the middleware is properly invoked, this code
  561. currently uses the later approach. The following headers are currently used:
  562. GSS-String:
  563. This means that GSS authentication was successful and that we need to pass
  564. this value for the WWW-Authenticate header in the response.
  565. Return-401:
  566. This means that the SPNEGO backend is in use, but we didn't get an
  567. AUTHORIZATION header from the client. The way that the protocol works
  568. (http://tools.ietf.org/html/rfc4559) is by having the first response to an
  569. un-authenticated request be a 401 with the WWW-Authenticate header set to
  570. Negotiate. This will cause the browser to re-try the request with the
  571. AUTHORIZATION header set.
  572. """
  573. view_func = resolve(request.path)[0]
  574. if view_func in DJANGO_VIEW_AUTH_WHITELIST:
  575. return
  576. # AuthenticationMiddleware is required so that request.user exists.
  577. if not hasattr(request, 'user'):
  578. raise exceptions.ImproperlyConfigured(
  579. "The Django remote user auth middleware requires the"
  580. " authentication middleware to be installed. Edit your"
  581. " MIDDLEWARE_CLASSES setting to insert"
  582. " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
  583. " before the SpnegoUserMiddleware class.")
  584. if 'HTTP_AUTHORIZATION' in request.META:
  585. type, authstr = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
  586. if type == 'Negotiate':
  587. try:
  588. result, context = kerberos.authGSSServerInit('HTTP')
  589. if result != 1:
  590. return
  591. gssstring = ''
  592. r = kerberos.authGSSServerStep(context, authstr)
  593. if r == 1:
  594. gssstring = kerberos.authGSSServerResponse(context)
  595. request.META['GSS-String'] = 'Negotiate %s' % gssstring
  596. else:
  597. kerberos.authGSSServerClean(context)
  598. return
  599. username = kerberos.authGSSServerUserName(context)
  600. kerberos.authGSSServerClean(context)
  601. # In Trusted knox proxy, Hue must expect following:
  602. # Trusted knox user: KNOX_PRINCIPAL
  603. # Trusted knox proxy host: KNOX_PROXYHOSTS
  604. if 'desktop.auth.backend.KnoxSpnegoDjangoBackend' in AUTH.BACKEND.get():
  605. knox_verification = False
  606. principals = self.clean_principal(KNOX.KNOX_PRINCIPAL.get())
  607. principal = self.clean_principal(username)
  608. if principal.intersection(principals):
  609. # This may contain chain of reverse proxies, e.g. knox proxy, hue load balancer
  610. # Compare hostname on both HTTP_X_FORWARDED_HOST & KNOX_PROXYHOSTS.
  611. # Both of these can be configured to use either hostname or IPs and we have to normalize to one or the other
  612. req_hosts = self.clean_host(request.META['HTTP_X_FORWARDED_HOST'])
  613. knox_proxy = self.clean_host(KNOX.KNOX_PROXYHOSTS.get())
  614. if req_hosts.intersection(knox_proxy):
  615. knox_verification = True
  616. else:
  617. access_warn(request, 'Failed to verify provided host %s with %s ' % (req_hosts, knox_proxy))
  618. else:
  619. access_warn(request, 'Failed to verify provided username %s with %s ' % (principal, principals))
  620. # If knox authentication failed then generate 401 (Unauthorized error)
  621. if not knox_verification:
  622. request.META['Return-401'] = ''
  623. return
  624. if request.user.is_authenticated:
  625. if request.user.username == self.clean_username(username, request):
  626. return
  627. user = authenticate(username=username, request=request)
  628. if user:
  629. request.user = user
  630. login(request, user)
  631. msg = 'Successful login for user: %s' % request.user.username
  632. else:
  633. msg = 'Failed login for user: %s' % request.user.username
  634. request.audit = {
  635. 'operation': 'USER_LOGIN',
  636. 'username': request.user.username,
  637. 'operationText': msg
  638. }
  639. access_warn(request, msg)
  640. return
  641. except:
  642. LOG.exception('Unexpected error when authenticating against KDC')
  643. return
  644. else:
  645. request.META['Return-401'] = ''
  646. return
  647. else:
  648. if not request.user.is_authenticated:
  649. request.META['Return-401'] = ''
  650. return
  651. def process_response(self, request, response):
  652. if 'GSS-String' in request.META:
  653. response['WWW-Authenticate'] = request.META['GSS-String']
  654. elif 'Return-401' in request.META:
  655. response = HttpResponse("401 Unauthorized", content_type="text/plain",
  656. status=401)
  657. response['WWW-Authenticate'] = 'Negotiate'
  658. response.status = 401
  659. return response
  660. def clean_host(self, pattern):
  661. hosts = []
  662. if pattern:
  663. pattern_list = pattern if isinstance(pattern, list) else pattern.split(',')
  664. for hostport in pattern_list:
  665. host = hostport.split(':')[0].strip()
  666. try:
  667. hosts.append(socket.gethostbyaddr(host)[0])
  668. except Exception:
  669. LOG.exception('Could not resolve host addr %s' % host)
  670. hosts.append(host)
  671. return set(hosts)
  672. def clean_principal(self, pattern):
  673. principals = []
  674. if pattern:
  675. pattern_list = pattern if isinstance(pattern, list) else pattern.split(',')
  676. for principal_host in pattern_list:
  677. principal = principal_host.split('/')[0].strip()
  678. principals.append(principal)
  679. return set(principals)
  680. def clean_username(self, username, request):
  681. """
  682. Allows the backend to clean the username, if the backend defines a
  683. clean_username method.
  684. """
  685. backend_str = request.session[BACKEND_SESSION_KEY]
  686. backend = load_backend(backend_str)
  687. try:
  688. username = backend.clean_username(username, request)
  689. except AttributeError:
  690. pass
  691. return username
  692. class HueRemoteUserMiddleware(RemoteUserMiddleware):
  693. """
  694. Middleware to delegate authentication to a proxy server. The proxy server
  695. will set an HTTP header (defaults to Remote-User) with the name of the
  696. authenticated user. This class extends the RemoteUserMiddleware class
  697. built into Django with the ability to configure the HTTP header and to
  698. unload the middleware if the RemoteUserDjangoBackend is not currently
  699. in use.
  700. """
  701. def __init__(self, get_response):
  702. if not 'desktop.auth.backend.RemoteUserDjangoBackend' in AUTH.BACKEND.get():
  703. LOG.info('Unloading HueRemoteUserMiddleware')
  704. raise exceptions.MiddlewareNotUsed
  705. super().__init__(get_response)
  706. self.header = AUTH.REMOTE_USER_HEADER.get()
  707. class EnsureSafeMethodMiddleware(MiddlewareMixin):
  708. """
  709. Middleware to white list configured HTTP request methods.
  710. """
  711. def process_request(self, request):
  712. if request.method not in HTTP_ALLOWED_METHODS.get():
  713. return HttpResponseNotAllowed(HTTP_ALLOWED_METHODS.get())
  714. class EnsureSafeRedirectURLMiddleware(MiddlewareMixin):
  715. """
  716. Middleware to white list configured redirect URLs.
  717. """
  718. def process_response(self, request, response):
  719. if response.status_code in (301, 302, 303, 305, 307, 308) and response.get('Location') and not hasattr(response, 'redirect_override'):
  720. redirection_patterns = REDIRECT_WHITELIST.get()
  721. location = response['Location']
  722. if any(regexp.match(location) for regexp in redirection_patterns):
  723. return response
  724. if url_has_allowed_host_and_scheme(location, allowed_hosts={request.get_host()}):
  725. return response
  726. if request.path in ['/oidc/authenticate/', '/oidc/callback/', '/oidc/logout/', '/hue/oidc_failed/']:
  727. return response
  728. response = render("error.mako", request, {
  729. 'error': _('Redirect to %s is not allowed.') % response['Location'],
  730. 'is_embeddable': request.GET.get('is_embeddable', False),
  731. })
  732. response.status_code = 403
  733. return response
  734. else:
  735. return response
  736. class MetricsMiddleware(MiddlewareMixin):
  737. """
  738. Middleware to track the number of active requests.
  739. """
  740. def process_request(self, request):
  741. self._response_timer = metrics.response_time.time()
  742. metrics.active_requests.inc()
  743. def process_exception(self, request, exception):
  744. self._response_timer.stop()
  745. metrics.request_exceptions.inc()
  746. def process_response(self, request, response):
  747. self._response_timer.stop()
  748. metrics.active_requests.dec()
  749. return response
  750. class ContentSecurityPolicyMiddleware(MiddlewareMixin):
  751. def __init__(self, get_response):
  752. self.get_response = get_response
  753. self.secure_content_security_policy = SECURE_CONTENT_SECURITY_POLICY.get()
  754. if not self.secure_content_security_policy:
  755. LOG.info('Unloading ContentSecurityPolicyMiddleware')
  756. raise exceptions.MiddlewareNotUsed
  757. def process_response(self, request, response):
  758. if self.secure_content_security_policy and not 'Content-Security-Policy' in response:
  759. response["Content-Security-Policy"] = self.secure_content_security_policy
  760. return response
  761. class MimeTypeJSFileFixStreamingMiddleware(MiddlewareMixin):
  762. """
  763. Middleware to detect and fix ".js" mimetype. SLES 11SP4 as example OS which detect js file
  764. as "text/x-js" and if strict X-Content-Type-Options=nosniff is set then browser fails to
  765. execute javascript file.
  766. """
  767. def __init__(self, get_response):
  768. self.get_response = get_response
  769. jsmimetypes = ['application/javascript', 'application/ecmascript']
  770. if mimetypes.guess_type("dummy.js")[0] in jsmimetypes:
  771. LOG.info('Unloading MimeTypeJSFileFixStreamingMiddleware')
  772. raise exceptions.MiddlewareNotUsed
  773. def process_response(self, request, response):
  774. if request.path_info.endswith('.js'):
  775. response['Content-Type'] = "application/javascript"
  776. return response