summaryrefslogtreecommitdiff
path: root/src/saml2/s2repoze/plugins/sp.py
blob: 94389ff65cbe638a4a0e3cc39c57560fddc697d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
#
"""
A plugin that allows you to use SAML2 SSO as authentication
and SAML2 attribute aggregations as metadata collector in your
WSGI application.

"""
import logging
import sys
import platform
import shelve
import traceback
import saml2
import six
from saml2.samlp import Extensions
from saml2 import xmldsig as ds

from six import StringIO
from six.moves.urllib import parse

from paste.httpexceptions import HTTPSeeOther, HTTPRedirection
from paste.httpexceptions import HTTPNotImplemented
from paste.httpexceptions import HTTPInternalServerError
from paste.request import parse_dict_querystring
from paste.request import construct_url
from saml2.extension.pefim import SPCertEnc
from saml2.httputil import getpath, SeeOther
from saml2.client_base import ECP_SERVICE, MIME_PAOS
from zope.interface import implementer

from repoze.who.interfaces import IChallenger, IIdentifier, IAuthenticator
from repoze.who.interfaces import IMetadataProvider

from saml2 import ecp, BINDING_HTTP_REDIRECT, element_to_extension_element
from saml2 import BINDING_HTTP_POST

from saml2.client import Saml2Client
from saml2.ident import code, decode
from saml2.s_utils import sid
from saml2.config import config_factory
from saml2.profile import paos

# from saml2.population import Population
# from saml2.attribute_resolver import AttributeResolver

logger = logging.getLogger(__name__)

PAOS_HEADER_INFO = 'ver="%s";"%s"' % (paos.NAMESPACE, ECP_SERVICE)


def construct_came_from(environ):
    """ The URL that the user used when the process where interupted
    for single-sign-on processing. """

    came_from = environ.get("PATH_INFO")
    qstr = environ.get("QUERY_STRING", "")
    if qstr:
        came_from += "?" + qstr
    return came_from


def exception_trace(tag, exc, log):
    message = traceback.format_exception(*sys.exc_info())
    log.error("[%s] ExcList: %s" % (tag, "".join(message)))
    log.error("[%s] Exception: %s" % (tag, exc))


class ECP_response(object):
    code = 200
    title = "OK"

    def __init__(self, content):
        self.content = content

    # noinspection PyUnusedLocal
    def __call__(self, environ, start_response):
        start_response(
            "%s %s" % (self.code, self.title), [("Content-Type", "text/xml")]
        )
        return [self.content]


