Move settings from Policy to RelyingParty to allow per-RP values.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / MetadataGenerator.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  * MetadataGenerator.cpp
19  * 
20  * Handler for generating "approximate" metadata based on SP configuration.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "handler/AbstractHandler.h"
28 #include "handler/RemotedHandler.h"
29
30 #include <xercesc/framework/LocalFileInputSource.hpp>
31 #include <xercesc/framework/Wrapper4InputSource.hpp>
32
33 using namespace shibsp;
34 #ifndef SHIBSP_LITE
35 using namespace opensaml::saml2md;
36 using namespace opensaml;
37 using namespace xmlsignature;
38 #endif
39 using namespace xmltooling;
40 using namespace std;
41
42 namespace shibsp {
43
44 #if defined (_MSC_VER)
45     #pragma warning( push )
46     #pragma warning( disable : 4250 )
47 #endif
48
49     class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
50     {
51     public:
52         short acceptNode(const DOMNode* node) const {
53             return FILTER_REJECT;
54         }
55     };
56
57     static SHIBSP_DLLLOCAL Blocker g_Blocker;
58
59     class SHIBSP_API MetadataGenerator : public AbstractHandler, public RemotedHandler
60     {
61     public:
62         MetadataGenerator(const DOMElement* e, const char* appId);
63         virtual ~MetadataGenerator() {}
64
65         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
66         void receive(DDF& in, ostream& out);
67
68     private:
69         pair<bool,long> processMessage(const Application& application, const char* handlerURL, HTTPResponse& httpResponse) const;
70
71         set<string> m_acl;
72 #ifndef SHIBSP_LITE
73         vector<string> m_bases;
74 #endif
75     };
76
77 #if defined (_MSC_VER)
78     #pragma warning( pop )
79 #endif
80
81     Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
82     {
83         return new MetadataGenerator(p.first, p.second);
84     }
85
86 };
87
88 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
89     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
90 {
91     string address(appId);
92     address += getString("Location").second;
93     setAddress(address.c_str());
94     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
95         pair<bool,const char*> acl = getString("acl");
96         if (acl.first) {
97             string aclbuf=acl.second;
98             int j = 0;
99             for (unsigned int i=0;  i < aclbuf.length();  i++) {
100                 if (aclbuf.at(i)==' ') {
101                     m_acl.insert(aclbuf.substr(j, i-j));
102                     j = i+1;
103                 }
104             }
105             m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
106         }
107     }
108
109 #ifndef SHIBSP_LITE
110     static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
111     e = XMLHelper::getFirstChildElement(e, EndpointBase);
112     while (e) {
113         if (e->hasChildNodes()) {
114             auto_ptr_char base(e->getFirstChild()->getNodeValue());
115             if (base.get() && *base.get())
116                 m_bases.push_back(base.get());
117         }
118         e = XMLHelper::getNextSiblingElement(e, EndpointBase);
119     }
120 #endif
121 }
122
123 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
124 {
125     SPConfig& conf = SPConfig::getConfig();
126     if (conf.isEnabled(SPConfig::InProcess)) {
127         if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
128             m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
129             istringstream msg("Metadata Request Blocked");
130             return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED));
131         }
132     }
133     
134     try {
135         if (conf.isEnabled(SPConfig::OutOfProcess)) {
136             // When out of process, we run natively and directly process the message.
137             return processMessage(request.getApplication(), request.getHandlerURL(), request);
138         }
139         else {
140             // When not out of process, we remote all the message processing.
141             DDF out,in = DDF(m_address.c_str());
142             in.addmember("application_id").string(request.getApplication().getId());
143             in.addmember("handler_url").string(request.getHandlerURL());
144             DDFJanitor jin(in), jout(out);
145             
146             out=request.getServiceProvider().getListenerService()->send(in);
147             return unwrap(request, out);
148         }
149     }
150     catch (exception& ex) {
151         m_log.error("error while processing request: %s", ex.what());
152         istringstream msg("Metadata Request Failed");
153         return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
154     }
155 }
156
157 void MetadataGenerator::receive(DDF& in, ostream& out)
158 {
159     // Find application.
160     const char* aid=in["application_id"].string();
161     const char* hurl=in["handler_url"].string();
162     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
163     if (!app) {
164         // Something's horribly wrong.
165         m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
166         throw ConfigurationException("Unable to locate application for metadata request, deleted?");
167     }
168     else if (!hurl) {
169         throw ConfigurationException("Missing handler_url parameter in remoted method call.");
170     }
171     
172     // Wrap a response shim.
173     DDF ret(NULL);
174     DDFJanitor jout(ret);
175     auto_ptr<HTTPResponse> resp(getResponse(ret));
176         
177     // Since we're remoted, the result should either be a throw, a false/0 return,
178     // which we just return as an empty structure, or a response/redirect,
179     // which we capture in the facade and send back.
180     processMessage(*app, hurl, *resp.get());
181     out << ret;
182 }
183
184 pair<bool,long> MetadataGenerator::processMessage(const Application& application, const char* handlerURL, HTTPResponse& httpResponse) const
185 {
186 #ifndef SHIBSP_LITE
187     m_log.debug("processing metadata request");
188
189     EntityDescriptor* entity;
190     pair<bool,const char*> prop = getString("template");
191     if (prop.first) {
192         // Load a template to use for our metadata.
193         LocalFileInputSource src(getXMLString("template").second);
194         Wrapper4InputSource dsrc(&src,false);
195         DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
196         XercesJanitor<DOMDocument> docjan(doc);
197         auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
198         entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
199         if (!entity)
200             throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, prop.second));
201         xmlobj.release();
202     }
203     else {
204         entity = EntityDescriptorBuilder::buildEntityDescriptor();
205     }
206
207     auto_ptr<EntityDescriptor> wrapper(entity);
208     pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
209     if (cache.first)
210         entity->setValidUntil(time(NULL) + cache.second);
211     entity->setEntityID(application.getXMLString("entityID").second);
212
213     SPSSODescriptor* role;
214     if (entity->getSPSSODescriptors().empty()) {
215         role = SPSSODescriptorBuilder::buildSPSSODescriptor();
216         entity->getSPSSODescriptors().push_back(role);
217     }
218     else {
219         role = entity->getSPSSODescriptors().front();
220     }
221
222     // Policy flags.
223     prop = application.getRelyingParty(NULL)->getString("signing");
224     if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
225         role->AuthnRequestsSigned(true);
226     pair<bool,bool> flagprop = application.getRelyingParty(NULL)->getBool("signedAssertions");
227     if (flagprop.first && flagprop.second)
228         role->WantAssertionsSigned(true);
229
230     vector<const Handler*> handlers;
231     application.getHandlers(handlers);
232     for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
233         if (m_bases.empty()) {
234             (*h)->generateMetadata(*role, handlerURL);
235         }
236         else {
237             for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
238                 (*h)->generateMetadata(*role, b->c_str());
239         }
240     }
241
242     CredentialResolver* credResolver=application.getCredentialResolver();
243     if (credResolver) {
244         Locker credLocker(credResolver);
245         CredentialCriteria cc;
246         cc.setUsage(Credential::SIGNING_CREDENTIAL);
247         vector<const Credential*> creds;
248         credResolver->resolve(creds,&cc);
249         for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
250             KeyInfo* kinfo = (*c)->getKeyInfo();
251             if (kinfo) {
252                 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
253                 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
254                 kd->setKeyInfo(kinfo);
255                 role->getKeyDescriptors().push_back(kd);
256             }
257         }
258
259         cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
260         creds.clear();
261         credResolver->resolve(creds,&cc);
262         for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
263             KeyInfo* kinfo = (*c)->getKeyInfo();
264             if (kinfo) {
265                 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
266                 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
267                 kd->setKeyInfo(kinfo);
268                 role->getKeyDescriptors().push_back(kd);
269             }
270         }
271     }
272
273     // Self-sign it?
274     pair<bool,bool> flag = getBool("signing");
275     if (flag.first && flag.second) {
276         if (credResolver) {
277             Locker credLocker(credResolver);
278             // Fill in criteria to use.
279             CredentialCriteria cc;
280             cc.setUsage(Credential::SIGNING_CREDENTIAL);
281             prop = getString("keyName");
282             if (prop.first)
283                 cc.getKeyNames().insert(prop.second);
284             pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
285             pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
286             if (sigalg.first)
287                 cc.setXMLAlgorithm(sigalg.second);
288             const Credential* cred = credResolver->resolve(&cc);
289             if (!cred)
290                 throw XMLSecurityException("Unable to obtain signing credential to use.");
291             Signature* sig = SignatureBuilder::buildSignature();
292             entity->setSignature(sig);
293             if (sigalg.first)
294                 sig->setSignatureAlgorithm(sigalg.second);
295             if (digalg.first) {
296                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
297                 if (cr)
298                     cr->setDigestAlgorithm(digalg.second);
299             }
300     
301             // Sign response while marshalling.
302             vector<Signature*> sigs(1,sig);
303             entity->marshall((DOMDocument*)NULL,&sigs,cred);
304         }
305     }
306
307     stringstream s;
308     s << *entity;
309     httpResponse.setContentType("application/samlmetadata+xml");
310     return make_pair(true, httpResponse.sendResponse(s));
311 #else
312     return make_pair(false,0L);
313 #endif
314 }