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