Settable digest algorithm, enhanced prefix handling in signatures, pending xmlsec...
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2SOAPEncoder.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  * SAML2SOAPEncoder.cpp
19  * 
20  * SAML 2.0 SOAP binding message encoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/HTTPResponse.h"
26 #include "binding/MessageEncoder.h"
27 #include "signature/ContentReference.h"
28 #include "saml2/core/Protocols.h"
29
30 #include <sstream>
31 #include <log4cpp/Category.hh>
32 #include <xmltooling/util/NDC.h>
33 #include <xmltooling/soap/SOAP.h>
34
35 using namespace opensaml::saml2p;
36 using namespace opensaml;
37 using namespace xmlsignature;
38 using namespace soap11;
39 using namespace xmltooling;
40 using namespace log4cpp;
41 using namespace std;
42
43 namespace opensaml {
44     namespace saml2p {              
45         class SAML_DLLLOCAL SAML2SOAPEncoder : public MessageEncoder
46         {
47         public:
48             SAML2SOAPEncoder(const DOMElement* e);
49             virtual ~SAML2SOAPEncoder() {}
50             
51             long encode(
52                 GenericResponse& genericResponse,
53                 XMLObject* xmlObject,
54                 const char* destination,
55                 const char* recipientID=NULL,
56                 const char* relayState=NULL,
57                 const Credential* credential=NULL,
58                 const XMLCh* signatureAlg=NULL,
59                 const XMLCh* digestAlg=NULL
60                 ) const;
61         };
62
63         MessageEncoder* SAML_DLLLOCAL SAML2SOAPEncoderFactory(const DOMElement* const & e)
64         {
65             return new SAML2SOAPEncoder(e);
66         }
67     };
68 };
69
70 SAML2SOAPEncoder::SAML2SOAPEncoder(const DOMElement* e) {}
71
72 long SAML2SOAPEncoder::encode(
73     GenericResponse& genericResponse,
74     XMLObject* xmlObject,
75     const char* destination,
76     const char* recipientID,
77     const char* relayState,
78     const Credential* credential,
79     const XMLCh* signatureAlg,
80     const XMLCh* digestAlg
81     ) const
82 {
83 #ifdef _DEBUG
84     xmltooling::NDC ndc("encode");
85 #endif
86     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2SOAP");
87
88     log.debug("validating input");
89     if (xmlObject->getParent())
90         throw BindingException("Cannot encode XML content with parent.");
91
92     genericResponse.setContentType("text/xml");
93     HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
94     if (httpResponse) {
95         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
96         httpResponse->setResponseHeader("Pragma", "no-cache");
97     }
98
99     DOMElement* rootElement = NULL;
100     StatusResponseType* response = dynamic_cast<StatusResponseType*>(xmlObject);
101     if (response) {
102         try {
103             Envelope* env = EnvelopeBuilder::buildEnvelope();
104             Body* body = BodyBuilder::buildBody();
105             env->setBody(body);
106             body->getUnknownXMLObjects().push_back(response);
107             if (credential) {
108                 if (response->getSignature()) {
109                     log.debug("response already signed, skipping signature operation");
110                     rootElement = env->marshall();
111                 }
112                 else {
113                     log.debug("signing and marshalling the response");
114         
115                     // Build a Signature.
116                     Signature* sig = SignatureBuilder::buildSignature();
117                     response->setSignature(sig);    
118                     if (signatureAlg)
119                         sig->setSignatureAlgorithm(signatureAlg);
120                     if (digestAlg) {
121                         opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
122                         if (cr)
123                             cr->setDigestAlgorithm(digestAlg);
124                     }
125             
126                     // Sign response while marshalling.
127                     vector<Signature*> sigs(1,sig);
128                     rootElement = env->marshall((DOMDocument*)NULL,&sigs,credential);
129                 }
130             }
131             else {
132                 log.debug("marshalling the response");
133                 rootElement = env->marshall();
134             }
135             
136             stringstream s;
137             s << *rootElement;
138             log.debug("sending serialized response");
139             long ret = genericResponse.sendResponse(s);
140         
141             // Cleanup by destroying XML.
142             delete env;
143             return ret;
144         }
145         catch (XMLToolingException&) {
146             // A bit weird...we have to "revert" things so that the response is isolated
147             // so the caller can free it.
148             if (response->getParent()) {
149                 response->getParent()->detach();
150                 response->detach();
151             }
152             throw;
153         }
154     }
155
156     Fault* fault = dynamic_cast<Fault*>(xmlObject);
157     if (fault) {
158         try {
159             log.debug("building Envelope and marshalling Fault");
160             Envelope* env = EnvelopeBuilder::buildEnvelope();
161             Body* body = BodyBuilder::buildBody();
162             env->setBody(body);
163             body->getUnknownXMLObjects().push_back(fault);
164             rootElement = env->marshall();
165     
166             string xmlbuf;
167             XMLHelper::serialize(rootElement, xmlbuf);
168             istringstream s(xmlbuf);
169             log.debug("sending serialized fault");
170             long ret = genericResponse.sendError(s);
171         
172             // Cleanup by destroying XML.
173             delete env;
174             return ret;
175         }
176         catch (XMLToolingException&) {
177             // A bit weird...we have to "revert" things so that the fault is isolated
178             // so the caller can free it.
179             if (fault->getParent()) {
180                 fault->getParent()->detach();
181                 fault->detach();
182             }
183             throw;
184         }
185     }
186
187     Envelope* env = dynamic_cast<Envelope*>(xmlObject);
188     if (env) {
189         log.debug("marshalling envelope");
190         rootElement = env->marshall();
191
192         bool error =
193             (env->getBody() &&
194                 env->getBody()->hasChildren() &&
195                     dynamic_cast<Fault*>(env->getBody()->getUnknownXMLObjects().front()));
196
197         string xmlbuf;
198         XMLHelper::serialize(rootElement, xmlbuf);
199         istringstream s(xmlbuf);
200         log.debug("sending serialized envelope");
201         long ret = error ? genericResponse.sendError(s) : genericResponse.sendResponse(s);
202     
203         // Cleanup by destroying XML.
204         delete env;
205         return ret;
206     }
207
208     throw BindingException("XML content for SAML 2.0 SOAP Encoder must be a SAML 2.0 response or SOAP Fault/Envelope.");
209 }