2 * Copyright 2010-2011 JANET(UK)
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * An embeddable component interface to Shibboleth SP attribute processing.
25 #include <shibsp/exceptions.h>
26 #include <shibsp/Application.h>
27 #include <shibsp/GSSRequest.h>
28 #include <shibsp/SPRequest.h>
29 #include <shibsp/ServiceProvider.h>
30 #include <shibsp/attribute/Attribute.h>
31 #include <shibsp/remoting/ListenerService.h>
33 # include <saml/saml2/metadata/Metadata.h>
34 # include <saml/saml2/metadata/MetadataProvider.h>
35 # include <saml/util/SAMLConstants.h>
36 # include <shibsp/attribute/filtering/AttributeFilter.h>
37 # include <shibsp/attribute/filtering/BasicFilteringContext.h>
38 # include <shibsp/attribute/resolver/AttributeExtractor.h>
39 # include <shibsp/attribute/resolver/AttributeResolver.h>
40 # include <shibsp/attribute/resolver/ResolutionContext.h>
41 # include <shibsp/metadata/MetadataProviderCriteria.h>
43 #include <xmltooling/XMLObjectBuilder.h>
44 #include <xmltooling/XMLToolingConfig.h>
45 #include <xmltooling/impl/AnyElement.h>
46 #include <xmltooling/util/ParserPool.h>
47 #include <xmltooling/util/XMLHelper.h>
48 #include <xercesc/util/Base64.hpp>
50 using namespace shibresolver;
51 using namespace shibsp;
53 using namespace opensaml;
54 using namespace opensaml::saml2md;
56 using namespace xmltooling;
59 namespace shibresolver {
60 class SHIBRESOLVER_DLLLOCAL RemotedResolver : public Remoted {
67 for_each(tokens.begin(), tokens.end(), xmltooling::cleanup<XMLObject>());
68 for_each(inputAttrs.begin(), inputAttrs.end(), xmltooling::cleanup<Attribute>());
69 for_each(resolvedAttrs.begin(), resolvedAttrs.end(), xmltooling::cleanup<Attribute>());
72 vector<const XMLObject*> tokens;
73 vector<Attribute*> inputAttrs;
74 vector<Attribute*> resolvedAttrs;
77 void receive(DDF& in, ostream& out);
79 const Application& app,
81 const vector<const XMLObject*>& tokens,
82 const vector<Attribute*>& inputAttrs,
83 vector <Attribute*>& resolvedAttrs
87 static RemotedResolver g_Remoted;
90 ShibbolethResolver* ShibbolethResolver::create()
92 return new ShibbolethResolver();
95 ShibbolethResolver::ShibbolethResolver() : m_request(NULL), m_sp(NULL)
96 #ifdef SHIBRESOLVER_HAVE_GSSAPI
102 ShibbolethResolver::~ShibbolethResolver()
104 #ifdef SHIBRESOLVER_HAVE_GSSAPI
107 for_each(m_resolvedAttributes.begin(), m_resolvedAttributes.end(), xmltooling::cleanup<Attribute>());
112 void ShibbolethResolver::setRequest(const SPRequest* request)
115 #if defined(SHIBSP_HAVE_GSSAPI) && defined (SHIBRESOLVER_HAVE_GSSAPI)
117 const GSSRequest* gss = dynamic_cast<const GSSRequest*>(request);
119 addToken(gss->getGSSContext());
125 void ShibbolethResolver::setApplicationID(const char* appID)
132 void ShibbolethResolver::setIssuer(const char* issuer)
139 void ShibbolethResolver::addToken(const XMLObject* token)
142 m_tokens.push_back(token);
145 #ifdef SHIBRESOLVER_HAVE_GSSAPI
146 void ShibbolethResolver::addToken(gss_ctx_id_t ctx)
153 if (ctx != GSS_C_NO_CONTEXT) {
155 gss_buffer_desc contextbuf;
156 contextbuf.length = 0;
157 contextbuf.value = NULL;
158 OM_uint32 major = gss_export_sec_context(&minor, &ctx, &contextbuf);
159 if (major == GSS_S_COMPLETE) {
161 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(contextbuf.value), contextbuf.length, &len);
164 s.append(reinterpret_cast<char*>(out), len);
165 auto_ptr_XMLCh temp(s.c_str());
166 #ifdef SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE
167 XMLString::release(&out);
169 XMLString::release((char**)&out);
171 static const XMLCh _GSSAPI[] = UNICODE_LITERAL_6(G,S,S,A,P,I);
172 m_gsswrapper = new AnyElementImpl(shibspconstants::SHIB2ATTRIBUTEMAP_NS, _GSSAPI);
173 m_gsswrapper->setTextContent(temp.get());
176 Category::getInstance(SHIBRESOLVER_LOGCAT).error("error while base64-encoding GSS context");
180 Category::getInstance(SHIBRESOLVER_LOGCAT).error("error exporting GSS context");
186 void ShibbolethResolver::addAttribute(Attribute* attr)
189 m_inputAttributes.push_back(attr);
192 vector<Attribute*>& ShibbolethResolver::getResolvedAttributes()
194 return m_resolvedAttributes;
197 RequestMapper::Settings ShibbolethResolver::getSettings() const
200 throw ConfigurationException("Request settings not available without supplying SPRequest instance.");
201 return m_request->getRequestSettings();
204 void ShibbolethResolver::resolve()
206 Category& log = Category::getInstance(SHIBRESOLVER_LOGCAT);
207 SPConfig& conf = SPConfig::getConfig();
209 m_sp = conf.getServiceProvider();
215 const Application* app = m_request ? &(m_request->getApplication()) : m_sp->getApplication(m_appID.c_str());
217 throw ConfigurationException("Unable to locate application for resolution.");
221 m_tokens.push_back(m_gsswrapper);
224 if (conf.isEnabled(SPConfig::OutOfProcess)) {
234 // When not out of process, we remote all the message processing.
235 DDF out,in = DDF("org.project-moonshot.shibresolver");
236 DDFJanitor jin(in), jout(out);
237 in.addmember("application_id").string(app->getId());
238 if (!m_issuer.empty())
239 in.addmember("issuer").string(m_issuer.c_str());
240 if (!m_tokens.empty()) {
241 DDF& tokens = in.addmember("tokens").list();
242 for (vector<const XMLObject*>::const_iterator t = m_tokens.begin(); t != m_tokens.end(); ++t) {
245 tokens.add(DDF(NULL).string(os.str().c_str()));
248 if (!m_inputAttributes.empty()) {
250 DDF& attrs = in.addmember("attributes").list();
251 for (vector<Attribute*>::const_iterator a = m_inputAttributes.begin(); a != m_inputAttributes.end(); ++a) {
252 attr = (*a)->marshall();
257 out = (m_request ? m_request->getServiceProvider() : (*m_sp)).getListenerService()->send(in);
259 Attribute* attribute;
260 DDF attr = out.first();
261 while (!attr.isnull()) {
263 attribute = Attribute::unmarshall(attr);
264 m_resolvedAttributes.push_back(attribute);
265 if (log.isDebugEnabled())
266 log.debug("unmarshalled attribute (ID: %s) with %d value%s",
267 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
269 catch (AttributeException& ex) {
270 const char* id = attr.first().name();
271 log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
278 void RemotedResolver::receive(DDF& in, ostream& out)
280 Category& log = Category::getInstance(SHIBRESOLVER_LOGCAT);
283 const char* aid = in["application_id"].string();
284 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
286 // Something's horribly wrong.
287 log.error("couldn't find application (%s) for resolution", aid ? aid : "(missing)");
288 throw ConfigurationException("Unable to locate application for resolution, deleted?");
292 DDFJanitor jout(ret);
296 DDF tlist = in["tokens"];
297 DDF token = tlist.first();
298 while (token.isstring()) {
299 // Parse and bind the document into an XMLObject.
300 istringstream instr(token.string());
301 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
302 XercesJanitor<DOMDocument> janitor(doc);
303 XMLObject* xmlObject = XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true);
304 t.tokens.push_back(xmlObject);
306 token = tlist.next();
309 DDF alist = in["attributes"];
310 Attribute* attribute;
311 DDF attr = alist.first();
312 while (!attr.isnull()) {
313 attribute = Attribute::unmarshall(attr);
314 t.inputAttrs.push_back(attribute);
315 if (log.isDebugEnabled())
316 log.debug("unmarshalled attribute (ID: %s) with %d value%s",
317 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
321 resolve(*app, in["issuer"].string(), t.tokens, t.inputAttrs, t.resolvedAttrs);
323 if (!t.resolvedAttrs.empty()) {
325 for (vector<Attribute*>::const_iterator a = t.resolvedAttrs.begin(); a != t.resolvedAttrs.end(); ++a) {
326 attr = (*a)->marshall();
334 void RemotedResolver::resolve(
335 const Application& app,
337 const vector<const XMLObject*>& tokens,
338 const vector<Attribute*>& inputAttrs,
339 vector <Attribute*>& resolvedAttrs
343 Category& log = Category::getInstance(SHIBRESOLVER_LOGCAT);
344 pair<const EntityDescriptor*,const RoleDescriptor*> entity = make_pair((EntityDescriptor*)NULL, (RoleDescriptor*)NULL);
345 MetadataProvider* m = app.getMetadataProvider(false);
348 log.warn("no metadata providers are configured");
350 else if (issuer && *issuer) {
351 // Lookup metadata for the issuer.
352 MetadataProviderCriteria mc(app, issuer, &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
353 entity = m->getEntityDescriptor(mc);
355 log.warn("unable to locate metadata for provider (%s)", issuer);
357 else if (!entity.second) {
358 log.warn("unable to locate SAML 2.0 identity provider role for provider (%s)", issuer);
362 vector<const Assertion*> assertions;
364 AttributeExtractor* extractor = app.getAttributeExtractor();
366 Locker extlocker(extractor);
368 pair<bool,const char*> mprefix = app.getString("metadataAttributePrefix");
370 log.debug("extracting metadata-derived attributes...");
372 // We pass NULL for "issuer" because the IdP isn't the one asserting metadata-based attributes.
373 extractor->extractAttributes(app, NULL, *entity.second, resolvedAttrs);
374 for (vector<Attribute*>::iterator a = resolvedAttrs.begin(); a != resolvedAttrs.end(); ++a) {
375 vector<string>& ids = (*a)->getAliases();
376 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
377 *id = mprefix.second + *id;
380 catch (exception& ex) {
381 log.error("caught exception extracting attributes: %s", ex.what());
385 log.debug("extracting pushed attributes...");
386 for (vector<const XMLObject*>::const_iterator t = tokens.begin(); t!=tokens.end(); ++t) {
388 // Save off any assertions for later use by resolver.
389 const Assertion* assertion = dynamic_cast<const Assertion*>(*t);
391 assertions.push_back(assertion);
392 extractor->extractAttributes(app, entity.second, *(*t), resolvedAttrs);
394 catch (exception& ex) {
395 log.error("caught exception extracting attributes: %s", ex.what());
399 AttributeFilter* filter = app.getAttributeFilter();
400 if (filter && !resolvedAttrs.empty()) {
401 BasicFilteringContext fc(app, resolvedAttrs, entity.second);
402 Locker filtlocker(filter);
404 filter->filterAttributes(fc, resolvedAttrs);
406 catch (exception& ex) {
407 log.error("caught exception filtering attributes: %s", ex.what());
408 log.error("dumping extracted attributes due to filtering exception");
409 for_each(resolvedAttrs.begin(), resolvedAttrs.end(), xmltooling::cleanup<shibsp::Attribute>());
410 resolvedAttrs.clear();
415 log.warn("no AttributeExtractor plugin installed, check log during startup");
419 AttributeResolver* resolver = app.getAttributeResolver();
421 log.debug("resolving attributes...");
423 vector<Attribute*> inputs = inputAttrs;
424 inputs.insert(inputs.end(), resolvedAttrs.begin(), resolvedAttrs.end());
426 Locker locker(resolver);
427 auto_ptr<ResolutionContext> ctx(
428 resolver->createResolutionContext(
431 samlconstants::SAML20P_NS,
439 resolver->resolveAttributes(*ctx.get());
440 if (!ctx->getResolvedAttributes().empty())
441 resolvedAttrs.insert(resolvedAttrs.end(), ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
444 catch (exception& ex) {
445 log.error("attribute resolution failed: %s", ex.what());
448 throw ConfigurationException("Cannot process request using lite version of shibsp library.");
452 bool ShibbolethResolver::init(unsigned long features, const char* config, bool rethrow)
454 if (features && SPConfig::OutOfProcess) {
456 features = features | SPConfig::AttributeResolution | SPConfig::Metadata | SPConfig::Trust | SPConfig::Credentials;
458 if (!(features && SPConfig::InProcess))
459 features |= SPConfig::Listener;
461 else if (features && SPConfig::InProcess) {
462 features |= SPConfig::Listener;
464 SPConfig::getConfig().setFeatures(features);
465 if (!SPConfig::getConfig().init())
467 if (!SPConfig::getConfig().instantiate(config, rethrow))
473 * Shuts down runtime.
475 * Each process using the library SHOULD call this function exactly once before terminating itself.
477 void ShibbolethResolver::term()
479 SPConfig::getConfig().term();
483 extern "C" int SHIBRESOLVER_EXPORTS xmltooling_extension_init(void*)
485 #ifdef SHIBRESOLVER_SHIBSP_HAS_REMOTING
486 SPConfig& conf = SPConfig::getConfig();
487 if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess) && conf.isEnabled(SPConfig::Listener))
488 conf.getServiceProvider()->regListener("org.project-moonshot.shibresolver", &g_Remoted);
490 return 0; // signal success
493 extern "C" void SHIBRESOLVER_EXPORTS xmltooling_extension_term()
495 // Factories normally get unregistered during library shutdown, so no work usually required here.