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