Reducing header overuse, non-inlining selected methods (CPPOST-35).
[shibboleth/cpp-opensaml.git] / saml / binding / impl / SimpleSigningRule.cpp
1 /*
2  *  Copyright 2001-2009 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  * SimpleSigningRule.cpp
19  * 
20  * Blob-oriented signature checking SecurityPolicyRule.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/SecurityPolicy.h"
26 #include "binding/SecurityPolicyRule.h"
27 #include "saml2/core/Assertions.h"
28 #include "saml2/metadata/Metadata.h"
29 #include "saml2/metadata/MetadataCredentialCriteria.h"
30 #include "saml2/metadata/MetadataProvider.h"
31
32 #include <xercesc/util/Base64.hpp>
33 #include <xmltooling/logging.h>
34 #include <xmltooling/XMLToolingConfig.h>
35 #include <xmltooling/io/HTTPRequest.h>
36 #include <xmltooling/security/SignatureTrustEngine.h>
37 #include <xmltooling/signature/KeyInfo.h>
38 #include <xmltooling/signature/Signature.h>
39
40 using namespace opensaml::saml2md;
41 using namespace opensaml;
42 using namespace xmltooling::logging;
43 using namespace xmltooling;
44 using namespace std;
45
46 using xmlsignature::KeyInfo;
47 using xmlsignature::SignatureException;
48
49 namespace opensaml {
50     class SAML_DLLLOCAL SimpleSigningRule : public SecurityPolicyRule
51     {
52     public:
53         SimpleSigningRule(const DOMElement* e);
54         virtual ~SimpleSigningRule() {}
55         
56         const char* getType() const {
57             return SIMPLESIGNING_POLICY_RULE;
58         }
59         bool evaluate(const XMLObject& message, const GenericRequest* request, SecurityPolicy& policy) const;
60
61     private:
62         // Appends a raw parameter=value pair to the string.
63         static bool appendParameter(string& s, const char* data, const char* name);
64
65         bool m_errorFatal;
66     };
67
68     SecurityPolicyRule* SAML_DLLLOCAL SimpleSigningRuleFactory(const DOMElement* const & e)
69     {
70         return new SimpleSigningRule(e);
71     }
72
73     static const XMLCh errorFatal[] = UNICODE_LITERAL_10(e,r,r,o,r,F,a,t,a,l);
74 };
75
76 bool SimpleSigningRule::appendParameter(string& s, const char* data, const char* name)
77 {
78     const char* start = strstr(data,name);
79     if (!start)
80         return false;
81     if (!s.empty())
82         s += '&';
83     const char* end = strchr(start,'&');
84     if (end)
85         s.append(start, end-start);
86     else
87         s.append(start);
88     return true;
89 }
90
91 SimpleSigningRule::SimpleSigningRule(const DOMElement* e) : m_errorFatal(false)
92 {
93     if (e) {
94         const XMLCh* flag = e->getAttributeNS(NULL, errorFatal);
95         m_errorFatal = (flag && (*flag==chLatin_t || *flag==chDigit_1)); 
96     }
97 }
98
99 bool SimpleSigningRule::evaluate(const XMLObject& message, const GenericRequest* request, SecurityPolicy& policy) const
100 {
101     Category& log=Category::getInstance(SAML_LOGCAT".SecurityPolicyRule.SimpleSigning");
102     
103     if (!policy.getIssuerMetadata()) {
104         log.debug("ignoring message, no issuer metadata supplied");
105         return false;
106     }
107
108     const SignatureTrustEngine* sigtrust;
109     if (!(sigtrust=dynamic_cast<const SignatureTrustEngine*>(policy.getTrustEngine()))) {
110         log.debug("ignoring message, no SignatureTrustEngine supplied");
111         return false;
112     }
113
114     const HTTPRequest* httpRequest = dynamic_cast<const HTTPRequest*>(request);
115     if (!request || !httpRequest)
116         return false;
117
118     const char* signature = request->getParameter("Signature");
119     if (!signature)
120         return false;
121     
122     const char* sigAlgorithm = request->getParameter("SigAlg");
123     if (!sigAlgorithm) {
124         log.error("SigAlg parameter not found, no way to verify the signature");
125         return false;
126     }
127
128     string input;
129     const char* pch;
130     if (!strcmp(httpRequest->getMethod(), "GET")) {
131         // We have to construct a string containing the signature input by accessing the
132         // request directly. We can't use the decoded parameters because we need the raw
133         // data and URL-encoding isn't canonical.
134
135         // NOTE: SimpleSign for GET means Redirect binding, which means we verify over the
136         // base64-encoded message directly.
137
138         pch = httpRequest->getQueryString();
139         if (!appendParameter(input, pch, "SAMLRequest="))
140             appendParameter(input, pch, "SAMLResponse=");
141         appendParameter(input, pch, "RelayState=");
142         appendParameter(input, pch, "SigAlg=");
143     }
144     else {
145         // With POST, the input string is concatenated from the decoded form controls.
146         // GET should be this way too, but I messed up the spec, sorry.
147
148         // NOTE: SimpleSign for POST means POST binding, which means we verify over the
149         // base64-decoded XML. This sucks, because we have to decode the base64 directly.
150         // Serializing the XMLObject doesn't guarantee the signature will verify (this is
151         // why XMLSignature exists, and why this isn't really "simpler").
152
153         xsecsize_t x;
154         pch = httpRequest->getParameter("SAMLRequest");
155         if (pch) {
156             XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(pch),&x);
157             if (!decoded) {
158                 log.warn("unable to decode base64 in POST binding message");
159                 return false;
160             }
161             input = string("SAMLRequest=") + reinterpret_cast<const char*>(decoded);
162 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
163             XMLString::release(&decoded);
164 #else
165             XMLString::release((char**)&decoded);
166 #endif
167         }
168         else {
169             pch = httpRequest->getParameter("SAMLResponse");
170             XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(pch),&x);
171             if (!decoded) {
172                 log.warn("unable to decode base64 in POST binding message");
173                 return false;
174             }
175             input = string("SAMLResponse=") + reinterpret_cast<const char*>(decoded);
176 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
177             XMLString::release(&decoded);
178 #else
179             XMLString::release((char**)&decoded);
180 #endif
181         }
182
183         pch = httpRequest->getParameter("RelayState");
184         if (pch)
185             input = input + "&RelayState=" + pch;
186         input = input + "&SigAlg=" + sigAlgorithm;
187     }
188
189     // Check for KeyInfo, but defensively (we might be able to run without it).
190     KeyInfo* keyInfo=NULL;
191     pch = request->getParameter("KeyInfo");
192     if (pch) {
193         xsecsize_t x;
194         XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(pch),&x);
195         if (decoded) {
196             try {
197                 istringstream kstrm((char*)decoded);
198                 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(kstrm);
199                 XercesJanitor<DOMDocument> janitor(doc);
200                 XMLObject* kxml = XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true);
201                 janitor.release();
202                 if (!(keyInfo=dynamic_cast<KeyInfo*>(kxml)))
203                     delete kxml;
204             }
205             catch (XMLToolingException& ex) {
206                 log.warn("Failed to load KeyInfo from message: %s", ex.what());
207             }
208 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
209             XMLString::release(&decoded);
210 #else
211             XMLString::release((char**)&decoded);
212 #endif
213         }
214         else {
215             log.warn("Failed to load KeyInfo from message: Unable to decode base64-encoded KeyInfo.");
216         }
217     }
218     
219     auto_ptr<KeyInfo> kjanitor(keyInfo);
220     auto_ptr_XMLCh alg(sigAlgorithm);
221
222     // Set up criteria object.
223     MetadataCredentialCriteria cc(*(policy.getIssuerMetadata()));
224     cc.setXMLAlgorithm(alg.get());
225
226     if (!sigtrust->validate(alg.get(), signature, keyInfo, input.c_str(), input.length(), *(policy.getMetadataProvider()), &cc)) {
227         log.error("unable to verify message signature with supplied trust engine");
228         if (m_errorFatal)
229             throw SecurityPolicyException("Message was signed, but signature could not be verified.");
230         return false;
231     }
232
233     log.debug("signature verified against message issuer");
234     policy.setAuthenticated(true);
235     return true;
236 }