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