Debian Codegraph @

keystoneclient/contrib/auth/v3/saml2.py

raw symbols SCIP
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import datetime
14 import urllib.parse
15 import uuid
16
17 from lxml import etree # nosec(cjschaef): used to create xml, not parse it
18 from oslo_config import cfg
19
20 from keystoneclient import access
21 from keystoneclient.auth.identity import v3
22 from keystoneclient import exceptions
23 from keystoneclient.i18n import _
24
25
26 class _BaseSAMLPlugin(v3.AuthConstructor):
27
28 HTTP_MOVED_TEMPORARILY = 302
29 HTTP_SEE_OTHER = 303
30
31 PROTOCOL = 'saml2'
32
33 @staticmethod
34 def _first(_list):
35 if len(_list) != 1:
36 raise IndexError(_("Only single element list is acceptable"))
37 return _list[0]
38
39 @staticmethod
40 def str_to_xml(content, msg=None, include_exc=True):
41 try:
42 return etree.XML(content)
43 except etree.XMLSyntaxError as e:
44 if not msg:
45 msg = str(e)
46 else:
47 msg = msg % e if include_exc else msg
48 raise exceptions.AuthorizationFailure(msg)
49
50 @staticmethod
51 def xml_to_str(content, **kwargs):
52 return etree.tostring(content, **kwargs)
53
54 @property
55 def token_url(self):
56 """Return full URL where authorization data is sent."""
57 values = {
58 'host': self.auth_url.rstrip('/'),
59 'identity_provider': self.identity_provider,
60 'protocol': self.PROTOCOL
61 }
62 url = ("%(host)s/OS-FEDERATION/identity_providers/"
63 "%(identity_provider)s/protocols/%(protocol)s/auth")
64 url = url % values
65
66 return url
67
68 @classmethod
69 def get_options(cls):
70 options = super(_BaseSAMLPlugin, cls).get_options()
71 options.extend([
72 cfg.StrOpt('identity-provider', help="Identity Provider's name"),
73 cfg.StrOpt('identity-provider-url',
74 help="Identity Provider's URL"),
75 cfg.StrOpt('username', dest='username', help='Username',
76 deprecated_name='user-name'),
77 cfg.StrOpt('password', secret=True, help='Password')
78 ])
79 return options
80
81
82 class Saml2UnscopedTokenAuthMethod(v3.AuthMethod):
83 _method_parameters = []
84
85 def get_auth_data(self, session, auth, headers, **kwargs):
86 raise exceptions.MethodNotImplemented(_('This method should never '
87 'be called'))
88
89
90 class Saml2UnscopedToken(_BaseSAMLPlugin):
91 r"""Implement authentication plugin for SAML2 protocol.
92
93 ECP stands for `Enhanced Client or Proxy` and is a SAML2 extension
94 for federated authentication where a transportation layer consists of
95 HTTP protocol and XML SOAP messages.
96
97 `Read for more information
98 <https://wiki.shibboleth.net/confluence/display/SHIB2/ECP>`_ on ECP.
99
100 Reference the `SAML2 ECP specification <https://www.oasis-open.org/\
101 committees/download.php/49979/saml-ecp-v2.0-wd09.pdf>`_.
102
103 Currently only HTTPBasicAuth mechanism is available for the IdP
104 authenication.
105
106 :param auth_url: URL of the Identity Service
107 :type auth_url: string
108
109 :param identity_provider: name of the Identity Provider the client will
110 authenticate against. This parameter will be used
111 to build a dynamic URL used to obtain unscoped
112 OpenStack token.
113 :type identity_provider: string
114
115 :param identity_provider_url: An Identity Provider URL, where the SAML2
116 authn request will be sent.
117 :type identity_provider_url: string
118
119 :param username: User's login
120 :type username: string
121
122 :param password: User's password
123 :type password: string
124
125 """
126
127 _auth_method_class = Saml2UnscopedTokenAuthMethod
128
129 SAML2_HEADER_INDEX = 0
130 ECP_SP_EMPTY_REQUEST_HEADERS = {
131 'Accept': 'text/html, application/vnd.paos+xml',
132 'PAOS': ('ver="urn:liberty:paos:2003-08";"urn:oasis:names:tc:'
133 'SAML:2.0:profiles:SSO:ecp"')
134 }
135
136 ECP_SP_SAML2_REQUEST_HEADERS = {
137 'Content-Type': 'application/vnd.paos+xml'
138 }
139
140 ECP_SAML2_NAMESPACES = {
141 'ecp': 'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp',
142 'S': 'http://schemas.xmlsoap.org/soap/envelope/',
143 'paos': 'urn:liberty:paos:2003-08'
144 }
145
146 ECP_RELAY_STATE = '//ecp:RelayState'
147
148 ECP_SERVICE_PROVIDER_CONSUMER_URL = ('/S:Envelope/S:Header/paos:Request/'
149 '@responseConsumerURL')
150
151 ECP_IDP_CONSUMER_URL = ('/S:Envelope/S:Header/ecp:Response/'
152 '@AssertionConsumerServiceURL')
153
154 SOAP_FAULT = """
155 <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
156 <S:Body>
157 <S:Fault>
158 <faultcode>S:Server</faultcode>
159 <faultstring>responseConsumerURL from SP and
160 assertionConsumerServiceURL from IdP do not match
161 </faultstring>
162 </S:Fault>
163 </S:Body>
164 </S:Envelope>
165 """
166
167 def __init__(self, auth_url,
168 identity_provider,
169 identity_provider_url,
170 username, password,
171 **kwargs):
172 super(Saml2UnscopedToken, self).__init__(auth_url=auth_url, **kwargs)
173 self.identity_provider = identity_provider
174 self.identity_provider_url = identity_provider_url
175 self._username, self._password = username, password
176
177 @property
178 def username(self):
179 # Override to remove deprecation.
180 return self._username
181
182 @username.setter
183 def username(self, value):
184 # Override to remove deprecation.
185 self._username = value
186
187 @property
188 def password(self):
189 # Override to remove deprecation.
190 return self._password
191
192 @password.setter
193 def password(self, value):
194 # Override to remove deprecation.
195 self._password = value
196
197 def _handle_http_ecp_redirect(self, session, response, method, **kwargs):
198 if response.status_code not in (self.HTTP_MOVED_TEMPORARILY,
199 self.HTTP_SEE_OTHER):
200 return response
201
202 location = response.headers['location']
203 return session.request(location, method, authenticated=False,
204 **kwargs)
205
206 def _prepare_idp_saml2_request(self, saml2_authn_request):
207 header = saml2_authn_request[self.SAML2_HEADER_INDEX]
208 saml2_authn_request.remove(header)
209
210 def _check_consumer_urls(self, session, sp_response_consumer_url,
211 idp_sp_response_consumer_url):
212 """Check if consumer URLs issued by SP and IdP are equal.
213
214 In the initial SAML2 authn Request issued by a Service Provider
215 there is a url called ``consumer url``. A trusted Identity Provider
216 should issue identical url. If the URLs are not equal the federated
217 authn process should be interrupted and the user should be warned.
218
219 :param session: session object to send out HTTP requests.
220 :type session: keystoneclient.session.Session
221 :param sp_response_consumer_url: consumer URL issued by a SP
222 :type sp_response_consumer_url: string
223 :param idp_sp_response_consumer_url: consumer URL issued by an IdP
224 :type idp_sp_response_consumer_url: string
225
226 """
227 if sp_response_consumer_url != idp_sp_response_consumer_url:
228 # send fault message to the SP, discard the response
229 session.post(sp_response_consumer_url, data=self.SOAP_FAULT,
230 headers=self.ECP_SP_SAML2_REQUEST_HEADERS,
231 authenticated=False)
232
233 # prepare error message and raise an exception.
234 msg = _("Consumer URLs from Service Provider %(service_provider)s "
235 "%(sp_consumer_url)s and Identity Provider "
236 "%(identity_provider)s %(idp_consumer_url)s are not equal")
237 msg = msg % {
238 'service_provider': self.token_url,
239 'sp_consumer_url': sp_response_consumer_url,
240 'identity_provider': self.identity_provider,
241 'idp_consumer_url': idp_sp_response_consumer_url
242 }
243
244 raise exceptions.ValidationError(msg)
245
246 def _send_service_provider_request(self, session):
247 """Initial HTTP GET request to the SAML2 protected endpoint.
248
249 It's crucial to include HTTP headers indicating that the client is
250 willing to take advantage of the ECP SAML2 extension and receive data
251 as the SOAP.
252 Unlike standard authentication methods in the OpenStack Identity,
253 the client accesses::
254 ``/v3/OS-FEDERATION/identity_providers/{identity_providers}/
255 protocols/{protocol}/auth``
256
257 After a successful HTTP call the HTTP response should include SAML2
258 authn request in the XML format.
259
260 If a HTTP response contains ``X-Subject-Token`` in the headers and
261 the response body is a valid JSON assume the user was already
262 authenticated and Keystone returned a valid unscoped token.
263 Return True indicating the user was already authenticated.
264
265 :param session: a session object to send out HTTP requests.
266 :type session: keystoneclient.session.Session
267
268 """
269 sp_response = session.get(self.token_url,
270 headers=self.ECP_SP_EMPTY_REQUEST_HEADERS,
271 authenticated=False)
272
273 if 'X-Subject-Token' in sp_response.headers:
274 self.authenticated_response = sp_response
275 return True
276
277 try:
278 self.saml2_authn_request = etree.XML(sp_response.content)
279 except etree.XMLSyntaxError as e:
280 msg = _("SAML2: Error parsing XML returned "
281 "from Service Provider, reason: %s") % e
282 raise exceptions.AuthorizationFailure(msg)
283
284 relay_state = self.saml2_authn_request.xpath(
285 self.ECP_RELAY_STATE, namespaces=self.ECP_SAML2_NAMESPACES)
286 self.relay_state = self._first(relay_state)
287
288 sp_response_consumer_url = self.saml2_authn_request.xpath(
289 self.ECP_SERVICE_PROVIDER_CONSUMER_URL,
290 namespaces=self.ECP_SAML2_NAMESPACES)
291 self.sp_response_consumer_url = self._first(sp_response_consumer_url)
292 return False
293
294 def _send_idp_saml2_authn_request(self, session):
295 """Present modified SAML2 authn assertion from the Service Provider."""
296 self._prepare_idp_saml2_request(self.saml2_authn_request)
297 idp_saml2_authn_request = self.saml2_authn_request
298
299 # Currently HTTPBasicAuth method is hardcoded into the plugin
300 idp_response = session.post(
301 self.identity_provider_url,
302 headers={'Content-type': 'text/xml'},
303 data=etree.tostring(idp_saml2_authn_request),
304 requests_auth=(self.username, self.password),
305 authenticated=False, log=False)
306
307 try:
308 self.saml2_idp_authn_response = etree.XML(idp_response.content)
309 except etree.XMLSyntaxError as e:
310 msg = _("SAML2: Error parsing XML returned "
311 "from Identity Provider, reason: %s") % e
312 raise exceptions.AuthorizationFailure(msg)
313
314 idp_response_consumer_url = self.saml2_idp_authn_response.xpath(
315 self.ECP_IDP_CONSUMER_URL,
316 namespaces=self.ECP_SAML2_NAMESPACES)
317
318 self.idp_response_consumer_url = self._first(idp_response_consumer_url)
319
320 self._check_consumer_urls(session, self.idp_response_consumer_url,
321 self.sp_response_consumer_url)
322
323 def _send_service_provider_saml2_authn_response(self, session):
324 """Present SAML2 assertion to the Service Provider.
325
326 The assertion is issued by a trusted Identity Provider for the
327 authenticated user. This function directs the HTTP request to SP
328 managed URL, for instance: ``https://<host>:<port>/Shibboleth.sso/
329 SAML2/ECP``.
330 Upon success there's a session created and access to the protected
331 resource is granted. Many implementations of the SP return HTTP 302/303
332 status code pointing to the protected URL (``https://<host>:<port>/v3/
333 OS-FEDERATION/identity_providers/{identity_provider}/protocols/
334 {protocol_id}/auth`` in this case). Saml2 plugin should point to that
335 URL again, with HTTP GET method, expecting an unscoped token.
336
337 :param session: a session object to send out HTTP requests.
338
339 """
340 self.saml2_idp_authn_response[0][0] = self.relay_state
341
342 response = session.post(
343 self.idp_response_consumer_url,
344 headers=self.ECP_SP_SAML2_REQUEST_HEADERS,
345 data=etree.tostring(self.saml2_idp_authn_response),
346 authenticated=False, redirect=False)
347
348 # Don't follow HTTP specs - after the HTTP 302/303 response don't
349 # repeat the call directed to the Location URL. In this case, this is
350 # an indication that saml2 session is now active and protected resource
351 # can be accessed.
352 response = self._handle_http_ecp_redirect(
353 session, response, method='GET',
354 headers=self.ECP_SP_SAML2_REQUEST_HEADERS)
355
356 self.authenticated_response = response
357
358 def _get_unscoped_token(self, session):
359 """Get unscoped OpenStack token after federated authentication.
360
361 This is a multi-step process including multiple HTTP requests.
362
363 The federated authentication consists of::
364 * HTTP GET request to the Identity Service (acting as a Service
365 Provider). Client utilizes URL::
366 ``/v3/OS-FEDERATION/identity_providers/{identity_provider}/
367 protocols/saml2/auth``.
368 It's crucial to include HTTP headers indicating we are expecting
369 SOAP message in return.
370 Service Provider should respond with such SOAP message.
371 This step is handed by a method
372 ``Saml2UnscopedToken_send_service_provider_request()``
373
374 * HTTP POST request to the external Identity Provider service with
375 ECP extension enabled. The content sent is a header removed SOAP
376 message returned from the Service Provider. It's also worth noting
377 that ECP extension to the SAML2 doesn't define authentication method.
378 The most popular is HttpBasicAuth with just user and password.
379 Other possibilities could be X509 certificates or Kerberos.
380 Upon successful authentication the user should receive a SAML2
381 assertion.
382 This step is handed by a method
383 ``Saml2UnscopedToken_send_idp_saml2_authn_request(session)``
384
385 * HTTP POST request again to the Service Provider. The body of the
386 request includes SAML2 assertion issued by a trusted Identity
387 Provider. The request should be sent to the Service Provider
388 consumer url specified in the SAML2 assertion.
389 Providing the authentication was successful and both Service Provider
390 and Identity Providers are trusted to each other, the Service
391 Provider will issue an unscoped token with a list of groups the
392 federated user is a member of.
393 This step is handed by a method
394 ``Saml2UnscopedToken_send_service_provider_saml2_authn_response()``
395
396 Unscoped token example::
397
398 {
399 "token": {
400 "methods": [
401 "saml2"
402 ],
403 "user": {
404 "id": "username%40example.com",
405 "name": "[email protected]",
406 "OS-FEDERATION": {
407 "identity_provider": "ACME",
408 "protocol": "saml2",
409 "groups": [
410 {"id": "abc123"},
411 {"id": "bcd234"}
412 ]
413 }
414 }
415 }
416 }
417
418
419 :param session : a session object to send out HTTP requests.
420 :type session: keystoneclient.session.Session
421
422 :returns: (token, token_json)
423
424 """
425 saml_authenticated = self._send_service_provider_request(session)
426 if not saml_authenticated:
427 self._send_idp_saml2_authn_request(session)
428 self._send_service_provider_saml2_authn_response(session)
429 return (self.authenticated_response.headers['X-Subject-Token'],
430 self.authenticated_response.json()['token'])
431
432 def get_auth_ref(self, session, **kwargs):
433 """Authenticate via SAML2 protocol and retrieve unscoped token.
434
435 This is a multi-step process where a client does federated authn
436 receives an unscoped token.
437
438 Federated authentication utilizing SAML2 Enhanced Client or Proxy
439 extension. See ``Saml2UnscopedToken_get_unscoped_token()``
440 for more information on that step.
441 Upon successful authentication and assertion mapping an
442 unscoped token is returned and stored within the plugin object for
443 further use.
444
445 :param session : a session object to send out HTTP requests.
446 :type session: keystoneclient.session.Session
447
448 :return: an object with scoped token's id and unscoped token json
449 included.
450 :rtype: :py:class:`keystoneclient.access.AccessInfoV3`
451
452 """
453 token, token_json = self._get_unscoped_token(session)
454 return access.AccessInfoV3(token,
455 **token_json)
456
457
458 class ADFSUnscopedToken(_BaseSAMLPlugin):
459 """Authentication plugin for Microsoft ADFS2.0 IdPs.
460
461 :param auth_url: URL of the Identity Service
462 :type auth_url: string
463
464 :param identity_provider: name of the Identity Provider the client will
465 authenticate against. This parameter will be used
466 to build a dynamic URL used to obtain unscoped
467 OpenStack token.
468 :type identity_provider: string
469
470 :param identity_provider_url: An Identity Provider URL, where the SAML2
471 authentication request will be sent.
472 :type identity_provider_url: string
473
474 :param service_provider_endpoint: Endpoint where an assertion is being
475 sent, for instance: ``https://host.domain/Shibboleth.sso/ADFS``
476 :type service_provider_endpoint: string
477
478 :param username: User's login
479 :type username: string
480
481 :param password: User's password
482 :type password: string
483
484 """
485
486 _auth_method_class = Saml2UnscopedTokenAuthMethod
487
488 DEFAULT_ADFS_TOKEN_EXPIRATION = 120
489
490 HEADER_SOAP = {"Content-Type": "application/soap+xml; charset=utf-8"}
491 HEADER_X_FORM = {"Content-Type": "application/x-www-form-urlencoded"}
492
493 NAMESPACES = {
494 's': 'http://www.w3.org/2003/05/soap-envelope',
495 'a': 'http://www.w3.org/2005/08/addressing',
496 'u': ('http://docs.oasis-open.org/wss/2004/01/oasis-200401-'
497 'wss-wssecurity-utility-1.0.xsd')
498 }
499
500 ADFS_TOKEN_NAMESPACES = {
501 's': 'http://www.w3.org/2003/05/soap-envelope',
502 't': 'http://docs.oasis-open.org/ws-sx/ws-trust/200512'
503 }
504 ADFS_ASSERTION_XPATH = ('/s:Envelope/s:Body'
505 '/t:RequestSecurityTokenResponseCollection'
506 '/t:RequestSecurityTokenResponse')
507
508 def __init__(self, auth_url, identity_provider, identity_provider_url,
509 service_provider_endpoint, username, password, **kwargs):
510 super(ADFSUnscopedToken, self).__init__(auth_url=auth_url, **kwargs)
511 self.identity_provider = identity_provider
512 self.identity_provider_url = identity_provider_url
513 self.service_provider_endpoint = service_provider_endpoint
514 self._username, self._password = username, password
515
516 @property
517 def username(self):
518 # Override to remove deprecation.
519 return self._username
520
521 @username.setter
522 def username(self, value):
523 # Override to remove deprecation.
524 self._username = value
525
526 @property
527 def password(self):
528 # Override to remove deprecation.
529 return self._password
530
531 @password.setter
532 def password(self, value):
533 # Override to remove deprecation.
534 self._password = value
535
536 @classmethod
537 def get_options(cls):
538 options = super(ADFSUnscopedToken, cls).get_options()
539
540 options.extend([
541 cfg.StrOpt('service-provider-endpoint',
542 help="Service Provider's Endpoint")
543 ])
544 return options
545
546 def _cookies(self, session):
547 """Check if cookie jar is not empty.
548
549 keystoneclient.session.Session object doesn't have a cookies attribute.
550 We should then try fetching cookies from the underlying
551 requests.Session object. If that fails too, there is something wrong
552 and let Python raise the AttributeError.
553
554 :param session
555 :returns: True if cookie jar is nonempty, False otherwise
556 :raises AttributeError: in case cookies are not find anywhere
557
558 """
559 try:
560 return bool(session.cookies)
561 except AttributeError: # nosec(cjschaef): fetch cookies from
562 # underylying requests.Session object, or fail trying
563 pass
564
565 return bool(session.session.cookies)
566
567 def _token_dates(self, fmt='%Y-%m-%dT%H:%M:%S.%fZ'):
568 """Calculate created and expires datetime objects.
569
570 The method is going to be used for building ADFS Request Security
571 Token message. Time interval between ``created`` and ``expires``
572 dates is now static and equals to 120 seconds. ADFS security tokens
573 should not be live too long, as currently ``keystoneclient``
574 doesn't have mechanisms for reusing such tokens (every time ADFS authn
575 method is called, keystoneclient will login with the ADFS instance).
576
577 :param fmt: Datetime format for specifying string format of a date.
578 It should not be changed if the method is going to be used
579 for building the ADFS security token request.
580 :type fmt: string
581
582 """
583 date_created = datetime.datetime.utcnow()
584 date_expires = date_created + datetime.timedelta(
585 seconds=self.DEFAULT_ADFS_TOKEN_EXPIRATION)
586 return [_time.strftime(fmt) for _time in (date_created, date_expires)]
587
588 def _prepare_adfs_request(self):
589 """Build the ADFS Request Security Token SOAP message.
590
591 Some values like username or password are inserted in the request.
592
593 """
594 WSS_SECURITY_NAMESPACE = {
595 'o': ('http://docs.oasis-open.org/wss/2004/01/oasis-200401-'
596 'wss-wssecurity-secext-1.0.xsd')
597 }
598
599 TRUST_NAMESPACE = {
600 'trust': 'http://docs.oasis-open.org/ws-sx/ws-trust/200512'
601 }
602
603 WSP_NAMESPACE = {
604 'wsp': 'http://schemas.xmlsoap.org/ws/2004/09/policy'
605 }
606
607 WSA_NAMESPACE = {
608 'wsa': 'http://www.w3.org/2005/08/addressing'
609 }
610
611 root = etree.Element(
612 '{http://www.w3.org/2003/05/soap-envelope}Envelope',
613 nsmap=self.NAMESPACES)
614
615 header = etree.SubElement(
616 root, '{http://www.w3.org/2003/05/soap-envelope}Header')
617 action = etree.SubElement(
618 header, "{http://www.w3.org/2005/08/addressing}Action")
619 action.set(
620 "{http://www.w3.org/2003/05/soap-envelope}mustUnderstand", "1")
621 action.text = ('http://docs.oasis-open.org/ws-sx/ws-trust/200512'
622 '/RST/Issue')
623
624 messageID = etree.SubElement(
625 header, '{http://www.w3.org/2005/08/addressing}MessageID')
626 messageID.text = 'urn:uuid:' + uuid.uuid4().hex
627 replyID = etree.SubElement(
628 header, '{http://www.w3.org/2005/08/addressing}ReplyTo')
629 address = etree.SubElement(
630 replyID, '{http://www.w3.org/2005/08/addressing}Address')
631 address.text = 'http://www.w3.org/2005/08/addressing/anonymous'
632
633 to = etree.SubElement(
634 header, '{http://www.w3.org/2005/08/addressing}To')
635 to.set("{http://www.w3.org/2003/05/soap-envelope}mustUnderstand", "1")
636
637 security = etree.SubElement(
638 header, '{http://docs.oasis-open.org/wss/2004/01/oasis-200401-'
639 'wss-wssecurity-secext-1.0.xsd}Security',
640 nsmap=WSS_SECURITY_NAMESPACE)
641
642 security.set(
643 "{http://www.w3.org/2003/05/soap-envelope}mustUnderstand", "1")
644
645 timestamp = etree.SubElement(
646 security, ('{http://docs.oasis-open.org/wss/2004/01/oasis-200401-'
647 'wss-wssecurity-utility-1.0.xsd}Timestamp'))
648 timestamp.set(
649 ('{http://docs.oasis-open.org/wss/2004/01/oasis-200401-'
650 'wss-wssecurity-utility-1.0.xsd}Id'), '_0')
651
652 created = etree.SubElement(
653 timestamp, ('{http://docs.oasis-open.org/wss/2004/01/oasis-200401-'
654 'wss-wssecurity-utility-1.0.xsd}Created'))
655
656 expires = etree.SubElement(
657 timestamp, ('{http://docs.oasis-open.org/wss/2004/01/oasis-200401-'
658 'wss-wssecurity-utility-1.0.xsd}Expires'))
659
660 created.text, expires.text = self._token_dates()
661
662 usernametoken = etree.SubElement(
663 security, '{http://docs.oasis-open.org/wss/2004/01/oasis-200401-'
664 'wss-wssecurity-secext-1.0.xsd}UsernameToken')
665 usernametoken.set(
666 ('{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-'
667 'wssecurity-utility-1.0.xsd}u'), "uuid-%s-1" % uuid.uuid4().hex)
668
669 username = etree.SubElement(
670 usernametoken, ('{http://docs.oasis-open.org/wss/2004/01/oasis-'
671 '200401-wss-wssecurity-secext-1.0.xsd}Username'))
672 password = etree.SubElement(
673 usernametoken, ('{http://docs.oasis-open.org/wss/2004/01/oasis-'
674 '200401-wss-wssecurity-secext-1.0.xsd}Password'),
675 Type=('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-'
676 'username-token-profile-1.0#PasswordText'))
677
678 body = etree.SubElement(
679 root, "{http://www.w3.org/2003/05/soap-envelope}Body")
680
681 request_security_token = etree.SubElement(
682 body, ('{http://docs.oasis-open.org/ws-sx/ws-trust/200512}'
683 'RequestSecurityToken'), nsmap=TRUST_NAMESPACE)
684
685 applies_to = etree.SubElement(
686 request_security_token,
687 '{http://schemas.xmlsoap.org/ws/2004/09/policy}AppliesTo',
688 nsmap=WSP_NAMESPACE)
689
690 endpoint_reference = etree.SubElement(
691 applies_to,
692 '{http://www.w3.org/2005/08/addressing}EndpointReference',
693 nsmap=WSA_NAMESPACE)
694
695 wsa_address = etree.SubElement(
696 endpoint_reference,
697 '{http://www.w3.org/2005/08/addressing}Address')
698
699 keytype = etree.SubElement(
700 request_security_token,
701 '{http://docs.oasis-open.org/ws-sx/ws-trust/200512}KeyType')
702 keytype.text = ('http://docs.oasis-open.org/ws-sx/'
703 'ws-trust/200512/Bearer')
704
705 request_type = etree.SubElement(
706 request_security_token,
707 '{http://docs.oasis-open.org/ws-sx/ws-trust/200512}RequestType')
708 request_type.text = ('http://docs.oasis-open.org/ws-sx/'
709 'ws-trust/200512/Issue')
710 token_type = etree.SubElement(
711 request_security_token,
712 '{http://docs.oasis-open.org/ws-sx/ws-trust/200512}TokenType')
713 token_type.text = 'urn:oasis:names:tc:SAML:1.0:assertion'
714
715 # After constructing the request, let's plug in some values
716 username.text = self.username
717 password.text = self.password
718 to.text = self.identity_provider_url
719 wsa_address.text = self.service_provider_endpoint
720
721 self.prepared_request = root
722
723 def _get_adfs_security_token(self, session):
724 """Send ADFS Security token to the ADFS server.
725
726 Store the result in the instance attribute and raise an exception in
727 case the response is not valid XML data.
728
729 If a user cannot authenticate due to providing bad credentials, the
730 ADFS2.0 server will return a HTTP 500 response and a XML Fault message.
731 If ``exceptions.InternalServerError`` is caught, the method tries to
732 parse the XML response.
733 If parsing is unsuccessful, an ``exceptions.AuthorizationFailure`` is
734 raised with a reason from the XML fault. Otherwise an original
735 ``exceptions.InternalServerError`` is re-raised.
736
737 :param session : a session object to send out HTTP requests.
738 :type session: keystoneclient.session.Session
739
740 :raises keystoneclient.exceptions.AuthorizationFailure: when HTTP
741 response from the ADFS server is not a valid XML ADFS security
742 token.
743 :raises keystoneclient.exceptions.InternalServerError: If response
744 status code is HTTP 500 and the response XML cannot be
745 recognized.
746
747 """
748 def _get_failure(e):
749 xpath = '/s:Envelope/s:Body/s:Fault/s:Code/s:Subcode/s:Value'
750 content = e.response.content
751 try:
752 obj = self.str_to_xml(content).xpath(
753 xpath, namespaces=self.NAMESPACES)
754 obj = self._first(obj)
755 return obj.text
756 # NOTE(marek-denis): etree.Element.xpath() doesn't raise an
757 # exception, it just returns an empty list. In that case, _first()
758 # will raise IndexError and we should treat it as an indication XML
759 # is not valid. exceptions.AuthorizationFailure can be raised from
760 # str_to_xml(), however since server returned HTTP 500 we should
761 # re-raise exceptions.InternalServerError.
762 except (IndexError, exceptions.AuthorizationFailure):
763 raise e
764
765 request_security_token = self.xml_to_str(self.prepared_request)
766 try:
767 response = session.post(
768 url=self.identity_provider_url, headers=self.HEADER_SOAP,
769 data=request_security_token, authenticated=False)
770 except exceptions.InternalServerError as e:
771 reason = _get_failure(e)
772 raise exceptions.AuthorizationFailure(reason)
773 msg = _("Error parsing XML returned from "
774 "the ADFS Identity Provider, reason: %s")
775 self.adfs_token = self.str_to_xml(response.content, msg)
776
777 def _prepare_sp_request(self):
778 """Prepare ADFS Security Token to be sent to the Service Provider.
779
780 The method works as follows:
781 * Extract SAML2 assertion from the ADFS Security Token.
782 * Replace namespaces
783 * urlencode assertion
784 * concatenate static string with the encoded assertion
785
786 """
787 assertion = self.adfs_token.xpath(
788 self.ADFS_ASSERTION_XPATH, namespaces=self.ADFS_TOKEN_NAMESPACES)
789 assertion = self._first(assertion)
790 assertion = self.xml_to_str(assertion)
791 # TODO(marek-denis): Ideally no string replacement should occur.
792 # Unfortunately lxml doesn't allow for namespaces changing in-place and
793 # probably the only solution good for now is to build the assertion
794 # from scratch and reuse values from the adfs security token.
795 assertion = assertion.replace(
796 b'http://docs.oasis-open.org/ws-sx/ws-trust/200512',
797 b'http://schemas.xmlsoap.org/ws/2005/02/trust')
798
799 encoded_assertion = urllib.parse.quote(assertion)
800 self.encoded_assertion = 'wa=wsignin1.0&wresult=' + encoded_assertion
801
802 def _send_assertion_to_service_provider(self, session):
803 """Send prepared assertion to a service provider.
804
805 As the assertion doesn't contain a protected resource, the value from
806 the ``location`` header is not valid and we should not let the Session
807 object get redirected there. The aim of this call is to get a cookie in
808 the response which is required for entering a protected endpoint.
809
810 :param session : a session object to send out HTTP requests.
811 :type session: keystoneclient.session.Session
812
813 :raises: Corresponding HTTP error exception
814
815 """
816 session.post(
817 url=self.service_provider_endpoint, data=self.encoded_assertion,
818 headers=self.HEADER_X_FORM, redirect=False, authenticated=False)
819
820 def _access_service_provider(self, session):
821 """Access protected endpoint and fetch unscoped token.
822
823 After federated authentication workflow a protected endpoint should be
824 accessible with the session object. The access is granted basing on the
825 cookies stored within the session object. If, for some reason no
826 cookies are present (quantity test) it means something went wrong and
827 user will not be able to fetch an unscoped token. In that case an
828 ``exceptions.AuthorizationFailure` exception is raised and no HTTP call
829 is even made.
830
831 :param session : a session object to send out HTTP requests.
832 :type session: keystoneclient.session.Session
833
834 :raises keystoneclient.exceptions.AuthorizationFailure: in case session
835 object has empty cookie jar.
836
837 """
838 if self._cookies(session) is False:
839 raise exceptions.AuthorizationFailure(
840 _("Session object doesn't contain a cookie, therefore you are "
841 "not allowed to enter the Identity Provider's protected "
842 "area."))
843 self.authenticated_response = session.get(self.token_url,
844 authenticated=False)
845
846 def _get_unscoped_token(self, session, *kwargs):
847 """Retrieve unscoped token after authentcation with ADFS server.
848
849 This is a multistep process::
850
851 * Prepare ADFS Request Securty Token -
852 build an etree.XML object filling certain attributes with proper user
853 credentials, created/expires dates (ticket is be valid for 120 seconds
854 as currently we don't handle reusing ADFS issued security tokens) .
855 Step handled by ``ADFSUnscopedToken._prepare_adfs_request()`` method.
856
857 * Send ADFS Security token to the ADFS server. Step handled by
858 ``ADFSUnscopedToken._get_adfs_security_token()`` method.
859
860 * Receive and parse security token, extract actual SAML assertion and
861 prepare a request addressed for the Service Provider endpoint.
862 This also includes changing namespaces in the XML document. Step
863 handled by ``ADFSUnscopedToken._prepare_sp_request()`` method.
864
865 * Send prepared assertion to the Service Provider endpoint. Usually
866 the server will respond with HTTP 301 code which should be ignored as
867 the 'location' header doesn't contain protected area. The goal of this
868 operation is fetching the session cookie which later allows for
869 accessing protected URL endpoints. Step handed by
870 ``ADFSUnscopedToken._send_assertion_to_service_provider()`` method.
871
872 * Once the session cookie is issued, the protected endpoint can be
873 accessed and an unscoped token can be retrieved. Step handled by
874 ``ADFSUnscopedToken._access_service_provider()`` method.
875
876 :param session : a session object to send out HTTP requests.
877 :type session: keystoneclient.session.Session
878
879 :returns: (Unscoped federated token, token JSON body)
880
881 """
882 self._prepare_adfs_request()
883 self._get_adfs_security_token(session)
884 self._prepare_sp_request()
885 self._send_assertion_to_service_provider(session)
886 self._access_service_provider(session)
887
888 try:
889 return (self.authenticated_response.headers['X-Subject-Token'],
890 self.authenticated_response.json()['token'])
891 except (KeyError, ValueError):
892 raise exceptions.InvalidResponse(
893 response=self.authenticated_response)
894
895 def get_auth_ref(self, session, **kwargs):
896 token, token_json = self._get_unscoped_token(session)
897 return access.AccessInfoV3(token, **token_json)
898
899
900 class Saml2ScopedTokenMethod(v3.TokenMethod):
901 _method_name = 'saml2'
902
903 def get_auth_data(self, session, auth, headers, **kwargs):
904 """Build and return request body for token scoping step."""
905 t = super(Saml2ScopedTokenMethod, self).get_auth_data(
906 session, auth, headers, **kwargs)
907 _token_method, token = t
908 return self._method_name, token
909
910
911 class Saml2ScopedToken(v3.Token):
912 """Class for scoping unscoped saml2 token."""
913
914 _auth_method_class = Saml2ScopedTokenMethod
915
916 def __init__(self, auth_url, token, **kwargs):
917 super(Saml2ScopedToken, self).__init__(auth_url, token, **kwargs)
918 if not (self.project_id or self.domain_id):
919 raise exceptions.ValidationError(
920 _('Neither project nor domain specified'))