Add linefeeds to log, add logging of additional inbound messages.
[shibboleth/opensaml2.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("Cache-Control", "no-cache, no-store, must-revalidate, private");
131         httpResponse->setResponseHeader("Pragma", "no-cache");
132     }
133
134     // Wrap it in a SOAP envelope.
135     Envelope* env = EnvelopeBuilder::buildEnvelope();
136     Header* header = HeaderBuilder::buildHeader();
137     env->setHeader(header);
138     Body* body = BodyBuilder::buildBody();
139     env->setBody(body);
140     body->getUnknownXMLObjects().push_back(xmlObject);
141
142     ElementProxy* hdrblock;
143     QName qMU(SOAP11ENV_NS, Header::MUSTUNDERSTAND_ATTRIB_NAME, SOAP11ENV_PREFIX);
144     QName qActor(SOAP11ENV_NS, Header::ACTOR_ATTRIB_NAME, SOAP11ENV_PREFIX);
145     
146     if (request) {
147         // Create paos:Request header.
148         static const XMLCh service[] = UNICODE_LITERAL_7(s,e,r,v,i,c,e);
149         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);
150         hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(PAOS_NS, saml1p::Request::LOCAL_NAME, PAOS_PREFIX));
151         hdrblock->setAttribute(qMU, XML_ONE);
152         hdrblock->setAttribute(qActor, m_actor.get());
153         hdrblock->setAttribute(QName(NULL, service), SAML20ECP_NS);
154         hdrblock->setAttribute(QName(NULL, responseConsumerURL), request->getAssertionConsumerServiceURL());
155         header->getUnknownXMLObjects().push_back(hdrblock);
156
157         // Create ecp:Request header.
158         static const XMLCh IsPassive[] = UNICODE_LITERAL_9(I,s,P,a,s,s,i,v,e);
159         hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(SAML20ECP_NS, saml1p::Request::LOCAL_NAME, SAML20ECP_PREFIX));
160         hdrblock->setAttribute(qMU, XML_ONE);
161         hdrblock->setAttribute(qActor, m_actor.get());
162         if (!request->IsPassive())
163             hdrblock->setAttribute(QName(NULL,IsPassive), XML_ZERO);
164         if (m_providerName)
165             hdrblock->setAttribute(QName(NULL,ProviderName), m_providerName);
166         hdrblock->getUnknownXMLObjects().push_back(request->getIssuer()->clone());
167         if (request->getScoping() && request->getScoping()->getIDPList())
168             hdrblock->getUnknownXMLObjects().push_back(request->getScoping()->getIDPList()->clone());
169         else if (m_idpList)
170             hdrblock->getUnknownXMLObjects().push_back(m_idpList->clone());
171         header->getUnknownXMLObjects().push_back(hdrblock);
172     }
173     else {
174         // Create ecp:Response header.
175         hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(SAML20ECP_NS, Response::LOCAL_NAME, SAML20ECP_PREFIX));
176         hdrblock->setAttribute(qMU, XML_ONE);
177         hdrblock->setAttribute(qActor, m_actor.get());
178         hdrblock->setAttribute(QName(NULL,AuthnRequest::ASSERTIONCONSUMERSERVICEURL_ATTRIB_NAME), response->getDestination());
179         header->getUnknownXMLObjects().push_back(hdrblock);
180     }
181     
182     if (relayState) {
183         // Create ecp:RelayState header.
184         static const XMLCh RelayState[] = UNICODE_LITERAL_10(R,e,l,a,y,S,t,a,t,e);
185         hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(SAML20ECP_NS, RelayState, SAML20ECP_PREFIX));
186         hdrblock->setAttribute(qMU, XML_ONE);
187         hdrblock->setAttribute(qActor, m_actor.get());
188         auto_ptr_XMLCh rs(relayState);
189         hdrblock->setTextContent(rs.get());
190         header->getUnknownXMLObjects().push_back(hdrblock);
191     }
192     
193     try {
194         DOMElement* rootElement = NULL;
195         if (credential) {
196             if (request->getSignature()) {
197                 log.debug("message already signed, skipping signature operation");
198                 rootElement = env->marshall();
199             }
200             else {
201                 log.debug("signing the message and marshalling the envelope");
202     
203                 // Build a Signature.
204                 Signature* sig = SignatureBuilder::buildSignature();
205                 request->setSignature(sig);    
206                 if (signatureAlg)
207                     sig->setSignatureAlgorithm(signatureAlg);
208                 if (digestAlg) {
209                     opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
210                     if (cr)
211                         cr->setDigestAlgorithm(digestAlg);
212                 }
213         
214                 // Sign message while marshalling.
215                 vector<Signature*> sigs(1,sig);
216                 rootElement = env->marshall((DOMDocument*)NULL,&sigs,credential);
217             }
218         }
219         else {
220             log.debug("marshalling the envelope");
221             rootElement = env->marshall();
222         }
223
224         stringstream s;
225         s << *rootElement;
226         
227         if (log.isDebugEnabled())
228             log.debug("marshalled envelope:\n%s", s.str().c_str());
229
230         log.debug("sending serialized envelope");
231         long ret = genericResponse.sendResponse(s);
232     
233         // Cleanup by destroying XML.
234         delete env;
235         return ret;
236     }
237     catch (XMLToolingException&) {
238         // A bit weird...we have to "revert" things so that the message is isolated
239         // so the caller can free it.
240         xmlObject->getParent()->detach();
241         xmlObject->detach();
242         throw;
243     }
244 }