Attempt at a metadata generation handler.
[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     string relayState;
126     SPConfig& conf = SPConfig::getConfig();
127     if (conf.isEnabled(SPConfig::InProcess)) {
128         if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
129             m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
130             istringstream msg("Metadata Request Blocked");
131             return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
132         }
133     }
134     
135     try {
136         if (conf.isEnabled(SPConfig::OutOfProcess)) {
137             // When out of process, we run natively and directly process the message.
138             return processMessage(request.getApplication(), request.getHandlerURL(), request);
139         }
140         else {
141             // When not out of process, we remote all the message processing.
142             DDF out,in = DDF(m_address.c_str());
143             in.addmember("application_id").string(request.getApplication().getId());
144             in.addmember("handler_url").string(request.getHandlerURL());
145             DDFJanitor jin(in), jout(out);
146             
147             out=request.getServiceProvider().getListenerService()->send(in);
148             return unwrap(request, out);
149         }
150     }
151     catch (exception& ex) {
152         m_log.error("error while processing request: %s", ex.what());
153         istringstream msg("Metadata Request Failed");
154         return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
155     }
156 }
157
158 void MetadataGenerator::receive(DDF& in, ostream& out)
159 {
160     // Find application.
161     const char* aid=in["application_id"].string();
162     const char* hurl=in["handler_url"].string();
163     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
164     if (!app) {
165         // Something's horribly wrong.
166         m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
167         throw ConfigurationException("Unable to locate application for metadata request, deleted?");
168     }
169     else if (!hurl) {
170         throw ConfigurationException("Missing handler_url parameter in remoted method call.");
171     }
172     
173     // Wrap a response shim.
174     DDF ret(NULL);
175     DDFJanitor jout(ret);
176     auto_ptr<HTTPResponse> resp(getResponse(ret));
177         
178     // Since we're remoted, the result should either be a throw, a false/0 return,
179     // which we just return as an empty structure, or a response/redirect,
180     // which we capture in the facade and send back.
181     processMessage(*app, hurl, *resp.get());
182     out << ret;
183 }
184
185 pair<bool,long> MetadataGenerator::processMessage(const Application& application, const char* handlerURL, HTTPResponse& httpResponse) const
186 {
187 #ifndef SHIBSP_LITE
188     m_log.debug("processing metadata request");
189
190     EntityDescriptor* entity;
191     pair<bool,const char*> prop = getString("template");
192     if (prop.first) {
193         // Load a template to use for our metadata.
194         LocalFileInputSource src(getXMLString("template").second);
195         Wrapper4InputSource dsrc(&src,false);
196         DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
197         XercesJanitor<DOMDocument> docjan(doc);
198         auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
199         entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
200         if (!entity)
201             throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, prop.second));
202         xmlobj.release();
203     }
204     else {
205         entity = EntityDescriptorBuilder::buildEntityDescriptor();
206     }
207
208     auto_ptr<EntityDescriptor> wrapper(entity);
209     pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
210     if (cache.first)
211         entity->setValidUntil(time(NULL) + cache.second);
212     entity->setEntityID(application.getXMLString("entityID").second);
213
214     SPSSODescriptor* role;
215     if (entity->getSPSSODescriptors().empty()) {
216         role = SPSSODescriptorBuilder::buildSPSSODescriptor();
217         entity->getSPSSODescriptors().push_back(role);
218     }
219     else {
220         role = entity->getSPSSODescriptors().front();
221     }
222
223     vector<const Handler*> handlers;
224     application.getHandlers(handlers);
225     for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
226         (*h)->generateMetadata(*role, handlerURL);
227         for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
228             (*h)->generateMetadata(*role, b->c_str());
229     }
230
231     CredentialResolver* credResolver=application.getCredentialResolver();
232     if (credResolver) {
233         Locker credLocker(credResolver);
234         CredentialCriteria cc;
235         cc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
236         vector<const Credential*> creds;
237         credResolver->resolve(creds,&cc);
238         for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
239             KeyInfo* kinfo = (*c)->getKeyInfo();
240             if (kinfo) {
241                 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
242                 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
243                 kd->setKeyInfo(kinfo);
244                 role->getKeyDescriptors().push_back(kd);
245             }
246         }
247
248         cc.setUsage(CredentialCriteria::ENCRYPTION_CREDENTIAL);
249         creds.clear();
250         credResolver->resolve(creds,&cc);
251         for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
252             KeyInfo* kinfo = (*c)->getKeyInfo();
253             if (kinfo) {
254                 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
255                 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
256                 kd->setKeyInfo(kinfo);
257                 role->getKeyDescriptors().push_back(kd);
258             }
259         }
260     }
261
262     // Self-sign it?
263     pair<bool,bool> flag = getBool("signing");
264     if (flag.first && flag.second) {
265         if (credResolver) {
266             Locker credLocker(credResolver);
267             // Fill in criteria to use.
268             CredentialCriteria cc;
269             cc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
270             prop = getString("keyName");
271             if (prop.first)
272                 cc.getKeyNames().insert(prop.second);
273             pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
274             pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
275             if (sigalg.first)
276                 cc.setXMLAlgorithm(sigalg.second);
277             const Credential* cred = credResolver->resolve(&cc);
278             if (!cred)
279                 throw XMLSecurityException("Unable to obtain signing credential to use.");
280             Signature* sig = SignatureBuilder::buildSignature();
281             entity->setSignature(sig);
282             if (sigalg.first)
283                 sig->setSignatureAlgorithm(sigalg.second);
284             if (digalg.first) {
285                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
286                 if (cr)
287                     cr->setDigestAlgorithm(digalg.second);
288             }
289     
290             // Sign response while marshalling.
291             vector<Signature*> sigs(1,sig);
292             entity->marshall((DOMDocument*)NULL,&sigs,cred);
293         }
294     }
295
296     stringstream s;
297     s << *entity;
298     httpResponse.setContentType("application/samlmetadata+xml");
299     return make_pair(true, httpResponse.sendResponse(s));
300 #else
301     return make_pair(false,0);
302 #endif
303 }