1 /**
2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
6 *
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
10 * License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
19 */
20
21 /**
22 * SAML2ECPEncoder.cpp
23 *
24 * SAML 2.0 ECP profile message encoder.
25 */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "signature/ContentReference.h"
30 #include "saml1/core/Protocols.h"
31 #include "saml2/binding/SAML2MessageEncoder.h"
32 #include "saml2/core/Protocols.h"
33
34 #include <sstream>
35 #include <xmltooling/logging.h>
36 #include <xmltooling/impl/AnyElement.h>
37 #include <xmltooling/io/HTTPResponse.h>
38 #include <xmltooling/util/NDC.h>
39 #include <xmltooling/signature/Signature.h>
40 #include <xmltooling/soap/SOAP.h>
41
42 using namespace samlconstants;
43 using namespace opensaml::saml2p;
44 using namespace opensaml::saml2md;
45 using namespace opensaml;
46 using namespace xmlconstants;
47 using namespace xmlsignature;
48 using namespace soap11;
49 using namespace xmltooling::logging;
50 using namespace xmltooling;
51 using namespace std;
52
53 using boost::scoped_ptr;
54
55 namespace opensaml {
56 namespace saml2p {
57
58 static const XMLCh ProviderName[] = UNICODE_LITERAL_12(P, r, o, v, i, d, e, r, N, a, m, e);
59
60 class SAML_DLLLOCAL SAML2ECPEncoder : public SAML2MessageEncoder
61 {
62 public:
63 SAML2ECPEncoder(const DOMElement* e);
~SAML2ECPEncoder()64 virtual ~SAML2ECPEncoder() {}
65
66 long encode(
67 GenericResponse& genericResponse,
68 XMLObject* xmlObject,
69 const char* destination,
70 const EntityDescriptor* recipient=nullptr,
71 const char* relayState=nullptr,
72 const ArtifactGenerator* artifactGenerator=nullptr,
73 const Credential* credential=nullptr,
74 const XMLCh* signatureAlg=nullptr,
75 const XMLCh* digestAlg=nullptr
76 ) const;
77
78 private:
79 auto_ptr_XMLCh m_actor;
80 const XMLCh* m_providerName;
81 scoped_ptr<IDPList> m_idpList;
82 AnyElementBuilder m_anyBuilder;
83 };
84
SAML2ECPEncoderFactory(const DOMElement * const & e,bool)85 MessageEncoder* SAML_DLLLOCAL SAML2ECPEncoderFactory(const DOMElement* const & e, bool)
86 {
87 return new SAML2ECPEncoder(e);
88 }
89 };
90 };
91
SAML2ECPEncoder(const DOMElement * e)92 SAML2ECPEncoder::SAML2ECPEncoder(const DOMElement* e)
93 : m_actor("http://schemas.xmlsoap.org/soap/actor/next"), m_providerName(nullptr) {
94
95 // Fishy alert: we ignore the namespace and look for a matching DOM Attr node by name only.
96 // Can't use DOM 1 calls, so we have to walk the attribute list by hand.
97
98 const DOMNamedNodeMap* attributes = e ? e->getAttributes() : nullptr;
99 XMLSize_t size = attributes ? attributes->getLength() : 0;
100 for (XMLSize_t i = 0; i < size; ++i) {
101 const DOMNode* attr = attributes->item(i);
102 if (XMLString::equals(attr->getLocalName(), ProviderName)) {
103 m_providerName = attr->getNodeValue();
104 }
105 }
106
107 DOMElement* child = e ? XMLHelper::getFirstChildElement(e, SAML20P_NS, IDPList::LOCAL_NAME) : nullptr;
108 if (child)
109 m_idpList.reset(dynamic_cast<IDPList*>(XMLObjectBuilder::buildOneFromElement(child)));
110 }
111
encode(GenericResponse & genericResponse,XMLObject * xmlObject,const char * destination,const EntityDescriptor * recipient,const char * relayState,const ArtifactGenerator * artifactGenerator,const Credential * credential,const XMLCh * signatureAlg,const XMLCh * digestAlg) const112 long SAML2ECPEncoder::encode(
113 GenericResponse& genericResponse,
114 XMLObject* xmlObject,
115 const char* destination,
116 const EntityDescriptor* recipient,
117 const char* relayState,
118 const ArtifactGenerator* artifactGenerator,
119 const Credential* credential,
120 const XMLCh* signatureAlg,
121 const XMLCh* digestAlg
122 ) const
123 {
124 #ifdef _DEBUG
125 xmltooling::NDC ndc("encode");
126 #endif
127 Category& log = Category::getInstance(SAML_LOGCAT ".MessageEncoder.SAML2ECP");
128
129 log.debug("validating input");
130 if (xmlObject->getParent())
131 throw BindingException("Cannot encode XML content with parent.");
132
133 Response* response = nullptr;
134 AuthnRequest* request = dynamic_cast<AuthnRequest*>(xmlObject);
135 if (!request) {
136 response = dynamic_cast<Response*>(xmlObject);
137 if (!response)
138 throw BindingException("XML content for SAML 2.0 ECP Encoder must be a SAML 2.0 AuthnRequest or Response.");
139 }
140
141 if (request && !request->getAssertionConsumerServiceURL())
142 throw BindingException("AuthnRequest must carry an AssertionConsumerServiceURL by value.");
143 else if (response && !response->getDestination())
144 throw BindingException("Response must carry a Destination attribute.");
145
146 // PAOS request leg is a custom MIME type, SOAP response leg is just text/xml.
147 genericResponse.setContentType(request ? "application/vnd.paos+xml" : "text/xml");
148 HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
149 if (httpResponse) {
150 httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
151 httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
152 httpResponse->setResponseHeader("Pragma", "no-cache");
153 if (request) {
154 preserveCorrelationID(*httpResponse, *request, relayState);
155 }
156 }
157
158 // Wrap it in a SOAP envelope.
159 Envelope* env = EnvelopeBuilder::buildEnvelope();
160 Header* header = HeaderBuilder::buildHeader();
161 env->setHeader(header);
162 Body* body = BodyBuilder::buildBody();
163 env->setBody(body);
164 body->getUnknownXMLObjects().push_back(xmlObject);
165
166 ElementProxy* hdrblock;
167 xmltooling::QName qMU(SOAP11ENV_NS, Header::MUSTUNDERSTAND_ATTRIB_NAME, SOAP11ENV_PREFIX);
168 xmltooling::QName qActor(SOAP11ENV_NS, Header::ACTOR_ATTRIB_NAME, SOAP11ENV_PREFIX);
169
170 if (request) {
171 // Create paos:Request header.
172 static const XMLCh service[] = UNICODE_LITERAL_7(s,e,r,v,i,c,e);
173 static const XMLCh responseConsumerURL[] = UNICODE_LITERAL_19(r,e,s,p,o,n,s,e,C,o,n,s,u,m,e,r,U,R,L);
174 hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(PAOS_NS, saml1p::Request::LOCAL_NAME, PAOS_PREFIX));
175 hdrblock->setAttribute(qMU, XML_ONE);
176 hdrblock->setAttribute(qActor, m_actor.get());
177 hdrblock->setAttribute(xmltooling::QName(nullptr, service), SAML20ECP_NS);
178 hdrblock->setAttribute(xmltooling::QName(nullptr, responseConsumerURL), request->getAssertionConsumerServiceURL());
179 header->getUnknownXMLObjects().push_back(hdrblock);
180
181 // Create ecp:Request header.
182 static const XMLCh IsPassive[] = UNICODE_LITERAL_9(I,s,P,a,s,s,i,v,e);
183 hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(SAML20ECP_NS, saml1p::Request::LOCAL_NAME, SAML20ECP_PREFIX));
184 hdrblock->setAttribute(qMU, XML_ONE);
185 hdrblock->setAttribute(qActor, m_actor.get());
186 if (!request->IsPassive())
187 hdrblock->setAttribute(xmltooling::QName(nullptr,IsPassive), XML_ZERO);
188 if (m_providerName)
189 hdrblock->setAttribute(xmltooling::QName(nullptr,ProviderName), m_providerName);
190 hdrblock->getUnknownXMLObjects().push_back(request->getIssuer()->clone());
191 if (request->getScoping() && request->getScoping()->getIDPList())
192 hdrblock->getUnknownXMLObjects().push_back(request->getScoping()->getIDPList()->clone());
193 else if (m_idpList.get())
194 hdrblock->getUnknownXMLObjects().push_back(m_idpList->clone());
195 header->getUnknownXMLObjects().push_back(hdrblock);
196 }
197 else {
198 // Create ecp:Response header.
199 hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(SAML20ECP_NS, Response::LOCAL_NAME, SAML20ECP_PREFIX));
200 hdrblock->setAttribute(qMU, XML_ONE);
201 hdrblock->setAttribute(qActor, m_actor.get());
202 hdrblock->setAttribute(xmltooling::QName(nullptr,AuthnRequest::ASSERTIONCONSUMERSERVICEURL_ATTRIB_NAME), response->getDestination());
203 header->getUnknownXMLObjects().push_back(hdrblock);
204 }
205
206 if (relayState && *relayState) {
207 // Create ecp:RelayState header.
208 static const XMLCh RelayState[] = UNICODE_LITERAL_10(R,e,l,a,y,S,t,a,t,e);
209 hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(SAML20ECP_NS, RelayState, SAML20ECP_PREFIX));
210 hdrblock->setAttribute(qMU, XML_ONE);
211 hdrblock->setAttribute(qActor, m_actor.get());
212 auto_ptr_XMLCh rs(relayState);
213 hdrblock->setTextContent(rs.get());
214 header->getUnknownXMLObjects().push_back(hdrblock);
215 }
216
217 try {
218 DOMElement* rootElement = nullptr;
219 if (credential) {
220 if (request->getSignature()) {
221 log.debug("message already signed, skipping signature operation");
222 rootElement = env->marshall();
223 }
224 else {
225 log.debug("signing the message and marshalling the envelope");
226
227 // Build a Signature.
228 Signature* sig = SignatureBuilder::buildSignature();
229 request->setSignature(sig);
230 if (signatureAlg)
231 sig->setSignatureAlgorithm(signatureAlg);
232 if (digestAlg) {
233 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
234 if (cr)
235 cr->setDigestAlgorithm(digestAlg);
236 }
237
238 // Sign message while marshalling.
239 vector<Signature*> sigs(1,sig);
240 rootElement = env->marshall((DOMDocument*)nullptr,&sigs,credential);
241 }
242 }
243 else {
244 log.debug("marshalling the envelope");
245 rootElement = env->marshall();
246 }
247
248 stringstream s;
249 s << *rootElement;
250
251 if (log.isDebugEnabled()) {
252 string forlog(s.str());
253 log.debug("marshalled envelope:\n%s", forlog.c_str());
254 }
255
256 log.debug("sending serialized envelope");
257 long ret = genericResponse.sendResponse(s);
258
259 // Cleanup by destroying XML.
260 delete env;
261 return ret;
262 }
263 catch (XMLToolingException&) {
264 // A bit weird...we have to "revert" things so that the message is isolated
265 // so the caller can free it.
266 xmlObject->getParent()->detach();
267 xmlObject->detach();
268 throw;
269 }
270 }
271