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