Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_all_defaults(self):
context = krbContext(using_keytab=True,
principal='HTTP/hostname@EXAMPLE.COM')
self.assertTrue(context._cleaned_options['using_keytab'])
expected_princ = gssapi.names.Name(
'HTTP/hostname@EXAMPLE.COM',
gssapi.names.NameType.kerberos_principal)
self.assertEqual(expected_princ, context._cleaned_options['principal'])
self.assertEqual(kctx.DEFAULT_CCACHE,
context._cleaned_options['ccache'])
self.assertEqual(kctx.DEFAULT_KEYTAB,
context._cleaned_options['keytab'])
def setUp(self):
self.principal = 'cqi'
self.princ_name = gssapi.names.Name(self.principal,
gssapi.names.NameType.user)
def test_specify_principal(self):
context = krbContext(principal='cqi')
expected_princ = gssapi.names.Name('cqi', gssapi.names.NameType.user)
self.assertEqual(expected_princ,
context._cleaned_options['principal'])
if not req.auth:
if optional:
req.context["user"] = None
return func(resource, req, resp, *args, **kwargs)
logger.debug("No Kerberos ticket offered while attempting to access %s from %s",
req.env["PATH_INFO"], req.context.get("remote_addr"))
raise falcon.HTTPUnauthorized("Unauthorized",
"No Kerberos ticket offered, are you sure you've logged in with domain user account?",
["Negotiate"])
os.environ["KRB5_KTNAME"] = config.KERBEROS_KEYTAB
server_creds = gssapi.creds.Credentials(
usage='accept',
name=gssapi.names.Name('HTTP/%s'% const.FQDN))
context = gssapi.sec_contexts.SecurityContext(creds=server_creds)
if not req.auth.startswith("Negotiate "):
raise falcon.HTTPBadRequest("Bad request", "Bad header: %s" % req.auth)
token = ''.join(req.auth.split()[1:])
try:
context.step(b64decode(token))
except binascii.Error: # base64 errors
raise falcon.HTTPBadRequest("Bad request", "Malformed token")
except gssapi.raw.exceptions.BadMechanismError:
raise falcon.HTTPBadRequest("Bad request", "Unsupported authentication mechanism (NTLM?) was offered. Please make sure you've logged into the computer with domain user account. The web interface should not prompt for username or password.")
try:
logger.debug("No credentials offered while attempting to access %s from %s",
req.env["PATH_INFO"], req.context.get("remote_addr"))
raise falcon.HTTPUnauthorized("Unauthorized", "Please authenticate", ("Basic",))
if kerberized:
if not req.auth.startswith("Negotiate "):
raise falcon.HTTPUnauthorized("Unauthorized",
"Bad header, expected Negotiate",
["Negotiate"])
os.environ["KRB5_KTNAME"] = config.KERBEROS_KEYTAB
try:
server_creds = gssapi.creds.Credentials(
usage='accept',
name=gssapi.names.Name('HTTP/%s'% const.FQDN))
except gssapi.raw.exceptions.BadNameError:
logger.error("Failed initialize HTTP service principal, possibly bad permissions for %s or /etc/krb5.conf" %
config.KERBEROS_KEYTAB)
raise
context = gssapi.sec_contexts.SecurityContext(creds=server_creds)
token = ''.join(req.auth.split()[1:])
try:
context.step(b64decode(token))
except binascii.Error: # base64 errors
raise falcon.HTTPBadRequest("Bad request", "Malformed token")
except gssapi.raw.exceptions.BadMechanismError:
raise falcon.HTTPBadRequest("Bad request", "Unsupported authentication mechanism (NTLM?) was offered. Please make sure you've logged into the computer with domain user account. The web interface should not prompt for username or password.")
import json
import logging
import os
import re
import socket
import unicodedata
from identidude import config
from datetime import datetime, date
logger = logging.getLogger(__name__)
# http://firstyear.id.au/blog/html/2015/11/26/python_gssapi_with_flask_and_s4u2proxy.html
os.environ["KRB5_KTNAME"] = "FILE:/etc/identidude/server.keytab"
server_creds = gssapi.creds.Credentials(
usage='accept',
name=gssapi.names.Name('HTTP/%s'% (socket.gethostname())))
def apidoc(cls):
"""
Automagically document resource classes based on validate(), required(), etc decorators
"""
@serialize
def apidoc_on_options(resource, req, resp, *args, **kwargs):
d = {}
for key in dir(resource):
if key == "on_options": continue
if re.match("on_\w+", key):
func = getattr(resource, key)
d[key[3:]] = getattr(func, "_apidoc", None)
d[key[3:]]["description"] = (getattr(func, "__doc__") or u"").strip()
return d
:param str keytab_file: refer to ``krbContext.__init__``.
:param str ccache_file: refer to ``krbContext.__init__``.
:param str password: refer to ``krbContext.__init__``.
:return: a mapping containing cleaned names and values, which are used
internally.
:rtype: dict
:raises ValueError: principal is missing or given keytab file does not
exist, when initialize from a keytab.
"""
cleaned = {}
if using_keytab:
if principal is None:
raise ValueError('Principal is required when using key table.')
princ_name = gssapi.names.Name(
principal, gssapi.names.NameType.kerberos_principal)
if keytab_file is None:
cleaned['keytab'] = DEFAULT_KEYTAB
elif not os.path.exists(keytab_file):
raise ValueError(f'Keytab file {keytab_file} does not exist.')
else:
cleaned['keytab'] = keytab_file
else:
if principal is None:
principal = get_login()
princ_name = gssapi.names.Name(principal,
gssapi.names.NameType.user)
cleaned['using_keytab'] = using_keytab
cleaned['principal'] = princ_name
if using_keytab:
if principal is None:
raise ValueError('Principal is required when using key table.')
princ_name = gssapi.names.Name(
principal, gssapi.names.NameType.kerberos_principal)
if keytab_file is None:
cleaned['keytab'] = DEFAULT_KEYTAB
elif not os.path.exists(keytab_file):
raise ValueError(f'Keytab file {keytab_file} does not exist.')
else:
cleaned['keytab'] = keytab_file
else:
if principal is None:
principal = get_login()
princ_name = gssapi.names.Name(principal,
gssapi.names.NameType.user)
cleaned['using_keytab'] = using_keytab
cleaned['principal'] = princ_name
cleaned['ccache'] = ccache_file or DEFAULT_CCACHE
cleaned['password'] = password
return cleaned
if principal is None:
raise ValueError('Principal is required when using key table.')
princ_name = gssapi.names.Name(
principal, gssapi.names.NameType.kerberos_principal)
if keytab_file is None:
cleaned['keytab'] = DEFAULT_KEYTAB
elif not os.path.exists(keytab_file):
raise ValueError(f'Keytab file {keytab_file} does not exist.')
else:
cleaned['keytab'] = keytab_file
else:
if principal is None:
principal = get_login()
princ_name = gssapi.names.Name(principal,
gssapi.names.NameType.user)
cleaned['using_keytab'] = using_keytab
cleaned['principal'] = princ_name
cleaned['ccache'] = ccache_file or DEFAULT_CCACHE
cleaned['password'] = password
return cleaned