File: adfs.cpp

package info (click to toggle)
shibboleth-sp2 2.6.0%2Bdfsg1-4%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 7,896 kB
  • sloc: cpp: 39,404; sh: 11,726; makefile: 866; xml: 371; ansic: 35
file content (1091 lines) | stat: -rw-r--r-- 44,698 bytes parent folder | download | duplicates (3)
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
/**
 * Licensed to the University Corporation for Advanced Internet
 * Development, Inc. (UCAID) under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.
 *
 * UCAID licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the
 * License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

/**
 * adfs.cpp
 *
 * ADFSv1 extension library.
 */

#if defined (_MSC_VER) || defined(__BORLANDC__)
# include "config_win32.h"
#else
# include "config.h"
#endif

#ifdef WIN32
# define _CRT_NONSTDC_NO_DEPRECATE 1
# define _CRT_SECURE_NO_DEPRECATE 1
# define ADFS_EXPORTS __declspec(dllexport)
#else
# define ADFS_EXPORTS
#endif

#include <shibsp/base.h>
#include <shibsp/exceptions.h>
#include <shibsp/Application.h>
#include <shibsp/ServiceProvider.h>
#include <shibsp/SessionCache.h>
#include <shibsp/SPConfig.h>
#include <shibsp/SPRequest.h>
#include <shibsp/TransactionLog.h>
#include <shibsp/handler/AssertionConsumerService.h>
#include <shibsp/handler/LogoutInitiator.h>
#include <shibsp/handler/SessionInitiator.h>
#include <xmltooling/logging.h>
#include <xmltooling/util/DateTime.h>
#include <xmltooling/util/NDC.h>
#include <xmltooling/util/URLEncoder.h>
#include <xmltooling/util/XMLHelper.h>
#include <memory>

#ifndef SHIBSP_LITE
# include <shibsp/attribute/resolver/ResolutionContext.h>
# include <shibsp/metadata/MetadataProviderCriteria.h>
# include <saml/SAMLConfig.h>
# include <saml/exceptions.h>
# include <saml/binding/SecurityPolicy.h>
# include <saml/saml1/core/Assertions.h>
# include <saml/saml2/core/Assertions.h>
# include <saml/saml2/metadata/Metadata.h>
# include <saml/saml2/metadata/EndpointManager.h>
# include <xmltooling/XMLToolingConfig.h>
# include <xmltooling/impl/AnyElement.h>
# include <xmltooling/util/ParserPool.h>
# include <xmltooling/validation/ValidatorSuite.h>
using namespace opensaml::saml2md;
# ifndef min
#  define min(a,b)            (((a) < (b)) ? (a) : (b))
# endif
#endif
using namespace shibsp;
using namespace opensaml;
using namespace xmltooling::logging;
using namespace xmltooling;
using namespace xercesc;
using namespace boost;
using namespace std;

#define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"
#define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"

namespace {

#ifndef SHIBSP_LITE
    class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder
    {
        auto_ptr_XMLCh m_ns;
    public:
        ADFSDecoder() : m_ns(WSTRUST_NS) {}
        virtual ~ADFSDecoder() {}

        const XMLCh* getProtocolFamily() const {
            return m_ns.get();
        }

        XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;

    protected:
        void extractMessageDetails(
            const XMLObject& message, const GenericRequest& req, const XMLCh* protocol, SecurityPolicy& policy
            ) const {
        }
    };

    MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
    {
        return new ADFSDecoder();
    }
#endif

#if defined (_MSC_VER)
    #pragma warning( push )
    #pragma warning( disable : 4250 )
#endif

    class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
    {
    public:
        ADFSSessionInitiator(const DOMElement* e, const char* appId)
            : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".SessionInitiator.ADFS"), nullptr, &m_remapper), m_appId(appId), m_binding(WSFED_NS) {
            // If Location isn't set, defer address registration until the setParent call.
            pair<bool,const char*> loc = getString("Location");
            if (loc.first) {
                string address = m_appId + loc.second + "::run::ADFSSI";
                setAddress(address.c_str());
            }
        }
        virtual ~ADFSSessionInitiator() {}

        void setParent(const PropertySet* parent) {
            DOMPropertySet::setParent(parent);
            pair<bool,const char*> loc = getString("Location");
            if (loc.first) {
                string address = m_appId + loc.second + "::run::ADFSSI";
                setAddress(address.c_str());
            }
            else {
                m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");
            }
        }

        void receive(DDF& in, ostream& out);
        pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
        pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;

        const XMLCh* getProtocolFamily() const {
            return m_binding.get();
        }

