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