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