#ifndef SHIBSP_LITE
        void generateMetadata(saml2md::SPSSODescriptor& role, const char* handlerURL) const {
            doGenerateMetadata(role, handlerURL);
        }
#endif

    private:
        pair<bool,long> doRequest(
            const Application& application,
            const HTTPRequest* httpRequest,
            HTTPResponse& httpResponse,
            const char* entityID,
            const char* acsLocation,
            const char* authnContextClassRef,
            string& relayState
            ) const;
        string m_appId;
        auto_ptr_XMLCh m_binding;
    };

    class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
    {
        auto_ptr_XMLCh m_protocol;
    public:
        ADFSConsumer(const DOMElement* e, const char* appId)
            : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT ".SSO.ADFS")), m_protocol(WSFED_NS) {}
        virtual ~ADFSConsumer() {}

#ifndef SHIBSP_LITE
        void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
            AssertionConsumerService::generateMetadata(role, handlerURL);
            role.addSupport(m_protocol.get());
        }

    private:
        void implementProtocol(
            const Application& application,
            const HTTPRequest& httpRequest,
            HTTPResponse& httpResponse,
            SecurityPolicy& policy,
            const PropertySet*,
            const XMLObject& xmlObject
            ) const;
#else
        const XMLCh* getProtocolFamily() const {
            return m_protocol.get();
        }
#endif
    };

    class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutInitiator
    {
    public:
        ADFSLogoutInitiator(const DOMElement* e, const char* appId)
                : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".LogoutInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
            // If Location isn't set, defer address registration until the setParent call.
            pair<bool,const char*> loc = getString("Location");
            if (loc.first) {
                string address = m_appId + loc.second + "::run::ADFSLI";
                setAddress(address.c_str());
            }
        }
        virtual ~ADFSLogoutInitiator() {}

        void setParent(const PropertySet* parent) {
            DOMPropertySet::setParent(parent);
            pair<bool,const char*> loc = getString("Location");
            if (loc.first) {
                string address = m_appId + loc.second + "::run::ADFSLI";
                setAddress(address.c_str());
            }
            else {
                m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");
            }
        }

        void receive(DDF& in, ostream& out);
        pair<bool,long> run(SPRequest& request, bool isHandler=true) const;

        const XMLCh* getProtocolFamily() const {
            return m_binding.get();
        }

    private:
        pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session) const;

        string m_appId;
        auto_ptr_XMLCh m_binding;
    };

    class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
    {
    public:
        ADFSLogout(const DOMElement* e, const char* appId)
                : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".Logout.ADFS")), m_login(e, appId) {
            m_initiator = false;
#ifndef SHIBSP_LITE
            m_preserve.push_back("wreply");
            string address = string(appId) + getString("Location").second + "::run::ADFSLO";
            setAddress(address.c_str());
#endif
        }
        virtual ~ADFSLogout() {}

        pair<bool,long> run(SPRequest& request, bool isHandler=true) const;

#ifndef SHIBSP_LITE
        void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
            m_login.generateMetadata(role, handlerURL);
            const char* loc = getString("Location").second;
            string hurl(handlerURL);
            if (*loc != '/')
                hurl += '/';
            hurl += loc;
            auto_ptr_XMLCh widen(hurl.c_str());
            SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
            ep->setLocation(widen.get());
            ep->setBinding(m_login.getProtocolFamily());
            role.getSingleLogoutServices().push_back(ep);
        }

        const char* getType() const {
            return m_login.getType();
        }
#endif
        const XMLCh* getProtocolFamily() const {
            return m_login.getProtocolFamily();
        }

    private:
        ADFSConsumer m_login;
    };

#if defined (_MSC_VER)
    #pragma warning( pop )
#endif

    SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
    {
        return new ADFSSessionInitiator(p.first, p.second);
    }

    Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
    {
        return new ADFSLogout(p.first, p.second);
    }

    Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
    {
        return new ADFSLogoutInitiator(p.first, p.second);
    }

    const XMLCh RequestedSecurityToken[] =      UNICODE_LITERAL_22(R,e,q,u,e,s,t,e,d,S,e,c,u,r,i,t,y,T,o,k,e,n);
    const XMLCh RequestSecurityTokenResponse[] =UNICODE_LITERAL_28(R,e,q,u,e,s,t,S,e,c,u,r,i,t,y,T,o,k,e,n,R,e,s,p,o,n,s,e);
};

extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
{
    SPConfig& conf=SPConfig::getConfig();
    conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);
    conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);
    conf.AssertionConsumerServiceManager.registerFactory("ADFS", ADFSLogoutFactory);
    conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);
#ifndef SHIBSP_LITE
    SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
    XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
    XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
#endif
    return 0;
}

extern "C" void ADFS_EXPORTS xmltooling_extension_term()
{
    /* should get unregistered during normal shutdown...
    SPConfig& conf=SPConfig::getConfig();
    conf.SessionInitiatorManager.deregisterFactory("ADFS");
    conf.LogoutInitiatorManager.deregisterFactory("ADFS");
    conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");
    conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);
#ifndef SHIBSP_LITE
    SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
#endif
    */
}

pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
{
    // We have to know the IdP to function.
    if (entityID.empty() || !checkCompatibility(request, isHandler))
        return make_pair(false, 0L);

    string target;
    pair<bool,const char*> prop;
    pair<bool,const char*> acClass;
    const Handler* ACS = nullptr;
    const Application& app = request.getApplication();

    if (isHandler) {
        prop.second = request.getParameter("acsIndex");
        if (prop.second && *prop.second) {
            ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
            if (!ACS)
                request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
        }

        prop = getString("target", request);
        if (prop.first)
            target = prop.second;

        // Since we're passing the ACS by value, we need to compute the return URL,
        // so we'll need the target resource for real.
        recoverRelayState(app, request, request, target, false);
        app.limitRedirect(request, target.c_str());

        // Default is to allow externally supplied settings.
        pair<bool,bool> externalInput = getBool("externalInput");
        unsigned int settingMask = HANDLER_PROPERTY_MAP | HANDLER_PROPERTY_FIXED;
        if (!externalInput.first || externalInput.second)
            settingMask |= HANDLER_PROPERTY_REQUEST;

        acClass = getString("authnContextClassRef", request, settingMask);
    }
    else {
        // Check for a hardwired target value in the map or handler.
        prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
        if (prop.first)
            target = prop.second;
        else
            target = request.getRequestURL();

        acClass = getString("authnContextClassRef", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
    }

    if (!ACS) {
        pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
        if (index.first)
            ACS = app.getAssertionConsumerServiceByIndex(index.second);
    }

    // Validate the ACS for use with this protocol.
    if (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily())) {
        if (ACS)
            request.log(SPRequest::SPWarn, "invalid acsIndex property, or non-ADFS ACS, using default ADFS ACS");
        ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily());
        if (!ACS)
            throw ConfigurationException("Unable to locate an ADFS-compatible ACS in the configuration.");
    }

    // Since we're not passing by index, we need to fully compute the return URL.
    // Compute the ACS URL. We add the ACS location to the base handlerURL.
    string ACSloc = request.getHandlerURL(target.c_str());
    prop = ACS->getString("Location");
    if (prop.first)
        ACSloc += prop.second;

    if (isHandler) {
        // We may already have RelayState set if we looped back here,
        // but we've turned it back into a resource by this point, so if there's
        // a target on the URL, reset to that value.
        prop.second = request.getParameter("target");
        if (prop.second && *prop.second)
            target = prop.second;
    }

    m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID.c_str());

    if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
        // Out of process means the POST data via the request can be exposed directly to the private method.
        // The method will handle POST preservation if necessary *before* issuing the response, but only if
        // it dispatches to an IdP.
        return doRequest(app, &request, request, entityID.c_str(), ACSloc.c_str(), (acClass.first ? acClass.second : nullptr), target);
    }

    // Remote the call.
    DDF out,in = DDF(m_address.c_str()).structure();
    DDFJanitor jin(in), jout(out);
    in.addmember("application_id").string(app.getId());
    in.addmember("entity_id").string(entityID.c_str());
    in.addmember("acsLocation").string(ACSloc.c_str());
    if (!target.empty())
        in.addmember("RelayState").unsafe_string(target.c_str());
    if (acClass.first)
        in.addmember("authnContextClassRef").string(acClass.second);

    // Remote the processing.
    out = request.getServiceProvider().getListenerService()->send(in);
    return unwrap(request, out);
}

