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