| 1 |
# Copyright (C) 2014, Ming Chen |
| 2 |
# |
| 3 |
# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 4 |
# of this software and associated documentation files (the "Software"), to deal |
| 5 |
# in the Software without restriction, including without limitation the rights |
| 6 |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 7 |
# copies of the Software, and to permit persons to whom the Software is furnished |
| 8 |
# to do so, subject to the following conditions: |
| 9 |
# |
| 10 |
# The above copyright notice and this permission notice shall be included in all |
| 11 |
# copies or substantial portions of the Software. |
| 12 |
# |
| 13 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 14 |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 15 |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 16 |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 17 |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 18 |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS |
| 19 |
# IN THE SOFTWARE. |
| 20 |
|
| 21 |
# This file is originated from https://github.com/python-cas/python-cas |
| 22 |
# at commit ec1f2d4779625229398547b9234d0e9e874a2c9a |
| 23 |
# some modifications have been made to be unicode coherent between python2 and python2 |
| 24 |
|
| 25 |
import urllib.parse as urllib_parse |
| 26 |
import urllib.request as urllib_request |
| 27 |
from urllib.request import Request |
| 28 |
from uuid import uuid4 |
| 29 |
import datetime |
| 30 |
|
| 31 |
|
| 32 |
class CASError(ValueError): |
| 33 |
pass |
| 34 |
|
| 35 |
|
| 36 |
class ReturnUnicode(object): |
| 37 |
@staticmethod |
| 38 |
def u(string, charset): |
| 39 |
if not isinstance(string, str): |
| 40 |
return string.decode(charset) |
| 41 |
else: |
| 42 |
return string |
| 43 |
|
| 44 |
|
| 45 |
class SingleLogoutMixin(object): |
| 46 |
@classmethod |
| 47 |
def get_saml_slos(cls, logout_request): |
| 48 |
"""returns saml logout ticket info""" |
| 49 |
from lxml import etree |
| 50 |
try: |
| 51 |
root = etree.fromstring(logout_request) |
| 52 |
return root.xpath( |
| 53 |
"//samlp:SessionIndex", |
| 54 |
namespaces={'samlp': "urn:oasis:names:tc:SAML:2.0:protocol"}) |
| 55 |
except etree.XMLSyntaxError: |
| 56 |
pass |
| 57 |
|
| 58 |
|
| 59 |
class CASClient(object): |
| 60 |
def __new__(self, *args, **kwargs): |
| 61 |
version = kwargs.pop('version') |
| 62 |
if version in (1, '1'): |
| 63 |
return CASClientV1(*args, **kwargs) |
| 64 |
elif version in (2, '2'): |
| 65 |
return CASClientV2(*args, **kwargs) |
| 66 |
elif version in (3, '3'): |
| 67 |
return CASClientV3(*args, **kwargs) |
| 68 |
elif version == 'CAS_2_SAML_1_0': |
| 69 |
return CASClientWithSAMLV1(*args, **kwargs) |
| 70 |
raise ValueError('Unsupported CAS_VERSION %r' % version) |
| 71 |
|
| 72 |
|
| 73 |
class CASClientBase(object): |
| 74 |
|
| 75 |
logout_redirect_param_name = 'service' |
| 76 |
|
| 77 |
def __init__(self, service_url=None, server_url=None, |
| 78 |
extra_login_params=None, renew=False, |
| 79 |
username_attribute=None): |
| 80 |
|
| 81 |
self.service_url = service_url |
| 82 |
self.server_url = server_url |
| 83 |
self.extra_login_params = extra_login_params or {} |
| 84 |
self.renew = renew |
| 85 |
self.username_attribute = username_attribute |
| 86 |
pass |
| 87 |
|
| 88 |
def verify_ticket(self, ticket): |
| 89 |
"""must return a triple""" |
| 90 |
raise NotImplementedError() |
| 91 |
|
| 92 |
def get_login_url(self): |
| 93 |
"""Generates CAS login URL""" |
| 94 |
params = {'service': self.service_url} |
| 95 |
if self.renew: |
| 96 |
params.update({'renew': 'true'}) |
| 97 |
|
| 98 |
params.update(self.extra_login_params) |
| 99 |
url = urllib_parse.urljoin(self.server_url, 'login') |
| 100 |
query = urllib_parse.urlencode(params) |
| 101 |
return url + '?' + query |
| 102 |
|
| 103 |
def get_logout_url(self, redirect_url=None): |
| 104 |
"""Generates CAS logout URL""" |
| 105 |
url = urllib_parse.urljoin(self.server_url, 'logout') |
| 106 |
if redirect_url: |
| 107 |
params = {self.logout_redirect_param_name: redirect_url} |
| 108 |
url += '?' + urllib_parse.urlencode(params) |
| 109 |
return url |
| 110 |
|
| 111 |
def get_proxy_url(self, pgt): |
| 112 |
"""Returns proxy url, given the proxy granting ticket""" |
| 113 |
params = urllib_parse.urlencode({'pgt': pgt, 'targetService': self.service_url}) |
| 114 |
return "%s/proxy?%s" % (self.server_url, params) |
| 115 |
|
| 116 |
def get_proxy_ticket(self, pgt): |
| 117 |
"""Returns proxy ticket given the proxy granting ticket""" |
| 118 |
response = urllib_request.urlopen(self.get_proxy_url(pgt)) |
| 119 |
if response.code == 200: |
| 120 |
from lxml import etree |
| 121 |
root = etree.fromstring(response.read()) |
| 122 |
tickets = root.xpath( |
| 123 |
"//cas:proxyTicket", |
| 124 |
namespaces={"cas": "http://www.yale.edu/tp/cas"} |
| 125 |
) |
| 126 |
if len(tickets) == 1: |
| 127 |
return tickets[0].text |
| 128 |
errors = root.xpath( |
| 129 |
"//cas:authenticationFailure", |
| 130 |
namespaces={"cas": "http://www.yale.edu/tp/cas"} |
| 131 |
) |
| 132 |
if len(errors) == 1: |
| 133 |
raise CASError(errors[0].attrib['code'], errors[0].text) |
| 134 |
raise CASError("Bad http code %s" % response.code) |
| 135 |
|
| 136 |
@staticmethod |
| 137 |
def get_page_charset(page, default="utf-8"): |
| 138 |
content_type = page.info().get('Content-type') |
| 139 |
if content_type and "charset=" in content_type: |
| 140 |
return content_type.split("charset=")[-1] |
| 141 |
else: |
| 142 |
return default |
| 143 |
|
| 144 |
|
| 145 |
class CASClientV1(CASClientBase, ReturnUnicode): |
| 146 |
"""CAS Client Version 1""" |
| 147 |
|
| 148 |
logout_redirect_param_name = 'url' |
| 149 |
|
| 150 |
def verify_ticket(self, ticket): |
| 151 |
"""Verifies CAS 1.0 authentication ticket. |
| 152 |
|
| 153 |
Returns username on success and None on failure. |
| 154 |
""" |
| 155 |
params = [('ticket', ticket), ('service', self.service_url)] |
| 156 |
if self.renew: |
| 157 |
params.append(('renew', 'true')) |
| 158 |
url = (urllib_parse.urljoin(self.server_url, 'validate') + '?' + |
| 159 |
urllib_parse.urlencode(params)) |
| 160 |
page = urllib_request.urlopen(url) |
| 161 |
try: |
| 162 |
verified = page.readline().strip() |
| 163 |
if verified == b'yes': |
| 164 |
charset = self.get_page_charset(page, default="ascii") |
| 165 |
user = self.u(page.readline().strip(), charset) |
| 166 |
return user, None, None |
| 167 |
else: |
| 168 |
return None, None, None |
| 169 |
finally: |
| 170 |
page.close() |
| 171 |
|
| 172 |
|
| 173 |
class CASClientV2(CASClientBase, ReturnUnicode): |
| 174 |
"""CAS Client Version 2""" |
| 175 |
|
| 176 |
url_suffix = 'serviceValidate' |
| 177 |
logout_redirect_param_name = 'url' |
| 178 |
|
| 179 |
def __init__(self, proxy_callback=None, *args, **kwargs): |
| 180 |
"""proxy_callback is for V2 and V3 so V3 is subclass of V2""" |
| 181 |
self.proxy_callback = proxy_callback |
| 182 |
super(CASClientV2, self).__init__(*args, **kwargs) |
| 183 |
|
| 184 |
def verify_ticket(self, ticket): |
| 185 |
"""Verifies CAS 2.0+/3.0+ XML-based authentication ticket and returns extended attributes""" |
| 186 |
(response, charset) = self.get_verification_response(ticket) |
| 187 |
return self.verify_response(response, charset) |
| 188 |
|
| 189 |
def get_verification_response(self, ticket): |
| 190 |
params = [('ticket', ticket), ('service', self.service_url)] |
| 191 |
if self.renew: |
| 192 |
params.append(('renew', 'true')) |
| 193 |
if self.proxy_callback: |
| 194 |
params.append(('pgtUrl', self.proxy_callback)) |
| 195 |
base_url = urllib_parse.urljoin(self.server_url, self.url_suffix) |
| 196 |
url = base_url + '?' + urllib_parse.urlencode(params) |
| 197 |
page = urllib_request.urlopen(url) |
| 198 |
try: |
| 199 |
charset = self.get_page_charset(page) |
| 200 |
return (page.read(), charset) |
| 201 |
finally: |
| 202 |
page.close() |
| 203 |
|
| 204 |
@classmethod |
| 205 |
def parse_attributes_xml_element(cls, element, charset): |
| 206 |
attributes = dict() |
| 207 |
for attribute in element: |
| 208 |
tag = cls.u(attribute.tag, charset).split(u"}").pop() |
| 209 |
if tag in attributes: |
| 210 |
if isinstance(attributes[tag], list): |
| 211 |
attributes[tag].append(cls.u(attribute.text, charset)) |
| 212 |
else: |
| 213 |
attributes[tag] = [attributes[tag]] |
| 214 |
attributes[tag].append(cls.u(attribute.text, charset)) |
| 215 |
else: |
| 216 |
if tag == u'attraStyle': |
| 217 |
pass |
| 218 |
else: |
| 219 |
attributes[tag] = cls.u(attribute.text, charset) |
| 220 |
return attributes |
| 221 |
|
| 222 |
@classmethod |
| 223 |
def verify_response(cls, response, charset): |
| 224 |
user, attributes, pgtiou = cls.parse_response_xml(response, charset) |
| 225 |
if len(attributes) == 0: |
| 226 |
attributes = None |
| 227 |
return user, attributes, pgtiou |
| 228 |
|
| 229 |
@classmethod |
| 230 |
def parse_response_xml(cls, response, charset): |
| 231 |
try: |
| 232 |
from xml.etree import ElementTree |
| 233 |
except ImportError: |
| 234 |
from elementtree import ElementTree |
| 235 |
|
| 236 |
user = None |
| 237 |
attributes = {} |
| 238 |
pgtiou = None |
| 239 |
|
| 240 |
tree = ElementTree.fromstring(response) |
| 241 |
if tree[0].tag.endswith('authenticationSuccess'): |
| 242 |
for element in tree[0]: |
| 243 |
if element.tag.endswith('user'): |
| 244 |
user = cls.u(element.text, charset) |
| 245 |
elif element.tag.endswith('proxyGrantingTicket'): |
| 246 |
pgtiou = cls.u(element.text, charset) |
| 247 |
elif element.tag.endswith('attributes'): |
| 248 |
attributes = cls.parse_attributes_xml_element(element, charset) |
| 249 |
return user, attributes, pgtiou |
| 250 |
|
| 251 |
|
| 252 |
class CASClientV3(CASClientV2, SingleLogoutMixin): |
| 253 |
"""CAS Client Version 3""" |
| 254 |
url_suffix = 'serviceValidate' |
| 255 |
logout_redirect_param_name = 'service' |
| 256 |
|
| 257 |
@classmethod |
| 258 |
def parse_attributes_xml_element(cls, element, charset): |
| 259 |
attributes = dict() |
| 260 |
for attribute in element: |
| 261 |
tag = cls.u(attribute.tag, charset).split(u"}").pop() |
| 262 |
if tag in attributes: |
| 263 |
if isinstance(attributes[tag], list): |
| 264 |
attributes[tag].append(cls.u(attribute.text, charset)) |
| 265 |
else: |
| 266 |
attributes[tag] = [attributes[tag]] |
| 267 |
attributes[tag].append(cls.u(attribute.text, charset)) |
| 268 |
else: |
| 269 |
attributes[tag] = cls.u(attribute.text, charset) |
| 270 |
return attributes |
| 271 |
|
| 272 |
@classmethod |
| 273 |
def verify_response(cls, response, charset): |
| 274 |
return cls.parse_response_xml(response, charset) |
| 275 |
|
| 276 |
|
| 277 |
SAML_1_0_NS = 'urn:oasis:names:tc:SAML:1.0:' |
| 278 |
SAML_1_0_PROTOCOL_NS = '{' + SAML_1_0_NS + 'protocol' + '}' |
| 279 |
SAML_1_0_ASSERTION_NS = '{' + SAML_1_0_NS + 'assertion' + '}' |
| 280 |
SAML_ASSERTION_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?> |
| 281 |
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> |
| 282 |
<SOAP-ENV:Header/> |
| 283 |
<SOAP-ENV:Body> |
| 284 |
<samlp:Request xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol" |
| 285 |
MajorVersion="1" |
| 286 |
MinorVersion="1" |
| 287 |
RequestID="{request_id}" |
| 288 |
IssueInstant="{timestamp}"> |
| 289 |
<samlp:AssertionArtifact>{ticket}</samlp:AssertionArtifact></samlp:Request> |
| 290 |
</SOAP-ENV:Body> |
| 291 |
</SOAP-ENV:Envelope>""" |
| 292 |
|
| 293 |
|
| 294 |
class CASClientWithSAMLV1(CASClientV2, SingleLogoutMixin): |
| 295 |
"""CASClient 3.0+ with SAML""" |
| 296 |
|
| 297 |
def verify_ticket(self, ticket, **kwargs): |
| 298 |
"""Verifies CAS 3.0+ XML-based authentication ticket and returns extended attributes. |
| 299 |
|
| 300 |
@date: 2011-11-30 |
| 301 |
@author: Carlos Gonzalez Vila <[email protected]> |
| 302 |
|
| 303 |
Returns username and attributes on success and None,None on failure. |
| 304 |
""" |
| 305 |
|
| 306 |
try: |
| 307 |
from xml.etree import ElementTree |
| 308 |
except ImportError: |
| 309 |
from elementtree import ElementTree |
| 310 |
|
| 311 |
page = self.fetch_saml_validation(ticket) |
| 312 |
charset = self.get_page_charset(page) |
| 313 |
|
| 314 |
try: |
| 315 |
user = None |
| 316 |
attributes = {} |
| 317 |
response = page.read() |
| 318 |
tree = ElementTree.fromstring(response) |
| 319 |
# Find the authentication status |
| 320 |
success = tree.find('.//' + SAML_1_0_PROTOCOL_NS + 'StatusCode') |
| 321 |
if success is not None and success.attrib['Value'].endswith(':Success'): |
| 322 |
# User is validated |
| 323 |
name_identifier = tree.find('.//' + SAML_1_0_ASSERTION_NS + 'NameIdentifier') |
| 324 |
if name_identifier is not None: |
| 325 |
user = self.u(name_identifier.text, charset) |
| 326 |
attrs = tree.findall('.//' + SAML_1_0_ASSERTION_NS + 'Attribute') |
| 327 |
for at in attrs: |
| 328 |
if self.username_attribute in list(at.attrib.values()): |
| 329 |
user = self.u( |
| 330 |
at.find(SAML_1_0_ASSERTION_NS + 'AttributeValue').text, |
| 331 |
charset |
| 332 |
) |
| 333 |
attributes[u'uid'] = user |
| 334 |
|
| 335 |
values = at.findall(SAML_1_0_ASSERTION_NS + 'AttributeValue') |
| 336 |
key = self.u(at.attrib['AttributeName'], charset) |
| 337 |
if len(values) > 1: |
| 338 |
values_array = [] |
| 339 |
for v in values: |
| 340 |
values_array.append(self.u(v.text, charset)) |
| 341 |
attributes[key] = values_array |
| 342 |
else: |
| 343 |
attributes[key] = self.u(values[0].text, charset) |
| 344 |
return user, attributes, None |
| 345 |
finally: |
| 346 |
page.close() |
| 347 |
|
| 348 |
def fetch_saml_validation(self, ticket): |
| 349 |
# We do the SAML validation |
| 350 |
headers = { |
| 351 |
'soapaction': 'http://www.oasis-open.org/committees/security', |
| 352 |
'cache-control': 'no-cache', |
| 353 |
'pragma': 'no-cache', |
| 354 |
'accept': 'text/xml', |
| 355 |
'connection': 'keep-alive', |
| 356 |
'content-type': 'text/xml; charset=utf-8', |
| 357 |
} |
| 358 |
params = [('TARGET', self.service_url)] |
| 359 |
saml_validate_url = urllib_parse.urljoin( |
| 360 |
self.server_url, 'samlValidate', |
| 361 |
) |
| 362 |
request = Request( |
| 363 |
saml_validate_url + '?' + urllib_parse.urlencode(params), |
| 364 |
self.get_saml_assertion(ticket), |
| 365 |
headers, |
| 366 |
) |
| 367 |
return urllib_request.urlopen(request) |
| 368 |
|
| 369 |
@classmethod |
| 370 |
def get_saml_assertion(cls, ticket): |
| 371 |
""" |
| 372 |
https://apereo.github.io/cas/7.0.x/protocol/CAS-Protocol-Specification.html#42-samlvalidate-cas-30 |
| 373 |
|
| 374 |
SAML request values: |
| 375 |
|
| 376 |
RequestID [REQUIRED]: |
| 377 |
unique identifier for the request |
| 378 |
IssueInstant [REQUIRED]: |
| 379 |
timestamp of the request |
| 380 |
samlp:AssertionArtifact [REQUIRED]: |
| 381 |
the valid CAS Service Ticket obtained as a response parameter at login. |
| 382 |
""" |
| 383 |
# RequestID [REQUIRED] - unique identifier for the request |
| 384 |
request_id = uuid4() |
| 385 |
|
| 386 |
# e.g. 2014-06-02T09:21:03.071189 |
| 387 |
timestamp = datetime.datetime.now().isoformat() |
| 388 |
|
| 389 |
return SAML_ASSERTION_TEMPLATE.format( |
| 390 |
request_id=request_id, |
| 391 |
timestamp=timestamp, |
| 392 |
ticket=ticket, |
| 393 |
).encode('utf8') |