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