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