pair<bool,long> ADFSSessionInitiator::unwrap(SPRequest& request, DDF& out) const
{
    // See if there's any response to send back.
    if (!out["redirect"].isnull() || !out["response"].isnull()) {
        // If so, we're responsible for handling the POST data, probably by dropping a cookie.
        preservePostData(request.getApplication(), request, request, out["RelayState"].string());
    }
    return RemotedHandler::unwrap(request, out);
}

void ADFSSessionInitiator::receive(DDF& in, ostream& out)
{
    // Find application.
    const char* aid = in["application_id"].string();
    const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
    if (!app) {
        // Something's horribly wrong.
        m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");
        throw ConfigurationException("Unable to locate application for new session, deleted?");
    }

    const char* entityID = in["entity_id"].string();
    const char* acsLocation = in["acsLocation"].string();
    if (!entityID || !acsLocation)
        throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");

    DDF ret(nullptr);
    DDFJanitor jout(ret);

    // Wrap the outgoing object with a Response facade.
    scoped_ptr<HTTPResponse> http(getResponse(ret));

    string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");

    // Since we're remoted, the result should either be a throw, which we pass on,
    // a false/0 return, which we just return as an empty structure, or a response/redirect,
    // which we capture in the facade and send back.
    doRequest(*app, nullptr, *http, entityID, acsLocation, in["authnContextClassRef"].string(), relayState);
    if (!ret.isstruct())
        ret.structure();
    ret.addmember("RelayState").unsafe_string(relayState.c_str());
    out << ret;
}

pair<bool,long> ADFSSessionInitiator::doRequest(
    const Application& app,
    const HTTPRequest* httpRequest,
    HTTPResponse& httpResponse,
    const char* entityID,
    const char* acsLocation,
    const char* authnContextClassRef,
    string& relayState
    ) const
{
#ifndef SHIBSP_LITE
    // Use metadata to invoke the SSO service directly.
    MetadataProvider* m = app.getMetadataProvider();
    Locker locker(m);
    MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
    pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
    if (!entity.first) {
        m_log.warn("unable to locate metadata for provider (%s)", entityID);
        throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
    }
    else if (!entity.second) {
        m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
        if (getParent())
            return make_pair(false, 0L);
        throw MetadataException("Unable to locate ADFS-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
    }
    const EndpointType* ep = EndpointManager<SingleSignOnService>(
        dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
        ).getByBinding(m_binding.get());
    if (!ep) {
        m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
        if (getParent())
            return make_pair(false, 0L);
        throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
    }

    preserveRelayState(app, httpResponse, relayState);

    scoped_ptr<AuthnRequestEvent> ar_event(newAuthnRequestEvent(app, httpRequest));
    if (ar_event.get()) {
        ar_event->m_binding = WSFED_NS;
        ar_event->m_protocol = WSFED_NS;
        ar_event->m_peer = entity.first;
        app.getServiceProvider().getTransactionLog()->write(*ar_event);
    }

    // UTC timestamp
    time_t epoch=time(nullptr);
#ifndef HAVE_GMTIME_R
    struct tm* ptime=gmtime(&epoch);
#else
    struct tm res;
    struct tm* ptime=gmtime_r(&epoch,&res);
#endif
    char timebuf[32];
    strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);

    auto_ptr_char dest(ep->getLocation());
    const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();

    const PropertySet* relyingParty = app.getRelyingParty(entity.first);

    string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignin1.0&wreply=" + urlenc->encode(acsLocation) +
        "&wct=" + urlenc->encode(timebuf) + "&wtrealm=" + urlenc->encode(relyingParty->getString("entityID").second);
    if (!authnContextClassRef) {
        pair<bool,const char*> rpClass = relyingParty->getString("authnContextClassRef");
        if (rpClass.first)
            authnContextClassRef = rpClass.second;
    }
    if (authnContextClassRef)
        req += "&wauth=" + urlenc->encode(authnContextClassRef);
    if (!relayState.empty())
        req += "&wctx=" + urlenc->encode(relayState.c_str());

    if (httpRequest) {
        // If the request object is available, we're responsible for the POST data.
        preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
    }

    return make_pair(true, httpResponse.sendRedirect(req.c_str()));
#else
    return make_pair(false, 0L);
#endif
}

