File: SAML2ArtifactDecoder.cpp

package info (click to toggle)
opensaml2 2.5.3-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 5,924 kB
  • sloc: cpp: 27,060; sh: 10,755; xml: 999; makefile: 439; ansic: 22
file content (178 lines) | stat: -rw-r--r-- 6,675 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
/**
 * 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.
 */

/**
 * SAML2ArtifactDecoder.cpp
 *
 * SAML 2.0 Artifact binding message decoder.
 */

#include "internal.h"
#include "exceptions.h"
#include "binding/SecurityPolicy.h"
#include "saml2/binding/SAML2Artifact.h"
#include "saml2/binding/SAML2MessageDecoder.h"
#include "saml2/core/Protocols.h"
#include "saml2/metadata/Metadata.h"
#include "saml2/metadata/MetadataProvider.h"

#include <boost/scoped_ptr.hpp>
#include <xmltooling/logging.h>
#include <xmltooling/XMLToolingConfig.h>
#include <xmltooling/io/HTTPRequest.h>
#include <xmltooling/util/NDC.h>
#include <xmltooling/util/ReplayCache.h>

using namespace opensaml::saml2md;
using namespace opensaml::saml2p;
using namespace opensaml::saml2;
using namespace opensaml;
using namespace xmltooling::logging;
using namespace xmltooling;
using namespace boost;
using namespace std;

namespace opensaml {
    namespace saml2p {
        class SAML_DLLLOCAL SAML2ArtifactDecoder : public SAML2MessageDecoder
        {
        public:
            SAML2ArtifactDecoder() {}
            virtual ~SAML2ArtifactDecoder() {}

            xmltooling::XMLObject* decode(
                std::string& relayState,
                const GenericRequest& genericRequest,
                SecurityPolicy& policy
                ) const;
        };

        MessageDecoder* SAML_DLLLOCAL SAML2ArtifactDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
        {
            return new SAML2ArtifactDecoder();
        }
    };
};

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

    log.debug("validating input");
    const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
    if (!httpRequest)
        throw BindingException("Unable to cast request object to HTTPRequest type.");
    const char* SAMLart = httpRequest->getParameter("SAMLart");
    if (!SAMLart)
        throw BindingException("Request missing SAMLart query string or form parameter.");
    const char* state = httpRequest->getParameter("RelayState");
    if (state)
        relayState = state;

    if (!m_artifactResolver || !policy.getMetadataProvider() || !policy.getRole())
        throw BindingException("Artifact binding requires ArtifactResolver and MetadataProvider implementations be supplied.");

    // Import the artifact.
    scoped_ptr<SAMLArtifact> artifact;
    try {
        log.debug("processing encoded artifact (%s)", SAMLart);

        // Check replay.
        ReplayCache* replayCache = XMLToolingConfig::getConfig().getReplayCache();
        if (replayCache) {
            if (!replayCache->check("SAML2Artifact", SAMLart, time(nullptr) + (2*XMLToolingConfig::getConfig().clock_skew_secs))) {
                log.error("replay detected of artifact (%s)", SAMLart);
                throw BindingException("Rejecting replayed artifact ($1).", params(1,SAMLart));
            }
        }
        else
            log.warn("replay cache was not provided, this is a serious security risk!");

        artifact.reset(SAMLArtifact::parse(SAMLart));
    }
    catch (ArtifactException&) {
        log.error("error parsing artifact (%s)", SAMLart);
        throw;
    }

    // Check the type.
    SAML2Artifact* artifact2 = dynamic_cast<SAML2Artifact*>(artifact.get());
    if (!artifact2) {
        log.error("wrong artifact type");
        throw BindingException("Artifact binding requires SAML 2.0 artifact.");
    }

    log.debug("attempting to determine source of artifact...");
    MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
    mc.artifact = artifact.get();
    mc.role = policy.getRole();
    mc.protocol = samlconstants::SAML20P_NS;
    pair<const EntityDescriptor*,const RoleDescriptor*> provider=policy.getMetadataProvider()->getEntityDescriptor(mc);
    if (!provider.first) {
        log.error(
            "metadata lookup failed, unable to determine issuer of artifact (0x%s)",
            SAMLArtifact::toHex(artifact->getBytes()).c_str()
            );
        throw BindingException("Metadata lookup failed, unable to determine artifact issuer.");
    }

    if (log.isDebugEnabled()) {
        auto_ptr_char issuer(provider.first->getEntityID());
        log.debug("lookup succeeded, artifact issued by (%s)", issuer.get());
    }

    if (!provider.second || !dynamic_cast<const SSODescriptorType*>(provider.second)) {
        log.error("unable to find compatible SAML 2.0 role (%s) in metadata", policy.getRole()->toString().c_str());
        throw BindingException("Unable to find compatible metadata role for artifact issuer.");
    }
    // Set issuer into policy.
    policy.setIssuer(provider.first->getEntityID());
    policy.setIssuerMetadata(provider.second);

    log.debug("calling ArtifactResolver...");
    auto_ptr<ArtifactResponse> response(
        m_artifactResolver->resolve(*artifact2, dynamic_cast<const SSODescriptorType&>(*provider.second), policy)
        );

    // The policy should be enforced against the ArtifactResponse by the resolve step.
    // Reset only the message state.
    policy.reset(true);

    // Now extract details from the payload and check that message.
    XMLObject* payload = response->getPayload();
    if (!payload) {
        log.error("ArtifactResponse message did not contain a protocol message");
        throw BindingException("ArtifactResponse message did not contain a protocol message.");
    }
    extractMessageDetails(*payload, genericRequest, samlconstants::SAML20P_NS, policy);
    policy.evaluate(*payload, &genericRequest);

    // Return the payload only.
    response.release();
    payload->detach();
    return payload;
}