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