#ifndef SHIBSP_LITE

XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
{
#ifdef _DEBUG
    xmltooling::NDC ndc("decode");
#endif
    Category& log = Category::getInstance(SHIBSP_LOGCAT ".MessageDecoder.ADFS");

    log.debug("validating input");
    const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
    if (!httpRequest)
        throw BindingException("Unable to cast request object to HTTPRequest type.");
    if (strcmp(httpRequest->getMethod(),"POST"))
        throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
    const char* param = httpRequest->getParameter("wa");
    if (!param || strcmp(param, "wsignin1.0"))
        throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");
    param = httpRequest->getParameter("wctx");
    if (param)
        relayState = param;

    param = httpRequest->getParameter("wresult");
    if (!param)
        throw BindingException("Request missing wresult parameter.");

    log.debug("decoded ADFS response:\n%s", param);

    // Parse and bind the document into an XMLObject.
    istringstream is(param);
    DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
        : XMLToolingConfig::getConfig().getParser()).parse(is);
    XercesJanitor<DOMDocument> janitor(doc);
    auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
    janitor.release();

    if (!XMLString::equals(xmlObject->getElementQName().getLocalPart(), RequestSecurityTokenResponse)) {
    	log.error("unrecognized root element on message: %s", xmlObject->getElementQName().toString().c_str());
        throw BindingException("Decoded message was not of the appropriate type.");
    }

    SchemaValidators.validate(xmlObject.get());

    // Skip policy step here, there's no security in the wrapper.
    // policy.evaluate(*xmlObject.get(), &genericRequest);

    return xmlObject.release();
}

