cas.py 14.4 KB
Newer Older
Valentin Samir's avatar
Valentin Samir committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# Copyright (C) 2014, Ming Chen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is furnished
# to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

# This file is originated from https://github.com/python-cas/python-cas
# at commit ec1f2d4779625229398547b9234d0e9e874a2c9a
Valentin Samir's avatar
Valentin Samir committed
23
# some modifications have been made to be unicode coherent between python2 and python2
Valentin Samir's avatar
Valentin Samir committed
24

25
import six
Valentin Samir's avatar
Valentin Samir committed
26 27 28 29 30 31 32 33 34 35 36
from six.moves.urllib import parse as urllib_parse
from six.moves.urllib import request as urllib_request
from six.moves.urllib.request import Request
from uuid import uuid4
import datetime


class CASError(ValueError):
    pass


37 38
class ReturnUnicode(object):
    @staticmethod
39
    def u(string, charset):
40 41 42 43 44 45
        if not isinstance(string, six.text_type):
            return string.decode(charset)
        else:
            return string


Valentin Samir's avatar
Valentin Samir committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
class SingleLogoutMixin(object):
    @classmethod
    def get_saml_slos(cls, logout_request):
        """returns saml logout ticket info"""
        from lxml import etree
        try:
            root = etree.fromstring(logout_request)
            return root.xpath(
                "//samlp:SessionIndex",
                namespaces={'samlp': "urn:oasis:names:tc:SAML:2.0:protocol"})
        except etree.XMLSyntaxError:
            pass


class CASClient(object):
    def __new__(self, *args, **kwargs):
        version = kwargs.pop('version')
        if version in (1, '1'):
            return CASClientV1(*args, **kwargs)
        elif version in (2, '2'):
            return CASClientV2(*args, **kwargs)
        elif version in (3, '3'):
            return CASClientV3(*args, **kwargs)
        elif version == 'CAS_2_SAML_1_0':
            return CASClientWithSAMLV1(*args, **kwargs)
        raise ValueError('Unsupported CAS_VERSION %r' % version)


class CASClientBase(object):

    logout_redirect_param_name = 'service'

    def __init__(self, service_url=None, server_url=None,
                 extra_login_params=None, renew=False,
                 username_attribute=None):

        self.service_url = service_url
        self.server_url = server_url
        self.extra_login_params = extra_login_params or {}
        self.renew = renew
        self.username_attribute = username_attribute
        pass

    def verify_ticket(self, ticket):
        """must return a triple"""
        raise NotImplementedError()

    def get_login_url(self):
        """Generates CAS login URL"""
        params = {'service': self.service_url}
        if self.renew:
            params.update({'renew': 'true'})

        params.update(self.extra_login_params)
        url = urllib_parse.urljoin(self.server_url, 'login')
        query = urllib_parse.urlencode(params)
        return url + '?' + query

    def get_logout_url(self, redirect_url=None):
        """Generates CAS logout URL"""
        url = urllib_parse.urljoin(self.server_url, 'logout')
        if redirect_url:
            params = {self.logout_redirect_param_name: redirect_url}
            url += '?' + urllib_parse.urlencode(params)
        return url

    def get_proxy_url(self, pgt):
        """Returns proxy url, given the proxy granting ticket"""
        params = urllib_parse.urlencode({'pgt': pgt, 'targetService': self.service_url})
        return "%s/proxy?%s" % (self.server_url, params)

    def get_proxy_ticket(self, pgt):
        """Returns proxy ticket given the proxy granting ticket"""
        response = urllib_request.urlopen(self.get_proxy_url(pgt))
        if response.code == 200:
            from lxml import etree
            root = etree.fromstring(response.read())
            tickets = root.xpath(
                "//cas:proxyTicket",
                namespaces={"cas": "http://www.yale.edu/tp/cas"}
            )
            if len(tickets) == 1:
                return tickets[0].text
            errors = root.xpath(
                "//cas:authenticationFailure",
                namespaces={"cas": "http://www.yale.edu/tp/cas"}
            )
            if len(errors) == 1:
                raise CASError(errors[0].attrib['code'], errors[0].text)
        raise CASError("Bad http code %s" % response.code)


138
class CASClientV1(CASClientBase, ReturnUnicode):
Valentin Samir's avatar
Valentin Samir committed
139 140 141 142 143 144 145 146 147
    """CAS Client Version 1"""

    logout_redirect_param_name = 'url'

    def verify_ticket(self, ticket):
        """Verifies CAS 1.0 authentication ticket.

        Returns username on success and None on failure.
        """
148
        params = [('ticket', ticket), ('service', self.service_url)]
Valentin Samir's avatar
Valentin Samir committed
149 150 151 152 153
        url = (urllib_parse.urljoin(self.server_url, 'validate') + '?' +
               urllib_parse.urlencode(params))
        page = urllib_request.urlopen(url)
        try:
            verified = page.readline().strip()
154 155 156 157 158 159
            if verified == b'yes':
                content_type = page.info().get('Content-type')
                if "charset=" in content_type:
                    charset = content_type.split("charset=")[-1]
                else:
                    charset = "ascii"
