2016-06-30 22:00:53 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
2015-05-27 20:10:06 +00:00
|
|
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
|
|
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
|
|
|
# FOR A PARTICULAR PURPOSE. See the GNU General Public License version 3 for
|
|
|
|
# more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License version 3
|
|
|
|
# along with this program; if not, write to the Free Software Foundation, Inc., 51
|
|
|
|
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
|
|
#
|
2016-06-30 22:00:53 +00:00
|
|
|
# (c) 2015-2016 Valentin Samir
|
2015-05-27 19:56:39 +00:00
|
|
|
"""Some util function for the app"""
|
2015-05-30 17:45:59 +00:00
|
|
|
from .default_settings import settings
|
2015-05-28 13:08:57 +00:00
|
|
|
|
2015-05-29 14:11:10 +00:00
|
|
|
from django.core.urlresolvers import reverse
|
2015-11-17 13:50:16 +00:00
|
|
|
from django.http import HttpResponseRedirect, HttpResponse
|
|
|
|
from django.contrib import messages
|
2016-07-23 23:49:03 +00:00
|
|
|
from django.contrib.messages import constants as DEFAULT_MESSAGE_LEVELS
|
|
|
|
from django.core.serializers.json import DjangoJSONEncoder
|
2016-08-05 15:56:34 +00:00
|
|
|
from django.utils import timezone
|
2016-08-21 07:03:32 +00:00
|
|
|
from django.core.exceptions import ValidationError
|
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2015-05-28 13:08:57 +00:00
|
|
|
|
2016-08-21 07:03:32 +00:00
|
|
|
import re
|
2015-05-28 13:08:57 +00:00
|
|
|
import random
|
|
|
|
import string
|
2015-11-17 13:50:16 +00:00
|
|
|
import json
|
2016-06-26 18:29:47 +00:00
|
|
|
import hashlib
|
|
|
|
import crypt
|
|
|
|
import base64
|
|
|
|
import six
|
2016-07-29 12:33:02 +00:00
|
|
|
import requests
|
|
|
|
import time
|
|
|
|
import logging
|
2016-08-01 16:29:24 +00:00
|
|
|
import binascii
|
2016-06-30 21:13:53 +00:00
|
|
|
|
2015-12-12 12:51:59 +00:00
|
|
|
from importlib import import_module
|
2016-06-17 17:28:49 +00:00
|
|
|
from datetime import datetime, timedelta
|
2016-06-24 21:37:24 +00:00
|
|
|
from six.moves.urllib.parse import urlparse, urlunparse, parse_qsl, urlencode
|
2015-06-21 16:56:16 +00:00
|
|
|
|
2016-07-29 12:33:02 +00:00
|
|
|
from . import VERSION
|
|
|
|
|
|
|
|
#: logger facility
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2015-06-21 16:56:16 +00:00
|
|
|
|
2016-07-23 23:49:03 +00:00
|
|
|
def json_encode(obj):
|
|
|
|
"""Encode a python object to json"""
|
|
|
|
try:
|
|
|
|
return json_encode.encoder.encode(obj)
|
|
|
|
except AttributeError:
|
|
|
|
json_encode.encoder = DjangoJSONEncoder(default=six.text_type)
|
|
|
|
return json_encode(obj)
|
|
|
|
|
|
|
|
|
2016-06-20 11:31:59 +00:00
|
|
|
def context(params):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Function that add somes variable to the context before template rendering
|
|
|
|
|
|
|
|
:param dict params: The context dictionary used to render templates.
|
|
|
|
:return: The ``params`` dictionary with the key ``settings`` set to
|
|
|
|
:obj:`django.conf.settings`.
|
|
|
|
:rtype: dict
|
|
|
|
"""
|
2016-06-20 11:31:59 +00:00
|
|
|
params["settings"] = settings
|
2016-07-23 23:49:03 +00:00
|
|
|
params["message_levels"] = DEFAULT_MESSAGE_LEVELS
|
2016-07-29 12:33:02 +00:00
|
|
|
if settings.CAS_NEW_VERSION_HTML_WARNING:
|
|
|
|
LAST_VERSION = last_version()
|
|
|
|
params["VERSION"] = VERSION
|
|
|
|
params["LAST_VERSION"] = LAST_VERSION
|
|
|
|
if LAST_VERSION is not None:
|
2016-07-29 13:11:43 +00:00
|
|
|
params["upgrade_available"] = decode_version(VERSION) < decode_version(LAST_VERSION)
|
2016-07-29 12:33:02 +00:00
|
|
|
else:
|
|
|
|
params["upgrade_available"] = False
|
2016-06-20 11:31:59 +00:00
|
|
|
return params
|
|
|
|
|
|
|
|
|
2016-06-26 14:02:25 +00:00
|
|
|
def json_response(request, data):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Wrapper dumping `data` to a json and sending it to the user with an HttpResponse
|
|
|
|
|
|
|
|
:param django.http.HttpRequest request: The request object used to generate this response.
|
|
|
|
:param dict data: The python dictionnary to return as a json
|
|
|
|
:return: The content of ``data`` serialized in json
|
|
|
|
:rtype: django.http.HttpResponse
|
|
|
|
"""
|
2015-11-17 13:50:16 +00:00
|
|
|
data["messages"] = []
|
|
|
|
for msg in messages.get_messages(request):
|
|
|
|
data["messages"].append({'message': msg.message, 'level': msg.level_tag})
|
|
|
|
return HttpResponse(json.dumps(data), content_type="application/json")
|
|
|
|
|
|
|
|
|
2015-05-30 17:45:59 +00:00
|
|
|
def import_attr(path):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
transform a python dotted path to the attr
|
|
|
|
|
|
|
|
:param path: A dotted path to a python object or a python object
|
|
|
|
:type path: :obj:`unicode` or anything
|
|
|
|
:return: The python object pointed by the dotted path or the python object unchanged
|
|
|
|
"""
|
2015-05-30 17:45:59 +00:00
|
|
|
if not isinstance(path, str):
|
2016-05-11 11:06:41 +00:00
|
|
|
return path
|
2016-03-18 12:03:23 +00:00
|
|
|
if "." not in path:
|
|
|
|
ValueError("%r should be of the form `module.attr` and we just got `attr`" % path)
|
2015-05-30 17:45:59 +00:00
|
|
|
module, attr = path.rsplit('.', 1)
|
2016-03-18 12:03:23 +00:00
|
|
|
try:
|
|
|
|
return getattr(import_module(module), attr)
|
|
|
|
except ImportError:
|
|
|
|
raise ImportError("Module %r not found" % module)
|
|
|
|
except AttributeError:
|
|
|
|
raise AttributeError("Module %r has not attribut %r" % (module, attr))
|
2015-05-30 17:45:59 +00:00
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2015-05-29 14:11:10 +00:00
|
|
|
def redirect_params(url_name, params=None):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Redirect to ``url_name`` with ``params`` as querystring
|
|
|
|
|
|
|
|
:param unicode url_name: a URL pattern name
|
|
|
|
:param params: Some parameter to append to the reversed URL
|
|
|
|
:type params: :obj:`dict` or :obj:`NoneType<types.NoneType>`
|
|
|
|
:return: A redirection to the URL with name ``url_name`` with ``params`` as querystring.
|
|
|
|
:rtype: django.http.HttpResponseRedirect
|
|
|
|
"""
|
2015-05-29 14:11:10 +00:00
|
|
|
url = reverse(url_name)
|
2015-06-21 16:56:16 +00:00
|
|
|
params = urlencode(params if params else {})
|
2015-05-29 14:11:10 +00:00
|
|
|
return HttpResponseRedirect(url + "?%s" % params)
|
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2015-11-17 13:50:16 +00:00
|
|
|
def reverse_params(url_name, params=None, **kwargs):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
compute the reverse url of ``url_name`` and add to it parameters from ``params``
|
|
|
|
as querystring
|
|
|
|
|
|
|
|
:param unicode url_name: a URL pattern name
|
|
|
|
:param params: Some parameter to append to the reversed URL
|
|
|
|
:type params: :obj:`dict` or :obj:`NoneType<types.NoneType>`
|
|
|
|
:param **kwargs: additional parameters needed to compure the reverse URL
|
|
|
|
:return: The computed reverse URL of ``url_name`` with possible querystring from ``params``
|
|
|
|
:rtype: unicode
|
|
|
|
"""
|
2015-11-17 13:50:16 +00:00
|
|
|
url = reverse(url_name, **kwargs)
|
|
|
|
params = urlencode(params if params else {})
|
2016-06-17 17:28:49 +00:00
|
|
|
if params:
|
2016-07-20 16:28:23 +00:00
|
|
|
return u"%s?%s" % (url, params)
|
2016-06-17 17:28:49 +00:00
|
|
|
else:
|
|
|
|
return url
|
|
|
|
|
|
|
|
|
2016-06-27 22:48:48 +00:00
|
|
|
def copy_params(get_or_post_params, ignore=None):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
copy a :class:`django.http.QueryDict` in a :obj:`dict` ignoring keys in the set ``ignore``
|
|
|
|
|
|
|
|
:param django.http.QueryDict get_or_post_params: A GET or POST
|
|
|
|
:class:`QueryDict<django.http.QueryDict>`
|
|
|
|
:param set ignore: An optinal set of keys to ignore during the copy
|
|
|
|
:return: A copy of get_or_post_params
|
|
|
|
:rtype: dict
|
|
|
|
"""
|
2016-06-27 22:48:48 +00:00
|
|
|
if ignore is None:
|
|
|
|
ignore = set()
|
2016-06-17 17:28:49 +00:00
|
|
|
params = {}
|
|
|
|
for key in get_or_post_params:
|
|
|
|
if key not in ignore and get_or_post_params[key]:
|
|
|
|
params[key] = get_or_post_params[key]
|
|
|
|
return params
|
|
|
|
|
|
|
|
|
|
|
|
def set_cookie(response, key, value, max_age):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Set the cookie ``key`` on ``response`` with value ``value`` valid for ``max_age`` secondes
|
|
|
|
|
|
|
|
:param django.http.HttpResponse response: a django response where to set the cookie
|
|
|
|
:param unicode key: the cookie key
|
|
|
|
:param unicode value: the cookie value
|
|
|
|
:param int max_age: the maximum validity age of the cookie
|
|
|
|
"""
|
2016-06-17 17:28:49 +00:00
|
|
|
expires = datetime.strftime(
|
|
|
|
datetime.utcnow() + timedelta(seconds=max_age),
|
|
|
|
"%a, %d-%b-%Y %H:%M:%S GMT"
|
|
|
|
)
|
|
|
|
response.set_cookie(
|
|
|
|
key,
|
|
|
|
value,
|
|
|
|
max_age=max_age,
|
|
|
|
expires=expires,
|
|
|
|
domain=settings.SESSION_COOKIE_DOMAIN,
|
|
|
|
secure=settings.SESSION_COOKIE_SECURE or None
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2016-06-27 22:48:48 +00:00
|
|
|
def get_current_url(request, ignore_params=None):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Giving a django request, return the current http url, possibly ignoring some GET parameters
|
|
|
|
|
|
|
|
:param django.http.HttpRequest request: The current request object.
|
|
|
|
:param set ignore_params: An optional set of GET parameters to ignore
|
|
|
|
:return: The URL of the current page, possibly omitting some parameters from
|
|
|
|
``ignore_params`` in the querystring.
|
|
|
|
:rtype: unicode
|
|
|
|
"""
|
2016-06-27 22:48:48 +00:00
|
|
|
if ignore_params is None:
|
|
|
|
ignore_params = set()
|
2016-07-20 16:28:23 +00:00
|
|
|
protocol = u'https' if request.is_secure() else u"http"
|
|
|
|
service_url = u"%s://%s%s" % (protocol, request.get_host(), request.path)
|
2016-06-17 17:28:49 +00:00
|
|
|
if request.GET:
|
|
|
|
params = copy_params(request.GET, ignore_params)
|
|
|
|
if params:
|
2016-07-20 16:28:23 +00:00
|
|
|
service_url += u"?%s" % urlencode(params)
|
2016-06-17 17:28:49 +00:00
|
|
|
return service_url
|
2015-11-17 13:50:16 +00:00
|
|
|
|
|
|
|
|
2015-05-16 21:43:46 +00:00
|
|
|
def update_url(url, params):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
update parameters using ``params`` in the ``url`` query string
|
|
|
|
|
|
|
|
:param url: An URL possibily with a querystring
|
|
|
|
:type url: :obj:`unicode` or :obj:`str`
|
|
|
|
:param dict params: A dictionary of parameters for updating the url querystring
|
|
|
|
:return: The URL with an updated querystring
|
|
|
|
:rtype: unicode
|
|
|
|
"""
|
2015-06-21 16:56:16 +00:00
|
|
|
if not isinstance(url, bytes):
|
2015-06-12 16:10:52 +00:00
|
|
|
url = url.encode('utf-8')
|
2015-06-21 16:56:16 +00:00
|
|
|
for key, value in list(params.items()):
|
|
|
|
if not isinstance(key, bytes):
|
2015-06-03 15:42:25 +00:00
|
|
|
del params[key]
|
|
|
|
key = key.encode('utf-8')
|
2015-06-21 16:56:16 +00:00
|
|
|
if not isinstance(value, bytes):
|
2015-06-03 15:42:25 +00:00
|
|
|
value = value.encode('utf-8')
|
|
|
|
params[key] = value
|
2015-06-21 16:56:16 +00:00
|
|
|
url_parts = list(urlparse(url))
|
|
|
|
query = dict(parse_qsl(url_parts[4]))
|
2015-05-16 21:43:46 +00:00
|
|
|
query.update(params)
|
2016-06-30 22:09:51 +00:00
|
|
|
# make the params order deterministic
|
|
|
|
query = list(query.items())
|
|
|
|
query.sort()
|
|
|
|
url_query = urlencode(query)
|
2016-06-30 23:10:33 +00:00
|
|
|
if not isinstance(url_query, bytes): # pragma: no cover in python3 urlencode return an unicode
|
2016-06-30 22:09:51 +00:00
|
|
|
url_query = url_query.encode("utf-8")
|
|
|
|
url_parts[4] = url_query
|
2015-06-21 16:56:16 +00:00
|
|
|
return urlunparse(url_parts).decode('utf-8')
|
2015-05-28 13:08:57 +00:00
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2015-05-28 13:08:57 +00:00
|
|
|
def unpack_nested_exception(error):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
If exception are stacked, return the first one
|
|
|
|
|
|
|
|
:param error: A python exception with possible exception embeded within
|
|
|
|
:return: A python exception with no exception embeded within
|
|
|
|
"""
|
2015-05-28 13:08:57 +00:00
|
|
|
i = 0
|
|
|
|
while True:
|
|
|
|
if error.args[i:]:
|
|
|
|
if isinstance(error.args[i], Exception):
|
|
|
|
error = error.args[i]
|
|
|
|
i = 0
|
|
|
|
else:
|
|
|
|
i += 1
|
|
|
|
else:
|
|
|
|
break
|
|
|
|
return error
|
|
|
|
|
|
|
|
|
2016-07-20 16:28:23 +00:00
|
|
|
def _gen_ticket(prefix=None, lg=settings.CAS_TICKET_LEN):
|
|
|
|
"""
|
|
|
|
Generate a ticket with prefix ``prefix`` and length ``lg``
|
|
|
|
|
|
|
|
:param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU)
|
|
|
|
:param int lg: The length of the generated ticket (with the prefix)
|
|
|
|
:return: A randomlly generated ticket of length ``lg``
|
|
|
|
:rtype: unicode
|
|
|
|
"""
|
|
|
|
random_part = u''.join(
|
|
|
|
random.choice(
|
|
|
|
string.ascii_letters + string.digits
|
|
|
|
) for _ in range(lg - len(prefix or "") - 1)
|
2015-05-28 13:08:57 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
if prefix is not None:
|
|
|
|
return u'%s-%s' % (prefix, random_part)
|
|
|
|
else:
|
|
|
|
return random_part
|
2015-05-28 13:08:57 +00:00
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2015-06-05 13:44:17 +00:00
|
|
|
def gen_lt():
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Generate a Login Ticket
|
|
|
|
|
|
|
|
:return: A ticket with prefix ``settings.CAS_LOGIN_TICKET_PREFIX`` and length
|
|
|
|
``settings.CAS_LT_LEN``
|
|
|
|
:rtype: unicode
|
|
|
|
"""
|
2015-06-05 13:44:17 +00:00
|
|
|
return _gen_ticket(settings.CAS_LOGIN_TICKET_PREFIX, settings.CAS_LT_LEN)
|
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2015-05-28 13:08:57 +00:00
|
|
|
def gen_st():
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Generate a Service Ticket
|
|
|
|
|
|
|
|
:return: A ticket with prefix ``settings.CAS_SERVICE_TICKET_PREFIX`` and length
|
|
|
|
``settings.CAS_ST_LEN``
|
|
|
|
:rtype: unicode
|
|
|
|
"""
|
2015-06-05 13:44:17 +00:00
|
|
|
return _gen_ticket(settings.CAS_SERVICE_TICKET_PREFIX, settings.CAS_ST_LEN)
|
2015-05-28 13:08:57 +00:00
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2015-05-28 13:08:57 +00:00
|
|
|
def gen_pt():
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Generate a Proxy Ticket
|
|
|
|
|
|
|
|
:return: A ticket with prefix ``settings.CAS_PROXY_TICKET_PREFIX`` and length
|
|
|
|
``settings.CAS_PT_LEN``
|
|
|
|
:rtype: unicode
|
|
|
|
"""
|
2015-06-05 13:44:17 +00:00
|
|
|
return _gen_ticket(settings.CAS_PROXY_TICKET_PREFIX, settings.CAS_PT_LEN)
|
2015-05-28 13:08:57 +00:00
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2015-05-28 13:08:57 +00:00
|
|
|
def gen_pgt():
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Generate a Proxy Granting Ticket
|
|
|
|
|
|
|
|
:return: A ticket with prefix ``settings.CAS_PROXY_GRANTING_TICKET_PREFIX`` and length
|
|
|
|
``settings.CAS_PGT_LEN``
|
|
|
|
:rtype: unicode
|
|
|
|
"""
|
2015-06-05 13:44:17 +00:00
|
|
|
return _gen_ticket(settings.CAS_PROXY_GRANTING_TICKET_PREFIX, settings.CAS_PGT_LEN)
|
2015-05-28 13:08:57 +00:00
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2015-05-28 13:08:57 +00:00
|
|
|
def gen_pgtiou():
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Generate a Proxy Granting Ticket IOU
|
|
|
|
|
|
|
|
:return: A ticket with prefix ``settings.CAS_PROXY_GRANTING_TICKET_IOU_PREFIX`` and length
|
|
|
|
``settings.CAS_PGTIOU_LEN``
|
|
|
|
:rtype: unicode
|
|
|
|
"""
|
2015-06-05 13:44:17 +00:00
|
|
|
return _gen_ticket(settings.CAS_PROXY_GRANTING_TICKET_IOU_PREFIX, settings.CAS_PGTIOU_LEN)
|
2015-05-28 13:08:57 +00:00
|
|
|
|
2015-05-28 13:17:11 +00:00
|
|
|
|
|
|
|
def gen_saml_id():
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Generate an saml id
|
|
|
|
|
|
|
|
:return: A random id of length ``settings.CAS_TICKET_LEN``
|
|
|
|
:rtype: unicode
|
|
|
|
"""
|
|
|
|
return _gen_ticket()
|
2016-06-21 12:42:35 +00:00
|
|
|
|
|
|
|
|
2016-06-27 22:48:48 +00:00
|
|
|
def get_tuple(nuplet, index, default=None):
|
2016-07-03 15:54:11 +00:00
|
|
|
"""
|
2016-07-20 16:28:23 +00:00
|
|
|
:param tuple nuplet: A tuple
|
|
|
|
:param int index: An index
|
|
|
|
:param default: An optional default value
|
|
|
|
:return: ``nuplet[index]`` if defined, else ``default`` (possibly ``None``)
|
2016-07-03 15:54:11 +00:00
|
|
|
"""
|
2016-06-27 22:48:48 +00:00
|
|
|
if nuplet is None:
|
2016-06-23 15:18:53 +00:00
|
|
|
return default
|
2016-06-21 12:42:35 +00:00
|
|
|
try:
|
2016-06-27 22:48:48 +00:00
|
|
|
return nuplet[index]
|
2016-06-21 12:42:35 +00:00
|
|
|
except IndexError:
|
|
|
|
return default
|
2016-06-27 22:34:31 +00:00
|
|
|
|
2016-06-27 22:37:18 +00:00
|
|
|
|
2016-06-30 23:10:33 +00:00
|
|
|
def crypt_salt_is_valid(salt):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Validate a salt as crypt salt
|
|
|
|
|
|
|
|
:param str salt: a password salt
|
|
|
|
:return: ``True`` if ``salt`` is a valid crypt salt on this system, ``False`` otherwise
|
|
|
|
:rtype: bool
|
|
|
|
"""
|
2016-06-30 23:10:33 +00:00
|
|
|
if len(salt) < 2:
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
if salt[0] == '$':
|
|
|
|
if salt[1] == '$':
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
if '$' not in salt[1:]:
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
hashed = crypt.crypt("", salt)
|
|
|
|
if not hashed or '$' not in hashed[1:]:
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return True
|
2016-06-26 18:29:47 +00:00
|
|
|
|
2016-06-26 19:44:41 +00:00
|
|
|
|
2016-06-26 18:29:47 +00:00
|
|
|
class LdapHashUserPassword(object):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Class to deal with hashed password as defined at
|
|
|
|
https://tools.ietf.org/id/draft-stroeder-hashed-userpassword-values-01.html
|
|
|
|
"""
|
2016-06-26 18:29:47 +00:00
|
|
|
|
2016-07-20 16:28:23 +00:00
|
|
|
#: valide schemes that require a salt
|
2016-06-26 18:29:47 +00:00
|
|
|
schemes_salt = {b"{SMD5}", b"{SSHA}", b"{SSHA256}", b"{SSHA384}", b"{SSHA512}", b"{CRYPT}"}
|
2016-07-20 16:28:23 +00:00
|
|
|
#: valide sschemes that require no slat
|
2016-06-26 18:29:47 +00:00
|
|
|
schemes_nosalt = {b"{MD5}", b"{SHA}", b"{SHA256}", b"{SHA384}", b"{SHA512}"}
|
|
|
|
|
2016-07-20 16:28:23 +00:00
|
|
|
#: map beetween scheme and hash function
|
2016-06-26 18:29:47 +00:00
|
|
|
_schemes_to_hash = {
|
|
|
|
b"{SMD5}": hashlib.md5,
|
|
|
|
b"{MD5}": hashlib.md5,
|
|
|
|
b"{SSHA}": hashlib.sha1,
|
|
|
|
b"{SHA}": hashlib.sha1,
|
|
|
|
b"{SSHA256}": hashlib.sha256,
|
|
|
|
b"{SHA256}": hashlib.sha256,
|
|
|
|
b"{SSHA384}": hashlib.sha384,
|
|
|
|
b"{SHA384}": hashlib.sha384,
|
|
|
|
b"{SSHA512}": hashlib.sha512,
|
|
|
|
b"{SHA512}": hashlib.sha512
|
|
|
|
}
|
|
|
|
|
2016-07-20 16:28:23 +00:00
|
|
|
#: map between scheme and hash length
|
2016-06-26 18:29:47 +00:00
|
|
|
_schemes_to_len = {
|
|
|
|
b"{SMD5}": 16,
|
|
|
|
b"{SSHA}": 20,
|
|
|
|
b"{SSHA256}": 32,
|
|
|
|
b"{SSHA384}": 48,
|
|
|
|
b"{SSHA512}": 64,
|
|
|
|
}
|
|
|
|
|
|
|
|
class BadScheme(ValueError):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Error raised then the hash scheme is not in
|
|
|
|
:attr:`LdapHashUserPassword.schemes_salt` + :attr:`LdapHashUserPassword.schemes_nosalt`
|
|
|
|
"""
|
2016-06-26 18:29:47 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
class BadHash(ValueError):
|
2016-06-26 20:07:38 +00:00
|
|
|
"""Error raised then the hash is too short"""
|
2016-06-26 18:29:47 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
class BadSalt(ValueError):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""Error raised then, with the scheme ``{CRYPT}``, the salt is invalid"""
|
2016-06-26 18:29:47 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _raise_bad_scheme(cls, scheme, valid, msg):
|
2016-06-26 20:07:38 +00:00
|
|
|
"""
|
2016-07-20 16:28:23 +00:00
|
|
|
Raise :attr:`BadScheme` error for ``scheme``, possible valid scheme are
|
|
|
|
in ``valid``, the error message is ``msg``
|
|
|
|
|
|
|
|
:param bytes scheme: A bad scheme
|
|
|
|
:param list valid: A list a valid scheme
|
|
|
|
:param str msg: The error template message
|
|
|
|
:raises LdapHashUserPassword.BadScheme: always
|
2016-06-26 20:07:38 +00:00
|
|
|
"""
|
2016-06-26 19:44:41 +00:00
|
|
|
valid_schemes = [s.decode() for s in valid]
|
2016-06-26 18:29:47 +00:00
|
|
|
valid_schemes.sort()
|
2016-06-26 19:44:41 +00:00
|
|
|
raise cls.BadScheme(msg % (scheme, u", ".join(valid_schemes)))
|
2016-06-26 18:29:47 +00:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _test_scheme(cls, scheme):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Test if a scheme is valide or raise BadScheme
|
|
|
|
|
|
|
|
:param bytes scheme: A scheme
|
|
|
|
:raises BadScheme: if ``scheme`` is not a valid scheme
|
|
|
|
"""
|
2016-06-26 18:29:47 +00:00
|
|
|
if scheme not in cls.schemes_salt and scheme not in cls.schemes_nosalt:
|
|
|
|
cls._raise_bad_scheme(
|
|
|
|
scheme,
|
|
|
|
cls.schemes_salt | cls.schemes_nosalt,
|
|
|
|
"The scheme %r is not valid. Valide schemes are %s."
|
|
|
|
)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _test_scheme_salt(cls, scheme):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Test if the scheme need a salt or raise BadScheme
|
|
|
|
|
|
|
|
:param bytes scheme: A scheme
|
|
|
|
:raises BadScheme: if ``scheme` require no salt
|
|
|
|
"""
|
2016-06-26 18:29:47 +00:00
|
|
|
if scheme not in cls.schemes_salt:
|
|
|
|
cls._raise_bad_scheme(
|
|
|
|
scheme,
|
|
|
|
cls.schemes_salt,
|
|
|
|
"The scheme %r is only valid without a salt. Valide schemes with salt are %s."
|
|
|
|
)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _test_scheme_nosalt(cls, scheme):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Test if the scheme need no salt or raise BadScheme
|
|
|
|
|
|
|
|
:param bytes scheme: A scheme
|
|
|
|
:raises BadScheme: if ``scheme` require a salt
|
|
|
|
"""
|
2016-06-26 18:29:47 +00:00
|
|
|
if scheme not in cls.schemes_nosalt:
|
|
|
|
cls._raise_bad_scheme(
|
|
|
|
scheme,
|
|
|
|
cls.schemes_nosalt,
|
|
|
|
"The scheme %r is only valid with a salt. Valide schemes without salt are %s."
|
|
|
|
)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def hash(cls, scheme, password, salt=None, charset="utf8"):
|
2016-06-26 20:07:38 +00:00
|
|
|
"""
|
2016-07-20 16:28:23 +00:00
|
|
|
Hash ``password`` with ``scheme`` using ``salt``.
|
|
|
|
This three variable beeing encoded in ``charset``.
|
|
|
|
|
|
|
|
:param bytes scheme: A valid scheme
|
|
|
|
:param bytes password: A byte string to hash using ``scheme``
|
|
|
|
:param bytes salt: An optional salt to use if ``scheme`` requires any
|
|
|
|
:param str charset: The encoding of ``scheme``, ``password`` and ``salt``
|
|
|
|
:return: The hashed password encoded with ``charset``
|
|
|
|
:rtype: bytes
|
2016-06-26 20:07:38 +00:00
|
|
|
"""
|
2016-06-26 18:29:47 +00:00
|
|
|
scheme = scheme.upper()
|
|
|
|
cls._test_scheme(scheme)
|
|
|
|
if salt is None or salt == b"":
|
|
|
|
salt = b""
|
|
|
|
cls._test_scheme_nosalt(scheme)
|
2016-06-30 22:00:33 +00:00
|
|
|
else:
|
2016-06-26 18:29:47 +00:00
|
|
|
cls._test_scheme_salt(scheme)
|
|
|
|
try:
|
2016-06-26 19:44:41 +00:00
|
|
|
return scheme + base64.b64encode(
|
|
|
|
cls._schemes_to_hash[scheme](password + salt).digest() + salt
|
|
|
|
)
|
2016-06-26 18:29:47 +00:00
|
|
|
except KeyError:
|
|
|
|
if six.PY3:
|
|
|
|
password = password.decode(charset)
|
|
|
|
salt = salt.decode(charset)
|
2016-06-30 23:10:33 +00:00
|
|
|
if not crypt_salt_is_valid(salt):
|
2016-06-26 18:29:47 +00:00
|
|
|
raise cls.BadSalt("System crypt implementation do not support the salt %r" % salt)
|
2016-06-30 23:10:33 +00:00
|
|
|
hashed_password = crypt.crypt(password, salt)
|
2016-06-26 18:29:47 +00:00
|
|
|
if six.PY3:
|
|
|
|
hashed_password = hashed_password.encode(charset)
|
|
|
|
return scheme + hashed_password
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get_scheme(cls, hashed_passord):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Return the scheme of ``hashed_passord`` or raise :attr:`BadHash`
|
|
|
|
|
|
|
|
:param bytes hashed_passord: A hashed password
|
|
|
|
:return: The scheme used by the hashed password
|
|
|
|
:rtype: bytes
|
|
|
|
:raises BadHash: if no valid scheme is found within ``hashed_passord``
|
|
|
|
"""
|
2016-06-26 19:44:41 +00:00
|
|
|
if not hashed_passord[0] == b'{'[0] or b'}' not in hashed_passord:
|
2016-06-26 18:29:47 +00:00
|
|
|
raise cls.BadHash("%r should start with the scheme enclosed with { }" % hashed_passord)
|
|
|
|
scheme = hashed_passord.split(b'}', 1)[0]
|
|
|
|
scheme = scheme.upper() + b"}"
|
|
|
|
return scheme
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get_salt(cls, hashed_passord):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Return the salt of ``hashed_passord`` possibly empty
|
|
|
|
|
|
|
|
:param bytes hashed_passord: A hashed password
|
|
|
|
:return: The salt used by the hashed password (empty if no salt is used)
|
|
|
|
:rtype: bytes
|
|
|
|
:raises BadHash: if no valid scheme is found within ``hashed_passord`` or if the
|
|
|
|
hashed password is too short for the scheme found.
|
|
|
|
"""
|
2016-06-26 18:29:47 +00:00
|
|
|
scheme = cls.get_scheme(hashed_passord)
|
|
|
|
cls._test_scheme(scheme)
|
|
|
|
if scheme in cls.schemes_nosalt:
|
|
|
|
return b""
|
|
|
|
elif scheme == b'{CRYPT}':
|
2016-06-30 22:00:33 +00:00
|
|
|
return b'$'.join(hashed_passord.split(b'$', 3)[:-1])[len(scheme):]
|
2016-06-26 18:29:47 +00:00
|
|
|
else:
|
2016-07-31 10:27:14 +00:00
|
|
|
try:
|
|
|
|
hashed_passord = base64.b64decode(hashed_passord[len(scheme):])
|
2016-08-01 16:29:24 +00:00
|
|
|
except (TypeError, binascii.Error) as error:
|
2016-07-31 10:27:14 +00:00
|
|
|
raise cls.BadHash("Bad base64: %s" % error)
|
2016-06-26 18:29:47 +00:00
|
|
|
if len(hashed_passord) < cls._schemes_to_len[scheme]:
|
|
|
|
raise cls.BadHash("Hash too short for the scheme %s" % scheme)
|
|
|
|
return hashed_passord[cls._schemes_to_len[scheme]:]
|
|
|
|
|
|
|
|
|
|
|
|
def check_password(method, password, hashed_password, charset):
|
2016-06-26 20:07:38 +00:00
|
|
|
"""
|
2016-07-20 16:28:23 +00:00
|
|
|
Check that ``password`` match `hashed_password` using ``method``,
|
|
|
|
assuming the encoding is ``charset``.
|
|
|
|
|
|
|
|
:param str method: on of ``"crypt"``, ``"ldap"``, ``"hex_md5"``, ``"hex_sha1"``,
|
|
|
|
``"hex_sha224"``, ``"hex_sha256"``, ``"hex_sha384"``, ``"hex_sha512"``, ``"plain"``
|
|
|
|
:param password: The user inputed password
|
|
|
|
:type password: :obj:`str` or :obj:`unicode`
|
|
|
|
:param hashed_password: The hashed password as stored in the database
|
|
|
|
:type hashed_password: :obj:`str` or :obj:`unicode`
|
|
|
|
:param str charset: The used char encoding (also used internally, so it must be valid for
|
2016-07-31 14:52:19 +00:00
|
|
|
the charset used by ``password`` when it was initially )
|
2016-07-20 16:28:23 +00:00
|
|
|
:return: True if ``password`` match ``hashed_password`` using ``method``,
|
|
|
|
``False`` otherwise
|
|
|
|
:rtype: bool
|
2016-06-26 20:07:38 +00:00
|
|
|
"""
|
2016-06-26 18:29:47 +00:00
|
|
|
if not isinstance(password, six.binary_type):
|
|
|
|
password = password.encode(charset)
|
|
|
|
if not isinstance(hashed_password, six.binary_type):
|
|
|
|
hashed_password = hashed_password.encode(charset)
|
|
|
|
if method == "plain":
|
|
|
|
return password == hashed_password
|
|
|
|
elif method == "crypt":
|
|
|
|
if hashed_password.startswith(b'$'):
|
|
|
|
salt = b'$'.join(hashed_password.split(b'$', 3)[:-1])
|
2016-06-30 22:00:33 +00:00
|
|
|
elif hashed_password.startswith(b'_'): # pragma: no cover old BSD format not supported
|
2016-06-26 18:29:47 +00:00
|
|
|
salt = hashed_password[:9]
|
|
|
|
else:
|
|
|
|
salt = hashed_password[:2]
|
|
|
|
if six.PY3:
|
|
|
|
password = password.decode(charset)
|
|
|
|
salt = salt.decode(charset)
|
|
|
|
hashed_password = hashed_password.decode(charset)
|
2016-06-30 23:10:33 +00:00
|
|
|
if not crypt_salt_is_valid(salt):
|
2016-06-26 18:29:47 +00:00
|
|
|
raise ValueError("System crypt implementation do not support the salt %r" % salt)
|
2016-06-30 23:10:33 +00:00
|
|
|
crypted_password = crypt.crypt(password, salt)
|
2016-06-26 18:29:47 +00:00
|
|
|
return crypted_password == hashed_password
|
|
|
|
elif method == "ldap":
|
|
|
|
scheme = LdapHashUserPassword.get_scheme(hashed_password)
|
|
|
|
salt = LdapHashUserPassword.get_salt(hashed_password)
|
|
|
|
return LdapHashUserPassword.hash(scheme, password, salt, charset=charset) == hashed_password
|
|
|
|
elif (
|
|
|
|
method.startswith("hex_") and
|
|
|
|
method[4:] in {"md5", "sha1", "sha224", "sha256", "sha384", "sha512"}
|
|
|
|
):
|
2016-06-26 19:44:41 +00:00
|
|
|
return getattr(
|
|
|
|
hashlib,
|
|
|
|
method[4:]
|
|
|
|
)(password).hexdigest().encode("ascii") == hashed_password.lower()
|
2016-06-26 18:29:47 +00:00
|
|
|
else:
|
|
|
|
raise ValueError("Unknown password method check %r" % method)
|
2016-07-29 12:33:02 +00:00
|
|
|
|
|
|
|
|
|
|
|
def decode_version(version):
|
|
|
|
"""
|
|
|
|
decode a version string following version semantic http://semver.org/ input a tuple of int
|
|
|
|
|
|
|
|
:param unicode version: A dotted version
|
|
|
|
:return: A tuple a int
|
|
|
|
:rtype: tuple
|
|
|
|
"""
|
|
|
|
return tuple(int(sub_version) for sub_version in version.split('.'))
|
|
|
|
|
|
|
|
|
|
|
|
def last_version():
|
|
|
|
"""
|
|
|
|
Fetch the last version from pypi and return it. On successful fetch from pypi, the response
|
|
|
|
is cached 24h, on error, it is cached 10 min.
|
|
|
|
|
|
|
|
:return: the last django-cas-server version
|
|
|
|
:rtype: unicode
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
last_update, version, success = last_version._cache
|
|
|
|
except AttributeError:
|
|
|
|
last_update = 0
|
|
|
|
version = None
|
|
|
|
success = False
|
|
|
|
cache_delta = 24 * 3600 if success else 600
|
|
|
|
if (time.time() - last_update) < cache_delta:
|
|
|
|
return version
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
req = requests.get(settings.CAS_NEW_VERSION_JSON_URL)
|
2016-07-29 12:55:52 +00:00
|
|
|
data = json.loads(req.text)
|
|
|
|
versions = list(data["releases"].keys())
|
2016-07-29 12:33:02 +00:00
|
|
|
versions.sort()
|
|
|
|
version = versions[-1]
|
|
|
|
last_version._cache = (time.time(), version, True)
|
|
|
|
return version
|
|
|
|
except (
|
|
|
|
KeyError,
|
|
|
|
ValueError,
|
|
|
|
requests.exceptions.RequestException
|
2016-07-29 12:55:52 +00:00
|
|
|
) as error: # pragma: no cover (should not happen unless pypi is not available)
|
2016-07-29 12:33:02 +00:00
|
|
|
logger.error(
|
|
|
|
"Unable to fetch %s: %s" % (settings.CAS_NEW_VERSION_JSON_URL, error)
|
|
|
|
)
|
|
|
|
last_version._cache = (time.time(), version, False)
|
2016-07-31 14:52:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
def dictfetchall(cursor):
|
|
|
|
"Return all rows from a django cursor as a dict"
|
|
|
|
columns = [col[0] for col in cursor.description]
|
|
|
|
return [
|
|
|
|
dict(zip(columns, row))
|
|
|
|
for row in cursor.fetchall()
|
|
|
|
]
|
2016-08-05 15:56:34 +00:00
|
|
|
|
|
|
|
|
|
|
|
def logout_request(ticket):
|
|
|
|
"""
|
|
|
|
Forge a SLO logout request
|
|
|
|
|
|
|
|
:param unicode ticket: A ticket value
|
|
|
|
:return: A SLO XML body request
|
|
|
|
:rtype: unicode
|
|
|
|
"""
|
|
|
|
return u"""<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
|
|
|
|
ID="%(id)s" Version="2.0" IssueInstant="%(datetime)s">
|
|
|
|
<saml:NameID xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"></saml:NameID>
|
|
|
|
<samlp:SessionIndex>%(ticket)s</samlp:SessionIndex>
|
|
|
|
</samlp:LogoutRequest>""" % {
|
|
|
|
'id': gen_saml_id(),
|
|
|
|
'datetime': timezone.now().isoformat(),
|
|
|
|
'ticket': ticket
|
|
|
|
}
|
2016-08-21 07:03:32 +00:00
|
|
|
|
|
|
|
|
|
|
|
def regexpr_validator(value):
|
|
|
|
"""
|
|
|
|
Test that ``value`` is a valid regular expression
|
|
|
|
|
|
|
|
:param unicode value: A regular expression to test
|
|
|
|
:raises ValidationError: if ``value`` is not a valid regular expression
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
re.compile(value)
|
|
|
|
except re.error:
|
|
|
|
raise ValidationError(
|
|
|
|
_('"%(value)s" is not a valid regular expression'),
|
|
|
|
params={'value': value}
|
|
|
|
)
|