@implementer(IChallenger, IIdentifier, IAuthenticator, IMetadataProvider)
class SAML2Plugin(object):
    def __init__(
        self,
        rememberer_name,
        config,
        saml_client,
        wayf,
        cache,
        sid_store=None,
        discovery="",
        idp_query_param="",
        sid_store_cert=None,
    ):
        self.rememberer_name = rememberer_name
        self.wayf = wayf
        self.saml_client = saml_client
        self.conf = config
        self.cache = cache
        self.discosrv = discovery
        self.idp_query_param = idp_query_param
        self.logout_endpoints = [
            parse.urlparse(ep).path for ep in config.endpoint("single_logout_service")
        ]
        try:
            self.metadata = self.conf.metadata
        except KeyError:
            self.metadata = None
        if sid_store:
            self.outstanding_queries = shelve.open(
                sid_store, writeback=True, protocol=2
            )
        else:
            self.outstanding_queries = {}
        if sid_store_cert:
            self.outstanding_certs = shelve.open(
                sid_store_cert, writeback=True, protocol=2
            )
        else:
            self.outstanding_certs = {}

        self.iam = platform.node()

    def _get_rememberer(self, environ):
        rememberer = environ["repoze.who.plugins"][self.rememberer_name]
        return rememberer

    #### IIdentifier ####
    def remember(self, environ, identity):
        rememberer = self._get_rememberer(environ)
        return rememberer.remember(environ, identity)

    #### IIdentifier ####
    def forget(self, environ, identity):
        rememberer = self._get_rememberer(environ)
        return rememberer.forget(environ, identity)

    def _get_post(self, environ):
        """
        Get the posted information

        :param environ: A dictionary with environment variables
        """

        body = ""
        try:
            length = int(environ.get("CONTENT_LENGTH", "0"))
        except ValueError:
            length = 0
        if length != 0:
            body = environ["wsgi.input"].read(length)  # get the POST variables
            environ["s2repoze.body"] = body  # store the request body for later
            # use by pysaml2
            environ["wsgi.input"] = StringIO(body)  # restore the request body
            # as a stream so that everything seems untouched

        post = parse.parse_qs(body)  # parse the POST fields into a dict

        logger.debug("identify post: %s", post)

        return post

    def _wayf_redirect(self, came_from):
        sid_ = sid()
        self.outstanding_queries[sid_] = came_from
        logger.info("Redirect to WAYF function: %s", self.wayf)
        return -1, HTTPSeeOther(headers=[("Location", "%s?%s" % (self.wayf, sid_))])

    # noinspection PyUnusedLocal
    def _pick_idp(self, environ, came_from):
        """
        If more than one idp and if none is selected, I have to do wayf or
        disco
        """

        # check headers to see if it's an ECP request
        #        headers = {
        #                    'Accept' : 'text/html; application/vnd.paos+xml',
        #                    'PAOS'   : 'ver="%s";"%s"' % (paos.NAMESPACE,
        # SERVICE)
        #                    }

        _cli = self.saml_client

        logger.info("[_pick_idp] %s", environ)
        if "HTTP_PAOS" in environ:
            if environ["HTTP_PAOS"] == PAOS_HEADER_INFO:
                if MIME_PAOS in environ["HTTP_ACCEPT"]:
                    # Where should I redirect the user to
                    # entityid -> the IdP to use
                    # relay_state -> when back from authentication

                    logger.info("- ECP client detected -")

                    _relay_state = construct_came_from(environ)
                    _entityid = _cli.config.ecp_endpoint(environ["REMOTE_ADDR"])

                    if not _entityid:
                        return -1, HTTPInternalServerError(detail="No IdP to talk to")
                    logger.info("IdP to talk to: %s", _entityid)
                    return ecp.ecp_auth_request(_cli, _entityid, _relay_state)
                else:
                    return -1, HTTPInternalServerError(detail="Faulty Accept header")
            else:
                return -1, HTTPInternalServerError(detail="unknown ECP version")

        idps = self.metadata.with_descriptor("idpsso")

        logger.info("IdP URL: %s", idps)

        idp_entity_id = query = None

        for key in ["s2repoze.body", "QUERY_STRING"]:
            query = environ.get(key)
            if query:
                try:
                    _idp_entity_id = dict(parse.parse_qs(query))[self.idp_query_param][0]
                    if _idp_entity_id in idps:
                        idp_entity_id = _idp_entity_id
                    break
                except KeyError:
                    logger.debug("No IdP entity ID in query: %s", query)
                    pass

        if idp_entity_id is None:
            if len(idps) == 1:
                # idps is a dictionary
                idp_entity_id = idps.keys()[0]
            elif not len(idps):
                return -1, HTTPInternalServerError(detail="Misconfiguration")
            else:
                idp_entity_id = ""
                logger.info("ENVIRON: %s", environ)

                if self.wayf:
                    if query:
                        try:
                            wayf_selected = dict(parse.parse_qs(query))["wayf_selected"][0]
                        except KeyError:
                            return self._wayf_redirect(came_from)
                        idp_entity_id = wayf_selected
                    else:
                        return self._wayf_redirect(came_from)
                elif self.discosrv:
                    if query:
                        idp_entity_id = _cli.parse_discovery_service_response(
                            query=environ.get("QUERY_STRING")
                        )
                    else:
                        sid_ = sid()
                        self.outstanding_queries[sid_] = came_from
                        logger.debug("Redirect to Discovery Service function")
                        eid = _cli.config.entityid
                        ret = _cli.config.getattr("endpoints", "sp")[
                            "discovery_response"
                        ][0][0]
                        ret += "?sid=%s" % sid_
                        loc = _cli.create_discovery_service_request(
                            self.discosrv, eid, **{"return": ret}
                        )
                        return -1, SeeOther(loc)

                else:
                    return -1, HTTPNotImplemented(detail="No WAYF or DJ present!")

        logger.info("Chosen IdP: '%s'", idp_entity_id)
        return 0, idp_entity_id

    #### IChallenger ####
    # noinspection PyUnusedLocal
    def challenge(self, environ, _status, _app_headers, _forget_headers):
        _cli = self.saml_client

        if "REMOTE_USER" in environ:
            name_id = decode(environ["REMOTE_USER"])

            _cli = self.saml_client
            path_info = environ["PATH_INFO"]

            if "samlsp.logout" in environ:
                responses = _cli.global_logout(name_id)
                return self._handle_logout(responses)

        if "samlsp.pending" in environ:
            response = environ["samlsp.pending"]
            if isinstance(response, HTTPRedirection):
                response.headers += _forget_headers
            return response

        # logger = environ.get('repoze.who.logger','')

        # Which page was accessed to get here
        came_from = construct_came_from(environ)
        environ["myapp.came_from"] = came_from
        logger.debug("[sp.challenge] RelayState >> '%s'", came_from)

        # Am I part of a virtual organization or more than one ?
        try:
            vorg_name = environ["myapp.vo"]
        except KeyError:
            try:
                vorg_name = _cli.vorg._name
            except AttributeError:
                vorg_name = ""

        logger.info("[sp.challenge] VO: %s", vorg_name)

        # If more than one idp and if none is selected, I have to do wayf
        (done, response) = self._pick_idp(environ, came_from)
        # Three cases: -1 something went wrong or Discovery service used
        #               0 I've got an IdP to send a request to
        #               >0 ECP in progress
        logger.debug("_idp_pick returned: %s", done)
        if done == -1:
            return response
        elif done > 0:
            self.outstanding_queries[done] = came_from
            return ECP_response(response)
        else:
            entity_id = response
            logger.info("[sp.challenge] entity_id: %s", entity_id)
            # Do the AuthnRequest
            _binding = BINDING_HTTP_REDIRECT
            try:
                srvs = _cli.metadata.single_sign_on_service(entity_id, _binding)
                logger.debug("srvs: %s", srvs)
                dest = srvs[0]["location"]
                logger.debug("destination: %s", dest)

                extensions = None
                cert = None

                if _cli.config.generate_cert_func is not None:
                    cert_str, req_key_str = _cli.config.generate_cert_func()
                    cert = {"cert": cert_str, "key": req_key_str}
                    spcertenc = SPCertEnc(
                        x509_data=ds.X509Data(
                            x509_certificate=ds.X509Certificate(text=cert_str)
                        )
                    )
                    extensions = Extensions(
                        extension_elements=[element_to_extension_element(spcertenc)]
                    )

                if _cli.authn_requests_signed:
                    _sid = sid()
                    req_id, msg_str = _cli.create_authn_request(
                        dest,
                        vorg=vorg_name,
                        sign=_cli.authn_requests_signed,
                        message_id=_sid,
                        extensions=extensions,
                    )
                    _sid = req_id
                else:
                    req_id, req = _cli.create_authn_request(
                        dest,
                        vorg=vorg_name,
                        sign=False,
                        extensions=extensions,
                    )
                    msg_str = "%s" % req
                    _sid = req_id

                if cert is not None:
                    self.outstanding_certs[_sid] = cert

                ht_args = _cli.apply_binding(
                    _binding,
                    msg_str,
                    destination=dest,
                    relay_state=came_from,
                    sign=_cli.authn_requests_signed,
                )

                logger.debug("ht_args: %s", ht_args)
            except Exception as exc:
                logger.exception(exc)
                raise Exception("Failed to construct the AuthnRequest: %s" % exc)

            try:
                ret = _cli.config.getattr("endpoints", "sp")["discovery_response"][0][0]
                if (environ["PATH_INFO"]) in ret and ret.split(environ["PATH_INFO"])[
                    1
                ] == "":
                    query = parse.parse_qs(environ["QUERY_STRING"])
                    sid = query["sid"][0]
                    came_from = self.outstanding_queries[sid]
            except:
                pass
            # remember the request
            self.outstanding_queries[_sid] = came_from

            if not ht_args["data"] and ht_args["headers"][0][0] == "Location":
                logger.debug("redirect to: %s", ht_args["headers"][0][1])
                return HTTPSeeOther(headers=ht_args["headers"])
            else:
                return ht_args["data"]

    def _construct_identity(self, session_info):
        cni = code(session_info["name_id"])
        identity = {
            "login": cni,
            "password": "",
            "repoze.who.userid": cni,
            "user": session_info["ava"],
        }
        logger.debug("Identity: %s", identity)

        return identity

    def _eval_authn_response(self, environ, post, binding=BINDING_HTTP_POST):
        logger.info("Got AuthN response, checking..")
        logger.info("Outstanding: %s", self.outstanding_queries)

        try:
            # Evaluate the response, returns a AuthnResponse instance
            try:
                authresp = self.saml_client.parse_authn_request_response(
                    post["SAMLResponse"][0],
                    binding,
                    self.outstanding_queries,
                    self.outstanding_certs,
                )

            except Exception as excp:
                logger.exception("Exception: %s" % (excp,))
                raise

            session_info = authresp.session_info()
        except TypeError as excp:
            logger.exception("Exception: %s" % (excp,))
            return None

        if session_info["came_from"]:
            logger.debug("came_from << %s", session_info["came_from"])
            try:
                path, query = session_info["came_from"].split("?")
                environ["PATH_INFO"] = path
                environ["QUERY_STRING"] = query
            except ValueError:
                environ["PATH_INFO"] = session_info["came_from"]

        logger.info("Session_info: %s", session_info)
        return session_info

    def do_ecp_response(self, body, environ):
        response, _relay_state = ecp.handle_ecp_authn_response(self.saml_client, body)

        environ["s2repoze.relay_state"] = _relay_state.text
        session_info = response.session_info()
        logger.info("Session_info: %s", session_info)

        return session_info

    #### IIdentifier ####
    def identify(self, environ):
        """
        Tries to do the identification
        """
        # logger = environ.get('repoze.who.logger', '')

        session_info = None

        uri = environ.get("REQUEST_URI", construct_url(environ))
        query = parse_dict_querystring(environ)

        logger.debug("[sp.identify] uri: %s", uri)
        logger.debug("[sp.identify] query: %s", query)

        is_request = "SAMLRequest" in query
        is_response = "SAMLResponse" in query
        has_content_length = environ.get("CONTENT_LENGTH")

        if not has_content_length and not is_request and not is_response:
            logger.debug("[identify] get or empty post")
            return None

        if is_request or is_response:
            post = query
            binding = BINDING_HTTP_REDIRECT
        else:
            post = self._get_post(environ)
            binding = BINDING_HTTP_POST

        try:
            logger.debug("[sp.identify] post keys: %s", post.keys())
        except (TypeError, IndexError):
            pass

        try:
            path = getpath(environ)
            logout = False
            if path in self.logout_endpoints:
                logout = True

            if logout and is_request:
                print("logout request received")
                if binding == BINDING_HTTP_REDIRECT:
                    saml_request = post["SAMLRequest"]
                else:
                    saml_request = post["SAMLRequest"][0]
                try:
                    response = self.saml_client.handle_logout_request(
                        saml_request, self.saml_client.users.subjects()[0], binding
                    )
                    environ["samlsp.pending"] = self._handle_logout(response)
                    return {}
                except:
                    import traceback

                    traceback.print_exc()
            elif not is_response:
                logger.info("[sp.identify] --- NOT SAMLResponse ---")
                # Not for me, put the post back where next in line can find it
                environ["post.fieldstorage"] = post
                # restore wsgi.input incase that is needed
                # only of s2repoze.body is present
                if "s2repoze.body" in environ:
                    environ["wsgi.input"] = StringIO(environ["s2repoze.body"])
                return {}
            else:
                logger.info("[sp.identify] --- SAMLResponse ---")
                # check for SAML2 authN response
                try:
                    if logout:
                        response = self.saml_client.parse_logout_request_response(
                            post["SAMLResponse"][0], binding
                        )
                        if response:
                            action = self.saml_client.handle_logout_response(response)

                            if type(action) == dict:
                                request = self._handle_logout(action)
                            else:
                                request = HTTPSeeOther(headers=[("Location", "/")])
                            if request:
                                environ["samlsp.pending"] = request
                            return {}
                    else:
                        session_info = self._eval_authn_response(
                            environ, post, binding=binding
                        )
                except Exception as err:
                    environ["s2repoze.saml_error"] = err
                    return {}
        except TypeError as exc:
            # might be a ECP (=SOAP) response
            body = environ.get("s2repoze.body", None)
            if body:
                # might be a ECP response
                try:
                    session_info = self.do_ecp_response(body, environ)
                except Exception as err:
                    environ["post.fieldstorage"] = post
                    environ["s2repoze.saml_error"] = err
                    return {}
            else:
                exception_trace("sp.identity", exc, logger)
                environ["post.fieldstorage"] = post
                return {}

        if session_info:
            environ["s2repoze.sessioninfo"] = session_info
            identity_info = self._construct_identity(session_info)
        else:
            identity_info = None

        return identity_info

    # IMetadataProvider
    def add_metadata(self, environ, identity):
        """ Add information to the knowledge I have about the user """
        name_id = identity["repoze.who.userid"]
        if isinstance(name_id, six.string_types):
            try:
                # Make sure that userids authenticated by another plugin
                # don't cause problems here.
                name_id = decode(name_id)
            except:
                pass

        _cli = self.saml_client
        logger.debug("[add_metadata] for %s", name_id)
        try:
            logger.debug("Issuers: %s", _cli.users.sources(name_id))
        except KeyError:
            pass

        if "user" not in identity:
            identity["user"] = {}
        try:
            (ava, _) = _cli.users.get_identity(name_id)
            # now = time.gmtime()
            logger.debug("[add_metadata] adds: %s", ava)
            identity["user"].update(ava)
        except KeyError:
            pass

        if "pysaml2_vo_expanded" not in identity and _cli.vorg:
            # is this a Virtual Organization situation
            for vo in _cli.vorg.values():
                try:
                    if vo.do_aggregation(name_id):
                        # Get the extended identity
                        identity["user"] = _cli.users.get_identity(name_id)[0]
                        # Only do this once, mark that the identity has been
                        # expanded
                        identity["pysaml2_vo_expanded"] = 1
                except KeyError:
                    logger.exception(
                        "Failed to do attribute aggregation, "
                        "missing common attribute"
                    )
        logger.debug("[add_metadata] returns: %s", dict(identity))

        if not identity["user"]:
            # remove cookie and demand re-authentication
            pass

    # used 2 times : one to get the ticket, the other to validate it
    @staticmethod
    def _service_url(environ, qstr=None):
        if qstr is not None:
            url = construct_url(environ, querystring=qstr)
        else:
            url = construct_url(environ)
        return url

    #### IAuthenticatorPlugin ####
    # noinspection PyUnusedLocal
    def authenticate(self, environ, identity=None):
        if identity:
            if (
                identity.get("user")
                and environ.get("s2repoze.sessioninfo")
                and identity.get("user")
                == environ.get("s2repoze.sessioninfo").get("ava")
            ):
                return identity.get("login")
            tktuser = identity.get("repoze.who.plugins.auth_tkt.userid", None)
            if tktuser and self.saml_client.is_logged_in(decode(tktuser)):
                return tktuser
            return None
        else:
            return None

    @staticmethod
    def _handle_logout(responses):
        if "data" in responses:
            ht_args = responses
        else:
            ht_args = responses[responses.keys()[0]][1]
        if not ht_args["data"] and ht_args["headers"][0][0] == "Location":
            logger.debug("redirect to: %s", ht_args["headers"][0][1])
            return HTTPSeeOther(headers=ht_args["headers"])
        else:
            return ht_args["data"]


def make_plugin(
    remember_name=None,  # plugin for remember
    cache="",  # cache
    # Which virtual organization to support
    virtual_organization="",
    saml_conf="",
    wayf="",
    sid_store="",
    identity_cache="",
    discovery="",
    idp_query_param="",
):
    if saml_conf == "":
        raise ValueError("must include saml_conf in configuration")

    if remember_name is None:
        raise ValueError("must include remember_name in configuration")

    conf = config_factory("sp", saml_conf)

    scl = Saml2Client(
        config=conf,
        identity_cache=identity_cache,
        virtual_organization=virtual_organization,
    )

    plugin = SAML2Plugin(
        remember_name, conf, scl, wayf, cache, sid_store, discovery, idp_query_param
    )
    return plugin