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 #ifdef SHIBRESOLVER_HAVE_GSSAPI_NAMINGEXTS
26 # ifdef SHIBRESOLVER_HAVE_GSSMIT
27 # include <gssapi/gssapi_ext.h>
31 #include <shibsp/exceptions.h>
32 #include <shibsp/Application.h>
33 #include <shibsp/GSSRequest.h>
34 #include <shibsp/SPRequest.h>
35 #include <shibsp/ServiceProvider.h>
36 #include <shibsp/attribute/Attribute.h>
37 #include <shibsp/remoting/ListenerService.h>
39 # include <saml/saml2/metadata/Metadata.h>
40 # include <saml/saml2/metadata/MetadataProvider.h>
41 # include <saml/util/SAMLConstants.h>
42 # include <shibsp/attribute/filtering/AttributeFilter.h>
43 # include <shibsp/attribute/filtering/BasicFilteringContext.h>
44 # include <shibsp/attribute/resolver/AttributeExtractor.h>
45 # include <shibsp/attribute/resolver/AttributeResolver.h>
46 # include <shibsp/attribute/resolver/ResolutionContext.h>
47 # include <shibsp/metadata/MetadataProviderCriteria.h>
49 #include <xmltooling/XMLObjectBuilder.h>
50 #include <xmltooling/XMLToolingConfig.h>
51 #include <xmltooling/impl/AnyElement.h>
52 #include <xmltooling/util/ParserPool.h>
53 #include <xmltooling/util/XMLHelper.h>
54 #include <xercesc/util/Base64.hpp>
56 using namespace shibresolver;
57 using namespace shibsp;
59 using namespace opensaml;
60 using namespace opensaml::saml2md;
62 using namespace xmltooling;
65 namespace shibresolver {
66 class SHIBRESOLVER_DLLLOCAL RemotedResolver : public Remoted {
73 for_each(tokens.begin(), tokens.end(), xmltooling::cleanup<XMLObject>());
74 for_each(inputAttrs.begin(), inputAttrs.end(), xmltooling::cleanup<Attribute>());
75 for_each(resolvedAttrs.begin(), resolvedAttrs.end(), xmltooling::cleanup<Attribute>());
78 vector<const XMLObject*> tokens;
79 vector<Attribute*> inputAttrs;
80 vector<Attribute*> resolvedAttrs;
83 void receive(DDF& in, ostream& out);
85 const Application& app,
87 const vector<const XMLObject*>& tokens,
88 const vector<Attribute*>& inputAttrs,
89 vector <Attribute*>& resolvedAttrs
93 static RemotedResolver g_Remoted;
96 ShibbolethResolver* ShibbolethResolver::create()
98 return new ShibbolethResolver();
101 ShibbolethResolver::ShibbolethResolver() : m_request(NULL), m_sp(NULL)
102 #ifdef SHIBRESOLVER_HAVE_GSSAPI
108 ShibbolethResolver::~ShibbolethResolver()
110 #ifdef SHIBRESOLVER_HAVE_GSSAPI
113 for_each(m_resolvedAttributes.begin(), m_resolvedAttributes.end(), xmltooling::cleanup<Attribute>());
118 void ShibbolethResolver::setRequest(const SPRequest* request)
121 #if defined(SHIBSP_HAVE_GSSAPI) && defined (SHIBRESOLVER_HAVE_GSSAPI)
123 const GSSRequest* gss = dynamic_cast<const GSSRequest*>(request);
125 // TODO: fix API to prevent destruction of contexts
126 gss_ctx_id_t ctx = gss->getGSSContext();
133 void ShibbolethResolver::setApplicationID(const char* appID)
140 void ShibbolethResolver::setIssuer(const char* issuer)
147 void ShibbolethResolver::addToken(const XMLObject* token)
150 m_tokens.push_back(token);
153 #ifdef SHIBRESOLVER_HAVE_GSSAPI
154 void ShibbolethResolver::addToken(gss_ctx_id_t* ctx)
161 if (ctx && *ctx != GSS_C_NO_CONTEXT) {
163 gss_buffer_desc contextbuf = GSS_C_EMPTY_BUFFER;
164 OM_uint32 major = gss_export_sec_context(&minor, ctx, &contextbuf);
165 if (major == GSS_S_COMPLETE) {
167 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(contextbuf.value), contextbuf.length, &len);
170 s.append(reinterpret_cast<char*>(out), len);
171 auto_ptr_XMLCh temp(s.c_str());
172 #ifdef SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE
173 XMLString::release(&out);
175 XMLString::release((char**)&out);
177 static const XMLCh _GSSAPI[] = UNICODE_LITERAL_13(G,S,S,A,P,I,C,o,n,t,e,x,t);
178 m_gsswrapper = new AnyElementImpl(shibspconstants::SHIB2ATTRIBUTEMAP_NS, _GSSAPI);
179 m_gsswrapper->setTextContent(temp.get());
182 Category::getInstance(SHIBRESOLVER_LOGCAT).error("error while base64-encoding GSS context");
184 gss_release_buffer(&minor, &contextbuf);
187 Category::getInstance(SHIBRESOLVER_LOGCAT).error("error exporting GSS context");
192 #ifdef SHIBRESOLVER_HAVE_GSSAPI_NAMINGEXTS
193 void ShibbolethResolver::addToken(gss_name_t name)
201 gss_buffer_desc namebuf = GSS_C_EMPTY_BUFFER;
202 OM_uint32 major = gss_export_name_composite(&minor, name, &namebuf);
203 if (major == GSS_S_COMPLETE) {
205 gss_release_buffer(&minor, &namebuf);
208 Category::getInstance(SHIBRESOLVER_LOGCAT).error("error exporting GSS name");
213 void ShibbolethResolver::addToken(const gss_buffer_t contextbuf)
221 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(contextbuf->value), contextbuf->length, &len);
224 s.append(reinterpret_cast<char*>(out), len);
225 auto_ptr_XMLCh temp(s.c_str());
226 #ifdef SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE
227 XMLString::release(&out);
229 XMLString::release((char**)&out);
231 static const XMLCh _GSSAPI[] = UNICODE_LITERAL_10(G,S,S,A,P,I,N,a,m,e);
232 m_gsswrapper = new AnyElementImpl(shibspconstants::SHIB2ATTRIBUTEMAP_NS, _GSSAPI);
233 m_gsswrapper->setTextContent(temp.get());
236 Category::getInstance(SHIBRESOLVER_LOGCAT).error("error while base64-encoding GSS name");
242 void ShibbolethResolver::addAttribute(Attribute* attr)
245 m_inputAttributes.push_back(attr);
248 vector<Attribute*>& ShibbolethResolver::getResolvedAttributes()
250 return m_resolvedAttributes;
253 RequestMapper::Settings ShibbolethResolver::getSettings() const
256 throw ConfigurationException("Request settings not available without supplying SPRequest instance.");
257 return m_request->getRequestSettings();
260 void ShibbolethResolver::resolve()
262 Category& log = Category::getInstance(SHIBRESOLVER_LOGCAT);
263 SPConfig& conf = SPConfig::getConfig();
265 m_sp = conf.getServiceProvider();
271 const Application* app = m_request ? &(m_request->getApplication()) : m_sp->getApplication(m_appID.c_str());
273 throw ConfigurationException("Unable to locate application for resolution.");
275 #ifdef SHIBRESOLVER_HAVE_GSSAPI
277 m_tokens.push_back(m_gsswrapper);
280 if (conf.isEnabled(SPConfig::OutOfProcess)) {
290 // When not out of process, we remote all the message processing.
291 DDF out,in = DDF("org.project-moonshot.shibresolver");
292 DDFJanitor jin(in), jout(out);
293 in.addmember("application_id").string(app->getId());
294 if (!m_issuer.empty())
295 in.addmember("issuer").string(m_issuer.c_str());
296 if (!m_tokens.empty()) {
297 DDF& tokens = in.addmember("tokens").list();
298 for (vector<const XMLObject*>::const_iterator t = m_tokens.begin(); t != m_tokens.end(); ++t) {
301 tokens.add(DDF(NULL).string(os.str().c_str()));
304 if (!m_inputAttributes.empty()) {
306 DDF& attrs = in.addmember("attributes").list();
307 for (vector<Attribute*>::const_iterator a = m_inputAttributes.begin(); a != m_inputAttributes.end(); ++a) {
308 attr = (*a)->marshall();
313 out = (m_request ? m_request->getServiceProvider() : (*m_sp)).getListenerService()->send(in);
315 Attribute* attribute;
316 DDF attr = out.first();
317 while (!attr.isnull()) {
319 attribute = Attribute::unmarshall(attr);
320 m_resolvedAttributes.push_back(attribute);
321 if (log.isDebugEnabled())
322 log.debug("unmarshalled attribute (ID: %s) with %d value%s",
323 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
325 catch (AttributeException& ex) {
326 const char* id = attr.first().name();
327 log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
334 void RemotedResolver::receive(DDF& in, ostream& out)
336 Category& log = Category::getInstance(SHIBRESOLVER_LOGCAT);
339 const char* aid = in["application_id"].string();
340 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
342 // Something's horribly wrong.
343 log.error("couldn't find application (%s) for resolution", aid ? aid : "(missing)");
344 throw ConfigurationException("Unable to locate application for resolution, deleted?");
348 DDFJanitor jout(ret);
352 DDF tlist = in["tokens"];
353 DDF token = tlist.first();
354 while (token.isstring()) {
355 // Parse and bind the document into an XMLObject.
356 istringstream instr(token.string());
357 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
358 XercesJanitor<DOMDocument> janitor(doc);
359 XMLObject* xmlObject = XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true);
360 t.tokens.push_back(xmlObject);
362 token = tlist.next();
365 DDF alist = in["attributes"];
366 Attribute* attribute;
367 DDF attr = alist.first();
368 while (!attr.isnull()) {
369 attribute = Attribute::unmarshall(attr);
370 t.inputAttrs.push_back(attribute);
371 if (log.isDebugEnabled())
372 log.debug("unmarshalled attribute (ID: %s) with %d value%s",
373 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
377 resolve(*app, in["issuer"].string(), t.tokens, t.inputAttrs, t.resolvedAttrs);
379 if (!t.resolvedAttrs.empty()) {
381 for (vector<Attribute*>::const_iterator a = t.resolvedAttrs.begin(); a != t.resolvedAttrs.end(); ++a) {
382 attr = (*a)->marshall();
390 void RemotedResolver::resolve(
391 const Application& app,
393 const vector<const XMLObject*>& tokens,
394 const vector<Attribute*>& inputAttrs,
395 vector <Attribute*>& resolvedAttrs
399 Category& log = Category::getInstance(SHIBRESOLVER_LOGCAT);
400 string issuerstr(issuer ? issuer : "");
401 pair<const EntityDescriptor*,const RoleDescriptor*> entity = make_pair((EntityDescriptor*)NULL, (RoleDescriptor*)NULL);
402 MetadataProvider* m = app.getMetadataProvider(false);
405 log.warn("no metadata providers are configured");
408 if (!issuerstr.empty()) {
409 // Attempt to locate an issuer based on input token.
410 for (vector<const XMLObject*>::const_iterator t = tokens.begin(); t!=tokens.end(); ++t) {
411 const saml2::Assertion* assertion = dynamic_cast<const saml2::Assertion*>(*t);
412 if (assertion && assertion->getIssuer()) {
413 auto_ptr_char iss(assertion->getIssuer()->getName());
414 if (iss.get() && *iss.get()) {
415 issuerstr = iss.get();
420 if (!issuerstr.empty()) {
421 log.info("setting issuer based on input token (%s)", issuerstr.c_str());
425 if (!issuerstr.empty()) {
426 // Lookup metadata for the issuer.
427 MetadataProviderCriteria idpmc(app, issuerstr.c_str(), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
428 entity = m->getEntityDescriptor(idpmc);
430 log.warn("unable to locate metadata for provider (%s)", issuerstr.c_str());
432 else if (!entity.second) {
433 MetadataProviderCriteria aamc(app, issuerstr.c_str(), &AttributeAuthorityDescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
434 entity = m->getEntityDescriptor(aamc);
435 if (!entity.second) {
436 log.warn("unable to locate SAML 2.0 IdP or AA role for provider (%s)", issuerstr.c_str());
442 vector<const Assertion*> assertions;
444 AttributeExtractor* extractor = app.getAttributeExtractor();
446 Locker extlocker(extractor);
448 pair<bool,const char*> mprefix = app.getString("metadataAttributePrefix");
450 log.debug("extracting metadata-derived attributes...");
452 // We pass NULL for "issuer" because the IdP isn't the one asserting metadata-based attributes.
453 extractor->extractAttributes(app, NULL, *entity.second, resolvedAttrs);
454 for (vector<Attribute*>::iterator a = resolvedAttrs.begin(); a != resolvedAttrs.end(); ++a) {
455 vector<string>& ids = (*a)->getAliases();
456 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
457 *id = mprefix.second + *id;
460 catch (exception& ex) {
461 log.error("caught exception extracting attributes: %s", ex.what());
465 log.debug("extracting pushed attributes...");
466 for (vector<const XMLObject*>::const_iterator t = tokens.begin(); t!=tokens.end(); ++t) {
468 // Save off any assertions for later use by resolver.
469 const Assertion* assertion = dynamic_cast<const Assertion*>(*t);
471 assertions.push_back(assertion);
472 extractor->extractAttributes(app, entity.second, *(*t), resolvedAttrs);
474 catch (exception& ex) {
475 log.error("caught exception extracting attributes: %s", ex.what());
479 AttributeFilter* filter = app.getAttributeFilter();
480 if (filter && !resolvedAttrs.empty()) {
481 BasicFilteringContext fc(app, resolvedAttrs, entity.second);
482 Locker filtlocker(filter);
484 filter->filterAttributes(fc, resolvedAttrs);
486 catch (exception& ex) {
487 log.error("caught exception filtering attributes: %s", ex.what());
488 log.error("dumping extracted attributes due to filtering exception");
489 for_each(resolvedAttrs.begin(), resolvedAttrs.end(), xmltooling::cleanup<shibsp::Attribute>());
490 resolvedAttrs.clear();
495 log.warn("no AttributeExtractor plugin installed, check log during startup");
499 AttributeResolver* resolver = app.getAttributeResolver();
501 log.debug("resolving attributes...");
503 vector<Attribute*> inputs = inputAttrs;
504 inputs.insert(inputs.end(), resolvedAttrs.begin(), resolvedAttrs.end());
506 Locker locker(resolver);
507 auto_ptr<ResolutionContext> ctx(
508 resolver->createResolutionContext(
511 samlconstants::SAML20P_NS,
519 resolver->resolveAttributes(*ctx.get());
520 if (!ctx->getResolvedAttributes().empty())
521 resolvedAttrs.insert(resolvedAttrs.end(), ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
524 catch (exception& ex) {
525 log.error("attribute resolution failed: %s", ex.what());
528 throw ConfigurationException("Cannot process request using lite version of shibsp library.");
532 bool ShibbolethResolver::init(unsigned long features, const char* config, bool rethrow)
534 if (features && SPConfig::OutOfProcess) {
536 features = features | SPConfig::AttributeResolution | SPConfig::Metadata | SPConfig::Trust | SPConfig::Credentials;
538 if (!(features && SPConfig::InProcess))
539 features |= SPConfig::Listener;
541 else if (features && SPConfig::InProcess) {
542 features |= SPConfig::Listener;
544 SPConfig::getConfig().setFeatures(features);
545 if (!SPConfig::getConfig().init())
547 if (!SPConfig::getConfig().instantiate(config, rethrow))
553 * Shuts down runtime.
555 * Each process using the library SHOULD call this function exactly once before terminating itself.
557 void ShibbolethResolver::term()
559 SPConfig::getConfig().term();
563 extern "C" int SHIBRESOLVER_EXPORTS xmltooling_extension_init(void*)
565 #ifdef SHIBRESOLVER_SHIBSP_HAS_REMOTING
566 SPConfig& conf = SPConfig::getConfig();
567 if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess) && conf.isEnabled(SPConfig::Listener))
568 conf.getServiceProvider()->regListener("org.project-moonshot.shibresolver", &g_Remoted);
570 return 0; // signal success
573 extern "C" void SHIBRESOLVER_EXPORTS xmltooling_extension_term()
575 // Factories normally get unregistered during library shutdown, so no work usually required here.