void ADFSConsumer::implementProtocol(
    const Application& application,
    const HTTPRequest& httpRequest,
    HTTPResponse& httpResponse,
    SecurityPolicy& policy,
    const PropertySet*,
    const XMLObject& xmlObject
    ) const
{
    // Implementation of ADFS profile.
    m_log.debug("processing message against ADFS Passive Requester profile");

    // With ADFS, all the security comes from the assertion, which is two levels down in the message.

    const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
    if (!response || !response->hasChildren())
        throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");

    const Assertion* token = nullptr;
    for (vector<XMLObject*>::const_iterator xo = response->getUnknownXMLObjects().begin(); xo != response->getUnknownXMLObjects().end(); ++xo) {
    	// Look for the RequestedSecurityToken element.
    	if (XMLString::equals((*xo)->getElementQName().getLocalPart(), RequestedSecurityToken)) {
    	    response = dynamic_cast<const ElementProxy*>(*xo);
    	    if (!response || !response->hasChildren())
    	        throw FatalProfileException("Token wrapper element did not contain a security token.");
    	    token = dynamic_cast<const Assertion*>(response->getUnknownXMLObjects().front());
    	    if (!token || !token->getSignature())
    	        throw FatalProfileException("Incoming message did not contain a signed SAML assertion.");
    	    break;
    	}
    }

    // Extract message and issuer details from assertion.
    extractMessageDetails(*token, m_protocol.get(), policy);

    // Populate recipient as audience.
    const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
    policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);

    // Run the policy over the assertion. Handles replay, freshness, and
    // signature verification, assuming the relevant rules are configured,
    // along with condition enforcement.
    policy.evaluate(*token, &httpRequest);

    // If no security is in place now, we kick it.
    if (!policy.isAuthenticated())
        throw SecurityPolicyException("Unable to establish security of incoming assertion.");

    const saml1::NameIdentifier* saml1name=nullptr;
    const saml1::AuthenticationStatement* saml1statement=nullptr;
    const saml2::NameID* saml2name=nullptr;
    const saml2::AuthnStatement* saml2statement=nullptr;
    const XMLCh* authMethod=nullptr;
    const XMLCh* authInstant=nullptr;
    time_t now = time(nullptr), sessionExp = 0;
    const PropertySet* sessionProps = application.getPropertySet("Sessions");

    const saml1::Assertion* saml1token = dynamic_cast<const saml1::Assertion*>(token);
    if (saml1token) {
        // Now do profile validation to ensure we can use it for SSO.
        if (!saml1token->getConditions() || !saml1token->getConditions()->getNotBefore() || !saml1token->getConditions()->getNotOnOrAfter())
            throw FatalProfileException("Assertion did not contain time conditions.");
        else if (saml1token->getAuthenticationStatements().empty())
            throw FatalProfileException("Assertion did not contain an authentication statement.");

        // authnskew allows rejection of SSO if AuthnInstant is too old.
        pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);

        saml1statement = saml1token->getAuthenticationStatements().front();
        if (saml1statement->getAuthenticationInstant()) {
            if (saml1statement->getAuthenticationInstantEpoch() - XMLToolingConfig::getConfig().clock_skew_secs > now) {
                throw FatalProfileException("The login time at your identity provider was future-dated.");
            }
            else if (authnskew.first && authnskew.second && saml1statement->getAuthenticationInstantEpoch() <= now &&
                    (now - saml1statement->getAuthenticationInstantEpoch() > authnskew.second)) {
                throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the allowed limit.");
            }
        }
        else if (authnskew.first && authnskew.second) {
            throw FatalProfileException("Your identity provider did not supply a time of login, violating local policy.");
        }

        // Address checking.
        saml1::SubjectLocality* locality = saml1statement->getSubjectLocality();
        if (locality && locality->getIPAddress()) {
            auto_ptr_char ip(locality->getIPAddress());
            checkAddress(application, httpRequest, ip.get());
        }

        saml1name = saml1statement->getSubject()->getNameIdentifier();
        authMethod = saml1statement->getAuthenticationMethod();
        if (saml1statement->getAuthenticationInstant())
            authInstant = saml1statement->getAuthenticationInstant()->getRawData();

        // Session expiration.
        pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
        if (!lifetime.first || lifetime.second == 0)
            lifetime.second = 28800;
        sessionExp = now + lifetime.second;
    }
    else {
        const saml2::Assertion* saml2token = dynamic_cast<const saml2::Assertion*>(token);
        if (!saml2token)
            throw FatalProfileException("Incoming message did not contain a recognized type of SAML assertion.");

        // Now do profile validation to ensure we can use it for SSO.
        if (!saml2token->getConditions() || !saml2token->getConditions()->getNotBefore() || !saml2token->getConditions()->getNotOnOrAfter())
            throw FatalProfileException("Assertion did not contain time conditions.");
        else if (saml2token->getAuthnStatements().empty())
            throw FatalProfileException("Assertion did not contain an authentication statement.");

        // authnskew allows rejection of SSO if AuthnInstant is too old.
        pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);

        saml2statement = saml2token->getAuthnStatements().front();
        if (authnskew.first && authnskew.second &&
                saml2statement->getAuthnInstant() && (now - saml2statement->getAuthnInstantEpoch() > authnskew.second))
            throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");

        // Address checking.
        saml2::SubjectLocality* locality = saml2statement->getSubjectLocality();
        if (locality && locality->getAddress()) {
            auto_ptr_char ip(locality->getAddress());
            checkAddress(application, httpRequest, ip.get());
        }

        saml2name = saml2token->getSubject() ? saml2token->getSubject()->getNameID() : nullptr;
        if (saml2statement->getAuthnContext() && saml2statement->getAuthnContext()->getAuthnContextClassRef())
            authMethod = saml2statement->getAuthnContext()->getAuthnContextClassRef()->getReference();
        if (saml2statement->getAuthnInstant())
            authInstant = saml2statement->getAuthnInstant()->getRawData();

        // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
        sessionExp = saml2statement->getSessionNotOnOrAfter() ? saml2statement->getSessionNotOnOrAfterEpoch() : 0;
        pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
        if (!lifetime.first || lifetime.second == 0)
            lifetime.second = 28800;
        if (sessionExp == 0)
            sessionExp = now + lifetime.second;     // IdP says nothing, calulate based on SP.
        else
            sessionExp = min(sessionExp, now + lifetime.second);    // Use the lowest.
    }

    m_log.debug("ADFS profile processing completed successfully");

    // We've successfully "accepted" the SSO token.
    // To complete processing, we need to extract and resolve attributes and then create the session.

    // Normalize a SAML 1.x NameIdentifier...
    scoped_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : nullptr);
    if (saml1name) {
        nameid->setName(saml1name->getName());
        nameid->setFormat(saml1name->getFormat());
        nameid->setNameQualifier(saml1name->getNameQualifier());
    }

    // The context will handle deleting attributes and new tokens.
    vector<const Assertion*> tokens(1,token);
    scoped_ptr<ResolutionContext> ctx(
        resolveAttributes(
            application,
            &httpRequest,
            policy.getIssuerMetadata(),
            m_protocol.get(),
            nullptr,
            saml1name,
            saml1statement,
            (saml1name ? nameid.get() : saml2name),
            saml2statement,
            authMethod,
            nullptr,
            &tokens
            )
        );

    if (ctx.get()) {
        // Copy over any new tokens, but leave them in the context for cleanup.
        tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
    }

    string session_id;
    application.getServiceProvider().getSessionCache()->insert(
        session_id,
        application,
        httpRequest,
        httpResponse,
        sessionExp,
        entity,
        m_protocol.get(),
        (saml1name ? nameid.get() : saml2name),
        authInstant,
        nullptr,
        authMethod,
        nullptr,
        &tokens,
        ctx ? &ctx->getResolvedAttributes() : nullptr
        );

    scoped_ptr<LoginEvent> login_event(newLoginEvent(application, httpRequest));
    if (login_event) {
        login_event->m_sessionID = session_id.c_str();
        login_event->m_peer = entity;
        login_event->m_protocol = WSFED_NS;
        login_event->m_binding = WSFED_NS;
        login_event->m_saml1AuthnStatement = saml1statement;
        login_event->m_nameID = (saml1name ? nameid.get() : saml2name);
        login_event->m_saml2AuthnStatement = saml2statement;
        if (ctx)
            login_event->m_attributes = &ctx->getResolvedAttributes();
        application.getServiceProvider().getTransactionLog()->write(*login_event);
    }
}