160
                user = self.u(page.readline().strip(), charset)
161
                return user, None, None
Valentin Samir's avatar
Valentin Samir committed
162 163 164 165 166 167
            else:
                return None, None, None
        finally:
            page.close()


168
class CASClientV2(CASClientBase, ReturnUnicode):
Valentin Samir's avatar
Valentin Samir committed
169 170 171 172 173 174 175 176 177 178 179 180
    """CAS Client Version 2"""

    url_suffix = 'serviceValidate'
    logout_redirect_param_name = 'url'

    def __init__(self, proxy_callback=None, *args, **kwargs):
        """proxy_callback is for V2 and V3 so V3 is subclass of V2"""
        self.proxy_callback = proxy_callback
        super(CASClientV2, self).__init__(*args, **kwargs)

    def verify_ticket(self, ticket):
        """Verifies CAS 2.0+/3.0+ XML-based authentication ticket and returns extended attributes"""
181 182
        (response, charset) = self.get_verification_response(ticket)
        return self.verify_response(response, charset)
Valentin Samir's avatar
Valentin Samir committed
183 184 185 186 187 188 189 190 191

    def get_verification_response(self, ticket):
        params = [('ticket', ticket), ('service', self.service_url)]
        if self.proxy_callback:
            params.append(('pgtUrl', self.proxy_callback))
        base_url = urllib_parse.urljoin(self.server_url, self.url_suffix)
        url = base_url + '?' + urllib_parse.urlencode(params)
        page = urllib_request.urlopen(url)
        try:
192 193 194 195 196 197
            content_type = page.info().get('Content-type')
            if "charset=" in content_type:
                charset = content_type.split("charset=")[-1]
            else:
                charset = "ascii"
            return (page.read(), charset)
Valentin Samir's avatar
Valentin Samir committed
198 199 200 201
        finally:
            page.close()

    @classmethod
202
    def parse_attributes_xml_element(cls, element, charset):
Valentin Samir's avatar
Valentin Samir committed
203 204
        attributes = dict()
        for attribute in element:
205
            tag = cls.self.u(attribute.tag, charset).split(u"}").pop()
Valentin Samir's avatar
Valentin Samir committed
206 207
            if tag in attributes:
                if isinstance(attributes[tag], list):
208
                    attributes[tag].append(cls.u(attribute.text, charset))
Valentin Samir's avatar
Valentin Samir committed
209 210
                else:
                    attributes[tag] = [attributes[tag]]
211
                    attributes[tag].append(cls.u(attribute.text, charset))
Valentin Samir's avatar
Valentin Samir committed
212
            else:
213
                if tag == u'attraStyle':
Valentin Samir's avatar
Valentin Samir committed
214 215
                    pass
                else:
216
                    attributes[tag] = cls.u(attribute.text, charset)
Valentin Samir's avatar
Valentin Samir committed
217 218 219
        return attributes

    @classmethod
220 221
    def verify_response(cls, response, charset):
        user, attributes, pgtiou = cls.parse_response_xml(response, charset)
Valentin Samir's avatar
Valentin Samir committed
222 223 224 225 226
        if len(attributes) == 0:
            attributes = None
        return user, attributes, pgtiou

    @classmethod
227
    def parse_response_xml(cls, response, charset):
Valentin Samir's avatar
Valentin Samir committed
228 229 230 231 232 233 234 235 236 237 238 239 240
        try:
            from xml.etree import ElementTree
        except ImportError:
            from elementtree import ElementTree

        user = None
        attributes = {}
        pgtiou = None

        tree = ElementTree.fromstring(response)
        if tree[0].tag.endswith('authenticationSuccess'):
            for element in tree[0]:
                if element.tag.endswith('user'):
241
                    user = cls.u(element.text, charset)
Valentin Samir's avatar
Valentin Samir committed
242
                elif element.tag.endswith('proxyGrantingTicket'):
243
                    pgtiou = cls.u(element.text, charset)
Valentin Samir's avatar
Valentin Samir committed
244
                elif element.tag.endswith('attributes'):
245
                    attributes = cls.parse_attributes_xml_element(element, charset)
Valentin Samir's avatar
Valentin Samir committed
246 247 248 249 250 251 252 253 254
        return user, attributes, pgtiou


class CASClientV3(CASClientV2, SingleLogoutMixin):
    """CAS Client Version 3"""
    url_suffix = 'serviceValidate'
    logout_redirect_param_name = 'service'

    @classmethod
255
    def parse_attributes_xml_element(cls, element, charset):
Valentin Samir's avatar
Valentin Samir committed
256 257
        attributes = dict()
        for attribute in element:
258
            tag = cls.u(attribute.tag, charset).split(u"}").pop()
Valentin Samir's avatar
Valentin Samir committed
259 260
            if tag in attributes:
                if isinstance(attributes[tag], list):
261
                    attributes[tag].append(cls.u(attribute.text, charset))
Valentin Samir's avatar
Valentin Samir committed
262 263
                else:
                    attributes[tag] = [attributes[tag]]
264
                    attributes[tag].append(cls.u(attribute.text, charset))
