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