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