#endif

pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
{
    // Normally we'd do notifications and session clearage here, but ADFS logout
    // is missing the needed request/response features, so we have to rely on
    // the IdP half to notify us back about the logout and do the work there.
    // Basically we have no way to tell in the Logout receiving handler whether
    // we initiated the logout or not.

    Session* session = nullptr;
    try {
        session = request.getSession(false, true, false);  // don't cache it and ignore all checks
        if (!session)
            return make_pair(false, 0L);

        // We only handle ADFS sessions.
        if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
            session->unlock();
            return make_pair(false, 0L);
        }
    }
    catch (std::exception& ex) {
        m_log.error("error accessing current session: %s", ex.what());
        return make_pair(false,0L);
    }

    if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
        // When out of process, we run natively.
        return doRequest(request.getApplication(), request, request, session);
    }
    else {
        // When not out of process, we remote the request.
        session->unlock();
        vector<string> headers(1,"Cookie");
        headers.push_back("User-Agent");
        DDF out,in = wrap(request, &headers);
        DDFJanitor jin(in), jout(out);
        out=request.getServiceProvider().getListenerService()->send(in);
        return unwrap(request, out);
    }
}

void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
{
#ifndef SHIBSP_LITE
    // Defer to base class for notifications
    if (in["notify"].integer() == 1)
        return LogoutHandler::receive(in, out);

    // Find application.
    const char* aid = in["application_id"].string();
    const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
    if (!app) {
        // Something's horribly wrong.
        m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
        throw ConfigurationException("Unable to locate application for logout, deleted?");
    }

    // Unpack the request.
    scoped_ptr<HTTPRequest> req(getRequest(in));

    // Set up a response shim.
    DDF ret(nullptr);
    DDFJanitor jout(ret);
    scoped_ptr<HTTPResponse> resp(getResponse(ret));

    Session* session = nullptr;
    try {
         session = app->getServiceProvider().getSessionCache()->find(*app, *req, nullptr, nullptr);
    }
    catch (std::exception& ex) {
        m_log.error("error accessing current session: %s", ex.what());
    }

    // With no session, we just skip the request and let it fall through to an empty struct return.
    if (session) {
        if (session->getEntityID()) {
            // Since we're remoted, the result should either be a throw, which we pass on,
            // a false/0 return, which we just return as an empty structure, or a response/redirect,
            // which we capture in the facade and send back.
            doRequest(*app, *req, *resp, session);
        }
        else {
            m_log.error("no issuing entityID found in session");
            session->unlock();
            app->getServiceProvider().getSessionCache()->remove(*app, *req, resp.get());
        }
    }
    out << ret;
#else
    throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
#endif
}

