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