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