pair<bool,long> ADFSLogoutInitiator::doRequest(
    const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
    ) const
{
    Locker sessionLocker(session, false);

    // Do back channel notification.
    vector<string> sessions(1, session->getID());
    if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
#ifndef SHIBSP_LITE
        scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(application, &httpRequest, session));
        if (logout_event) {
            logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_PARTIAL;
            application.getServiceProvider().getTransactionLog()->write(*logout_event);
        }
#endif
        sessionLocker.assign();
        session = nullptr;
        application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
        return sendLogoutPage(application, httpRequest, httpResponse, "partial");
    }

#ifndef SHIBSP_LITE
    pair<bool,long> ret = make_pair(false, 0L);

    try {
        // With a session in hand, we can create a request message, if we can find a compatible endpoint.
        MetadataProvider* m = application.getMetadataProvider();
        Locker metadataLocker(m);
        MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
        pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
        if (!entity.first) {
            throw MetadataException(
                "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
                );
        }
        else if (!entity.second) {
            throw MetadataException(
                "Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
                );
        }

        const EndpointType* ep = EndpointManager<SingleLogoutService>(
            dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()
            ).getByBinding(m_binding.get());
        if (!ep) {
            throw MetadataException(
                "Unable to locate ADFS single logout service for identity provider ($entityID).",
                namedparams(1, "entityID", session->getEntityID())
                );
        }

        const char* returnloc = httpRequest.getParameter("return");
        if (returnloc)
            application.limitRedirect(httpRequest, returnloc);

        // Log the request.
        scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(application, &httpRequest, session));
        if (logout_event) {
            logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_UNKNOWN;
            application.getServiceProvider().getTransactionLog()->write(*logout_event);
        }

        auto_ptr_char dest(ep->getLocation());
        string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
        if (returnloc) {
            req += "&wreply=";
            if (*returnloc == '/') {
                string s(returnloc);
                httpRequest.absolutize(s);
                req += XMLToolingConfig::getConfig().getURLEncoder()->encode(s.c_str());
            }
            else {
                req += XMLToolingConfig::getConfig().getURLEncoder()->encode(returnloc);
            }
        }
        ret.second = httpResponse.sendRedirect(req.c_str());
        ret.first = true;

        if (session) {
            sessionLocker.assign();
            session = nullptr;
            application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
        }
    }
    catch (MetadataException& mex) {
        // Less noise for IdPs that don't support logout
        m_log.info("unable to issue ADFS logout request: %s", mex.what());
    }
    catch (std::exception& ex) {
        m_log.error("error issuing ADFS logout request: %s", ex.what());
    }

    return ret;
#else
    throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
#endif
}

pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
{
    // Defer to base class for front-channel loop first.
    // This won't initiate the loop, only continue/end it.
    pair<bool,long> ret = LogoutHandler::run(request, isHandler);
    if (ret.first)
        return ret;

    // wa parameter indicates the "action" to perform
    bool returning = false;
    const char* param = request.getParameter("wa");
    if (param) {
        if (!strcmp(param, "wsignin1.0"))
            return m_login.run(request, isHandler);
        else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
            throw FatalProfileException("Unsupported WS-Federation action parameter ($1).", params(1, param));
    }
    else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
        throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
    else
        returning = true;

    param = request.getParameter("wreply");
    const Application& app = request.getApplication();

    if (!returning) {
        // Pass control to the first front channel notification point, if any.
        map<string,string> parammap;
        if (param)
            parammap["wreply"] = param;
        pair<bool,long> result = notifyFrontChannel(app, request, request, &parammap);
        if (result.first)
            return result;
    }

    // Best effort on back channel and to remove the user agent's session.
    string session_id = app.getServiceProvider().getSessionCache()->active(app, request);
    if (!session_id.empty()) {
        vector<string> sessions(1,session_id);
        notifyBackChannel(app, request.getRequestURL(), sessions, false);
        try {
            app.getServiceProvider().getSessionCache()->remove(app, request, &request);
        }
        catch (std::exception& ex) {
            m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());
        }
    }

    if (param) {
        if (*param == '/') {
            string p(param);
            request.absolutize(p);
            return make_pair(true, request.sendRedirect(p.c_str()));
        }
        else {
            app.limitRedirect(request, param);
            return make_pair(true, request.sendRedirect(param));
        }
    }
    return sendLogoutPage(app, request, request, "global");
}