Add linefeeds to log, add logging of additional inbound messages.
[shibboleth/opensaml2.git] / saml / saml2 / binding / impl / SAML2RedirectEncoder.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  * SAML2RedirectEncoder.cpp
19  * 
20  * SAML 2.0 HTTP-POST binding message encoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/MessageEncoder.h"
26 #include "saml2/binding/SAML2Redirect.h"
27 #include "saml2/core/Protocols.h"
28
29 #include <fstream>
30 #include <sstream>
31 #include <xercesc/util/Base64.hpp>
32 #include <xmltooling/logging.h>
33 #include <xmltooling/io/HTTPResponse.h>
34 #include <xmltooling/util/NDC.h>
35 #include <xmltooling/util/URLEncoder.h>
36
37 using namespace opensaml::saml2p;
38 using namespace opensaml::saml2md;
39 using namespace opensaml;
40 using namespace xmlsignature;
41 using namespace xmltooling::logging;
42 using namespace xmltooling;
43 using namespace std;
44
45 namespace opensaml {
46     namespace saml2p {              
47         class SAML_DLLLOCAL SAML2RedirectEncoder : public MessageEncoder
48         {
49         public:
50             SAML2RedirectEncoder() {}
51             virtual ~SAML2RedirectEncoder() {}
52
53             bool isCompact() const {
54                 return true;
55             }
56             
57             long encode(
58                 GenericResponse& genericResponse,
59                 XMLObject* xmlObject,
60                 const char* destination,
61                 const EntityDescriptor* recipient=NULL,
62                 const char* relayState=NULL,
63                 const ArtifactGenerator* artifactGenerator=NULL,
64                 const Credential* credential=NULL,
65                 const XMLCh* signatureAlg=NULL,
66                 const XMLCh* digestAlg=NULL
67                 ) const;
68         };
69
70         MessageEncoder* SAML_DLLLOCAL SAML2RedirectEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
71         {
72             return new SAML2RedirectEncoder();
73         }
74     };
75 };
76
77 long SAML2RedirectEncoder::encode(
78     GenericResponse& genericResponse,
79     XMLObject* xmlObject,
80     const char* destination,
81     const EntityDescriptor* recipient,
82     const char* relayState,
83     const ArtifactGenerator* artifactGenerator,
84     const Credential* credential,
85     const XMLCh* signatureAlg,
86     const XMLCh* digestAlg
87     ) const
88 {
89 #ifdef _DEBUG
90     xmltooling::NDC ndc("encode");
91 #endif
92     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2Redirect");
93
94     log.debug("validating input");
95     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
96     if (!httpResponse)
97         throw BindingException("Unable to cast response interface to HTTPResponse type.");
98     if (xmlObject->getParent())
99         throw BindingException("Cannot encode XML content with parent.");
100     
101     StatusResponseType* response = NULL;
102     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
103     if (!request) {
104         response = dynamic_cast<StatusResponseType*>(xmlObject);
105         if (!response)
106             throw BindingException("XML content for SAML 2.0 HTTP-Redirect Encoder must be a SAML 2.0 protocol message.");
107     }
108     
109     // Check for XML signature.
110     if (request ? request->getSignature() : response->getSignature()) {
111         log.debug("message already signed, removing native signature due to size considerations");
112         request ? request->setSignature(NULL) : response->setSignature(NULL);
113     }
114     
115     log.debug("marshalling, deflating, base64-encoding the message");
116     DOMElement* rootElement = xmlObject->marshall();
117     string xmlbuf;
118     XMLHelper::serialize(rootElement, xmlbuf);
119     log.debug("marshalled message:\n%s", xmlbuf.c_str());
120     
121     unsigned int len;
122     char* deflated = deflate(const_cast<char*>(xmlbuf.c_str()), xmlbuf.length(), &len);
123     if (!deflated)
124         throw BindingException("Failed to deflate message.");
125     
126     XMLByte* encoded=Base64::encode(reinterpret_cast<XMLByte*>(deflated),len,&len);
127     delete[] deflated;
128     if (!encoded)
129         throw BindingException("Base64 encoding of XML failed.");
130     
131     // Create beginnings of redirect query string.
132     const URLEncoder* escaper = XMLToolingConfig::getConfig().getURLEncoder();
133     xmlbuf.erase();
134     xmlbuf.append(reinterpret_cast<char*>(encoded),len);
135     xmlbuf = (request ? "SAMLRequest=" : "SAMLResponse=") + escaper->encode(xmlbuf.c_str()); 
136     if (relayState && *relayState)
137         xmlbuf = xmlbuf + "&RelayState=" + escaper->encode(relayState);
138   
139     if (credential) {
140         log.debug("signing the message");
141         
142         // Sign the query string after adding the algorithm.
143         if (!signatureAlg)
144             signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
145         auto_ptr_char alg(signatureAlg);
146         xmlbuf = xmlbuf + "&SigAlg=" + escaper->encode(alg.get());
147
148         char sigbuf[1024];
149         memset(sigbuf,0,sizeof(sigbuf));
150         Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, xmlbuf.c_str(), xmlbuf.length(), sigbuf, sizeof(sigbuf)-1);
151         xmlbuf = xmlbuf + "&Signature=" + escaper->encode(sigbuf);
152     }
153     
154     // Generate redirect.
155     log.debug("message encoded, sending redirect to client");
156     xmlbuf.insert((string::size_type)0,(string::size_type)1,(strchr(destination,'?') ? '&' : '?'));
157     xmlbuf.insert(0,destination);
158     long ret = httpResponse->sendRedirect(xmlbuf.c_str());
159
160     // Cleanup by destroying XML.
161     delete xmlObject;
162     
163     return ret;
164 }