Valentin Samir's avatar
Valentin Samir committed
265
            else:
266
                attributes[tag] = cls.u(attribute.text, charset)
Valentin Samir's avatar
Valentin Samir committed
267 268 269
        return attributes

    @classmethod
270 271
    def verify_response(cls, response, charset):
        return cls.parse_response_xml(response, charset)
Valentin Samir's avatar
Valentin Samir committed
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308


SAML_1_0_NS = 'urn:oasis:names:tc:SAML:1.0:'
SAML_1_0_PROTOCOL_NS = '{' + SAML_1_0_NS + 'protocol' + '}'
SAML_1_0_ASSERTION_NS = '{' + SAML_1_0_NS + 'assertion' + '}'
SAML_ASSERTION_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<samlp:Request xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol"
MajorVersion="1"
MinorVersion="1"
RequestID="{request_id}"
IssueInstant="{timestamp}">
<samlp:AssertionArtifact>{ticket}</samlp:AssertionArtifact></samlp:Request>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>"""


class CASClientWithSAMLV1(CASClientV2, SingleLogoutMixin):
    """CASClient 3.0+ with SAML"""

    def verify_ticket(self, ticket, **kwargs):
        """Verifies CAS 3.0+ XML-based authentication ticket and returns extended attributes.

        @date: 2011-11-30
        @author: Carlos Gonzalez Vila <carlewis@gmail.com>

        Returns username and attributes on success and None,None on failure.
        """

        try:
            from xml.etree import ElementTree
        except ImportError:
            from elementtree import ElementTree

        page = self.fetch_saml_validation(ticket)
309 310 311 312 313
        content_type = page.info().get('Content-type')
        if "charset=" in content_type:
            charset = content_type.split("charset=")[-1]
        else:
            charset = "ascii"
Valentin Samir's avatar
Valentin Samir committed
314 315 316 317 318 319 320 321 322 323

        try:
            user = None
            attributes = {}
            response = page.read()
            tree = ElementTree.fromstring(response)
            # Find the authentication status
            success = tree.find('.//' + SAML_1_0_PROTOCOL_NS + 'StatusCode')
            if success is not None and success.attrib['Value'].endswith(':Success'):
                # User is validated
324 325
                name_identifier = tree.find('.//' + SAML_1_0_ASSERTION_NS + 'NameIdentifier')
                if name_identifier is not None:
326
                    user = self.u(name_identifier.text, charset)
Valentin Samir's avatar
Valentin Samir committed
327 328 329
                attrs = tree.findall('.//' + SAML_1_0_ASSERTION_NS + 'Attribute')
                for at in attrs:
                    if self.username_attribute in list(at.attrib.values()):
330
                        user = self.u(
331 332 333 334
                            at.find(SAML_1_0_ASSERTION_NS + 'AttributeValue').text,
                            charset
                        )
                        attributes[u'uid'] = user
Valentin Samir's avatar
Valentin Samir committed
335 336

                    values = at.findall(SAML_1_0_ASSERTION_NS + 'AttributeValue')
337
                    key = self.u(at.attrib['AttributeName'], charset)
Valentin Samir's avatar
Valentin Samir committed
338 339 340
                    if len(values) > 1:
                        values_array = []
                        for v in values:
341
                            values_array.append(self.u(v.text, charset))
342
                            attributes[key] = values_array
Valentin Samir's avatar
Valentin Samir committed
343
                    else:
344
                        attributes[key] = self.u(values[0].text, charset)
Valentin Samir's avatar
Valentin Samir committed
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
            return user, attributes, None
        finally:
            page.close()

    def fetch_saml_validation(self, ticket):
        # We do the SAML validation
        headers = {
            'soapaction': 'http://www.oasis-open.org/committees/security',
            'cache-control': 'no-cache',
            'pragma': 'no-cache',
            'accept': 'text/xml',
            'connection': 'keep-alive',
            'content-type': 'text/xml; charset=utf-8',
        }
        params = [('TARGET', self.service_url)]
        saml_validate_url = urllib_parse.urljoin(
            self.server_url, 'samlValidate',
        )
        request = Request(
            saml_validate_url + '?' + urllib_parse.urlencode(params),
            self.get_saml_assertion(ticket),
            headers,
        )
        return urllib_request.urlopen(request)

    @classmethod
    def get_saml_assertion(cls, ticket):
        """
        http://www.jasig.org/cas/protocol#samlvalidate-cas-3.0

        SAML request values:

        RequestID [REQUIRED]:
            unique identifier for the request
        IssueInstant [REQUIRED]:
            timestamp of the request
        samlp:AssertionArtifact [REQUIRED]:
            the valid CAS Service Ticket obtained as a response parameter at login.
        """
        # RequestID [REQUIRED] - unique identifier for the request
        request_id = uuid4()

        # e.g. 2014-06-02T09:21:03.071189
        timestamp = datetime.datetime.now().isoformat()

        return SAML_ASSERTION_TEMPLATE.format(
            request_id=request_id,
            timestamp=timestamp,
            ticket=ticket,
        ).encode('utf8')