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