f2e8d19ae6731bb2b3da0f1d41a5c9cf9475fb12
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2ECPEncoder.cpp
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 "binding/MessageEncoder.h"
30 #include "signature/ContentReference.h"
31 #include "saml1/core/Protocols.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 namespace opensaml {
54     namespace saml2p {              
55         
56         static const XMLCh ProviderName[] = UNICODE_LITERAL_12(P,r,o,v,i,d,e,r,N,a,m,e);
57
58         class SAML_DLLLOCAL SAML2ECPEncoder : public MessageEncoder
59         {
60         public:
61             SAML2ECPEncoder(const DOMElement* e, const XMLCh* ns) : m_actor("http://schemas.xmlsoap.org/soap/actor/next"),
62                     m_providerName(e ? e->getAttributeNS(ns, ProviderName) : nullptr), m_idpList(nullptr) {
63                 DOMElement* child = e ? XMLHelper::getFirstChildElement(e, SAML20P_NS, IDPList::LOCAL_NAME) : nullptr;
64                 if (child)
65                     m_idpList = dynamic_cast<IDPList*>(XMLObjectBuilder::buildOneFromElement(child));
66             }
67             virtual ~SAML2ECPEncoder() {
68                 delete m_idpList;
69             }
70
71             const XMLCh* getProtocolFamily() const {
72                 return samlconstants::SAML20P_NS;
73             }
74
75             long encode(
76                 GenericResponse& genericResponse,
77                 XMLObject* xmlObject,
78                 const char* destination,
79                 const EntityDescriptor* recipient=nullptr,
80                 const char* relayState=nullptr,
81                 const ArtifactGenerator* artifactGenerator=nullptr,
82                 const Credential* credential=nullptr,
83                 const XMLCh* signatureAlg=nullptr,
84                 const XMLCh* digestAlg=nullptr
85                 ) const;
86             
87         private:
88             auto_ptr_XMLCh m_actor;
89             const XMLCh* m_providerName;
90             IDPList* m_idpList;
91             AnyElementBuilder m_anyBuilder;
92         };
93
94         MessageEncoder* SAML_DLLLOCAL SAML2ECPEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
95         {
96             return new SAML2ECPEncoder(p.first, p.second);
97         }
98     };
99 };
100
101 long SAML2ECPEncoder::encode(
102     GenericResponse& genericResponse,
103     XMLObject* xmlObject,
104     const char* destination,
105     const EntityDescriptor* recipient,
106     const char* relayState,
107     const ArtifactGenerator* artifactGenerator,
108     const Credential* credential,
109     const XMLCh* signatureAlg,
110     const XMLCh* digestAlg
111     ) const
112 {
113 #ifdef _DEBUG
114     xmltooling::NDC ndc("encode");
115 #endif
116     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2ECP");
117
118     log.debug("validating input");
119     if (xmlObject->getParent())
120         throw BindingException("Cannot encode XML content with parent.");
121
122     Response* response = nullptr;
123     AuthnRequest* request = dynamic_cast<AuthnRequest*>(xmlObject);
124     if (!request) {
125         response = dynamic_cast<Response*>(xmlObject);
126         if (!response)
127             throw BindingException("XML content for SAML 2.0 ECP Encoder must be a SAML 2.0 AuthnRequest or Response.");
128     }
129     
130     if (request && !request->getAssertionConsumerServiceURL())
131         throw BindingException("AuthnRequest must carry an AssertionConsumerServiceURL by value.");
132     else if (response && !response->getDestination())
133         throw BindingException("Response must carry a Destination attribute.");
134     
135     // PAOS request leg is a custom MIME type, SOAP response leg is just text/xml.
136     genericResponse.setContentType(request ? "application/vnd.paos+xml" : "text/xml");
137     HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
138     if (httpResponse) {
139         httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
140         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
141         httpResponse->setResponseHeader("Pragma", "no-cache");
142     }
143
144     // Wrap it in a SOAP envelope.
145     Envelope* env = EnvelopeBuilder::buildEnvelope();
146     Header* header = HeaderBuilder::buildHeader();
147     env->setHeader(header);
148     Body* body = BodyBuilder::buildBody();
149     env->setBody(body);
150     body->getUnknownXMLObjects().push_back(xmlObject);
151
152     ElementProxy* hdrblock;
153     xmltooling::QName qMU(SOAP11ENV_NS, Header::MUSTUNDERSTAND_ATTRIB_NAME, SOAP11ENV_PREFIX);
154     xmltooling::QName qActor(SOAP11ENV_NS, Header::ACTOR_ATTRIB_NAME, SOAP11ENV_PREFIX);
155     
156     if (request) {
157         // Create paos:Request header.
158         static const XMLCh service[] = UNICODE_LITERAL_7(s,e,r,v,i,c,e);
159         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);
160         hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(PAOS_NS, saml1p::Request::LOCAL_NAME, PAOS_PREFIX));
161         hdrblock->setAttribute(qMU, XML_ONE);
162         hdrblock->setAttribute(qActor, m_actor.get());
163         hdrblock->setAttribute(xmltooling::QName(nullptr, service), SAML20ECP_NS);
164         hdrblock->setAttribute(xmltooling::QName(nullptr, responseConsumerURL), request->getAssertionConsumerServiceURL());
165         header->getUnknownXMLObjects().push_back(hdrblock);
166
167         // Create ecp:Request header.
168         static const XMLCh IsPassive[] = UNICODE_LITERAL_9(I,s,P,a,s,s,i,v,e);
169         hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(SAML20ECP_NS, saml1p::Request::LOCAL_NAME, SAML20ECP_PREFIX));
170         hdrblock->setAttribute(qMU, XML_ONE);
171         hdrblock->setAttribute(qActor, m_actor.get());
172         if (!request->IsPassive())
173             hdrblock->setAttribute(xmltooling::QName(nullptr,IsPassive), XML_ZERO);
174         if (m_providerName)
175             hdrblock->setAttribute(xmltooling::QName(nullptr,ProviderName), m_providerName);
176         hdrblock->getUnknownXMLObjects().push_back(request->getIssuer()->clone());
177         if (request->getScoping() && request->getScoping()->getIDPList())
178             hdrblock->getUnknownXMLObjects().push_back(request->getScoping()->getIDPList()->clone());
179         else if (m_idpList)
180             hdrblock->getUnknownXMLObjects().push_back(m_idpList->clone());
181         header->getUnknownXMLObjects().push_back(hdrblock);
182     }
183     else {
184         // Create ecp:Response header.
185         hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(SAML20ECP_NS, Response::LOCAL_NAME, SAML20ECP_PREFIX));
186         hdrblock->setAttribute(qMU, XML_ONE);
187         hdrblock->setAttribute(qActor, m_actor.get());
188         hdrblock->setAttribute(xmltooling::QName(nullptr,AuthnRequest::ASSERTIONCONSUMERSERVICEURL_ATTRIB_NAME), response->getDestination());
189         header->getUnknownXMLObjects().push_back(hdrblock);
190     }
191     
192     if (relayState && *relayState) {
193         // Create ecp:RelayState header.
194         static const XMLCh RelayState[] = UNICODE_LITERAL_10(R,e,l,a,y,S,t,a,t,e);
195         hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(SAML20ECP_NS, RelayState, SAML20ECP_PREFIX));
196         hdrblock->setAttribute(qMU, XML_ONE);
197         hdrblock->setAttribute(qActor, m_actor.get());
198         auto_ptr_XMLCh rs(relayState);
199         hdrblock->setTextContent(rs.get());
200         header->getUnknownXMLObjects().push_back(hdrblock);
201     }
202     
203     try {
204         DOMElement* rootElement = nullptr;
205         if (credential) {
206             if (request->getSignature()) {
207                 log.debug("message already signed, skipping signature operation");
208                 rootElement = env->marshall();
209             }
210             else {
211                 log.debug("signing the message and marshalling the envelope");
212     
213                 // Build a Signature.
214                 Signature* sig = SignatureBuilder::buildSignature();
215                 request->setSignature(sig);    
216                 if (signatureAlg)
217                     sig->setSignatureAlgorithm(signatureAlg);
218                 if (digestAlg) {
219                     opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
220                     if (cr)
221                         cr->setDigestAlgorithm(digestAlg);
222                 }
223         
224                 // Sign message while marshalling.
225                 vector<Signature*> sigs(1,sig);
226                 rootElement = env->marshall((DOMDocument*)nullptr,&sigs,credential);
227             }
228         }
229         else {
230             log.debug("marshalling the envelope");
231             rootElement = env->marshall();
232         }
233
234         stringstream s;
235         s << *rootElement;
236         
237         if (log.isDebugEnabled()) {
238             string forlog(s.str());
239             log.debug("marshalled envelope:\n%s", forlog.c_str());
240         }
241
242         log.debug("sending serialized envelope");
243         long ret = genericResponse.sendResponse(s);
244     
245         // Cleanup by destroying XML.
246         delete env;
247         return ret;
248     }
249     catch (XMLToolingException&) {
250         // A bit weird...we have to "revert" things so that the message is isolated
251         // so the caller can free it.
252         xmlObject->getParent()->detach();
253         xmlObject->detach();
254         throw;
255     }
256 }