Merged issuer/protocol extraction back into rules.
[shibboleth/cpp-opensaml.git] / saml / binding / impl / SimpleSigningRule.cpp
1 /*
2  *  Copyright 2001-2006 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/Protocols.h"
28 #include "saml2/metadata/Metadata.h"
29 #include "saml2/metadata/MetadataProvider.h"
30 #include "security/TrustEngine.h"
31
32 #include <log4cpp/Category.hh>
33 #include <xmltooling/util/NDC.h>
34 #include <xmltooling/util/ReplayCache.h>
35 #include <xsec/enc/XSECCryptoException.hpp>
36 #include <xsec/enc/XSECCryptoProvider.hpp>
37 #include <xsec/framework/XSECException.hpp>
38
39 using namespace opensaml::saml2md;
40 using namespace opensaml;
41 using namespace xmltooling;
42 using namespace log4cpp;
43 using namespace std;
44
45 using xmlsignature::KeyInfo;
46
47 namespace opensaml {
48     SecurityPolicyRule* SAML_DLLLOCAL SimpleSigningRuleFactory(const DOMElement* const & e)
49     {
50         return new SimpleSigningRule(e);
51     }
52
53     // Appends a raw parameter=value pair to the string.
54     static bool appendParameter(string& s, const char* data, const char* name)
55     {
56         const char* start = strstr(data,name);
57         if (!start)
58             return false;
59         if (!s.empty())
60             s += '&';
61         const char* end = strchr(start,'&');
62         if (end)
63             s.append(start, end-start);
64         else
65             s.append(start);
66         return true;
67     }
68 };
69
70
71 pair<saml2::Issuer*,const RoleDescriptor*> SimpleSigningRule::evaluate(
72     const GenericRequest& request,
73     const XMLObject& message,
74     const MetadataProvider* metadataProvider,
75     const QName* role,
76     const opensaml::TrustEngine* trustEngine
77     ) const
78 {
79     Category& log=Category::getInstance(SAML_LOGCAT".SecurityPolicyRule.SimpleSigning");
80     log.debug("evaluating simple signing policy");
81     
82     pair<saml2::Issuer*,const RoleDescriptor*> ret = pair<saml2::Issuer*,const RoleDescriptor*>(NULL,NULL);  
83     
84     if (!metadataProvider || !role || !trustEngine) {
85         log.debug("ignoring message, no metadata supplied");
86         return ret;
87     }
88     
89     const char* signature = request.getParameter("Signature");
90     if (!signature) {
91         log.debug("ignoring unsigned message");
92         return ret;
93     }
94     
95     const char* sigAlgorithm = request.getParameter("SigAlg");
96     if (!sigAlgorithm) {
97         log.error("SigAlg parameter not found, no way to verify the signature");
98         return ret;
99     }
100
101     try {
102         log.debug("extracting issuer from message");
103         pair<saml2::Issuer*,const XMLCh*> issuerInfo = getIssuerAndProtocol(message);
104         
105         auto_ptr<saml2::Issuer> issuer(issuerInfo.first);
106         if (!issuerInfo.first || !issuerInfo.second ||
107                 (issuer->getFormat() && !XMLString::equals(issuer->getFormat(), saml2::NameIDType::ENTITY))) {
108             log.warn("issuer identity not estabished, or was not an entityID");
109             return ret;
110         }
111         
112         log.debug("searching metadata for message issuer...");
113         const EntityDescriptor* entity = metadataProvider->getEntityDescriptor(issuer->getName());
114         if (!entity) {
115             auto_ptr_char temp(issuer->getName());
116             log.warn("no metadata found, can't establish identity of issuer (%s)", temp.get());
117             return ret;
118         }
119
120         log.debug("matched message issuer against metadata, searching for applicable role...");
121         const RoleDescriptor* roledesc=entity->getRoleDescriptor(*role, issuerInfo.second);
122         if (!roledesc) {
123             log.warn("unable to find compatible role (%s) in metadata", role->toString().c_str());
124             return ret;
125         }
126
127         string input;
128         const char* pch;
129         const HTTPRequest& httpRequest = dynamic_cast<const HTTPRequest&>(request);
130         if (!strcmp(httpRequest.getMethod(), "GET")) {
131             // We have to construct a string containing the signature input by accessing the
132             // request directly. We can't use the decoded parameters because we need the raw
133             // data and URL-encoding isn't canonical.
134             pch = httpRequest.getQueryString();
135             if (!appendParameter(input, pch, "SAMLRequest="))
136                 appendParameter(input, pch, "SAMLResponse=");
137             appendParameter(input, pch, "RelayState=");
138             appendParameter(input, pch, "SigAlg=");
139         }
140         else {
141             // With POST, the input string is concatenated from the decoded form controls.
142             // GET should be this way too, but I messed up the spec, sorry.
143             pch = httpRequest.getParameter("SAMLRequest");
144             if (pch)
145                 input = string("SAMLRequest=") + pch;
146             else {
147                 pch = httpRequest.getParameter("SAMLResponse");
148                 input = string("SAMLResponse=") + pch;
149             }
150             pch = httpRequest.getParameter("RelayState");
151             if (pch)
152                 input = input + "&RelayState=" + pch;
153             input = input + "&SigAlg=" + sigAlgorithm;
154         }
155
156         // Check for KeyInfo, but defensively (we might be able to run without it).
157         KeyInfo* keyInfo=NULL;
158         pch = request.getParameter("KeyInfo");
159         if (pch) {
160             try {
161                 istringstream kstrm(pch);
162                 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(kstrm);
163                 XercesJanitor<DOMDocument> janitor(doc);
164                 XMLObject* kxml = XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true);
165                 janitor.release();
166                 if (!(keyInfo=dynamic_cast<KeyInfo*>(kxml)))
167                     delete kxml;
168             }
169             catch (XMLToolingException& ex) {
170                 log.warn("Failed to load KeyInfo from message: %s", ex.what());
171             }
172         }
173         
174         auto_ptr<KeyInfo> kjanitor(keyInfo);
175         auto_ptr_XMLCh alg(sigAlgorithm);
176         
177         if (!trustEngine->validate(alg.get(), signature, keyInfo, input.c_str(), input.length(), *roledesc, metadataProvider->getKeyResolver())) {
178             log.error("unable to verify signature on message with supplied trust engine");
179             return ret;
180         }
181
182         if (log.isDebugEnabled()) {
183             auto_ptr_char iname(entity->getEntityID());
184             log.debug("message from (%s), signature verified", iname.get());
185         }
186         
187         ret.first = issuer.release();
188         ret.second = roledesc;
189     }
190     catch (bad_cast&) {
191         // Just trap it.
192         log.warn("caught a bad_cast while extracting issuer");
193     }
194     return ret;
195 }
196
197 pair<saml2::Issuer*,const XMLCh*> SimpleSigningRule::getIssuerAndProtocol(const XMLObject& message) const
198 {
199     // We just let any bad casts throw here.
200
201     // Shortcuts some of the casting.
202     const XMLCh* ns = message.getElementQName().getNamespaceURI();
203     if (ns) {
204         if (XMLString::equals(ns, samlconstants::SAML20P_NS)) {
205             // 2.0 namespace should be castable to a specialized 2.0 root.
206             const saml2::RootObject& root = dynamic_cast<const saml2::RootObject&>(message);
207             saml2::Issuer* issuer = root.getIssuer();
208             if (issuer && issuer->getName())
209                 return make_pair(issuer->cloneIssuer(), samlconstants::SAML20P_NS);
210             
211             // No issuer in the message, so we have to try the Response approach. 
212             const vector<saml2::Assertion*>& assertions = dynamic_cast<const saml2p::Response&>(message).getAssertions();
213             if (!assertions.empty()) {
214                 issuer = assertions.front()->getIssuer();
215                 if (issuer && issuer->getName())
216                     return make_pair(issuer->cloneIssuer(), samlconstants::SAML20P_NS);
217             }
218         }
219     }
220     return pair<saml2::Issuer*,const XMLCh*>(NULL,NULL);
221 }