298e84b864f89403d55875136315aa899d3b541b
[shibboleth/cpp-opensaml.git] / saml / SAMLConfig.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * SAMLConfig.cpp
23  * 
24  * Library configuration.
25  */
26
27 #include "internal.h"
28
29 #if defined(XMLTOOLING_LOG4SHIB)
30 # ifndef OPENSAML_LOG4SHIB
31 #  error "Logging library mismatch (XMLTooling is using log4shib)."
32 # endif
33 #elif defined(XMLTOOLING_LOG4CPP)
34 # ifndef OPENSAML_LOG4CPP
35 #  error "Logging library mismatch (XMLTooling is using log4cpp)."
36 # endif
37 #else
38 # error "No supported logging library."
39 #endif
40
41 #include "exceptions.h"
42 #include "SAMLConfig.h"
43 #include "binding/ArtifactMap.h"
44 #include "binding/MessageDecoder.h"
45 #include "binding/MessageEncoder.h"
46 #include "binding/SAMLArtifact.h"
47 #include "binding/SecurityPolicyRule.h"
48 #include "saml1/core/Assertions.h"
49 #include "saml1/core/Protocols.h"
50 #include "saml2/core/Protocols.h"
51 #include "saml2/metadata/Metadata.h"
52 #include "saml2/metadata/MetadataFilter.h"
53 #include "saml2/metadata/MetadataProvider.h"
54 #include "util/SAMLConstants.h"
55
56 #include <xmltooling/logging.h>
57 #include <xmltooling/XMLToolingConfig.h>
58 #include <xmltooling/security/SecurityHelper.h>
59 #include <xmltooling/signature/Signature.h>
60 #include <xmltooling/util/NDC.h>
61 #include <xmltooling/util/PathResolver.h>
62 #include <xmltooling/util/Threads.h>
63
64 #include <boost/lambda/bind.hpp>
65 #include <boost/lambda/casts.hpp>
66 #include <boost/lambda/lambda.hpp>
67
68 #include <xsec/enc/XSECCryptoException.hpp>
69 #include <xsec/enc/XSECCryptoProvider.hpp>
70 #include <xsec/utils/XSECPlatformUtils.hpp>
71
72 using namespace opensaml;
73 using namespace xmlsignature;
74 using namespace xmltooling::logging;
75 using namespace xmltooling;
76 using namespace boost::lambda;
77 using namespace boost;
78 using namespace std;
79
80 // Expose entry points when used as an extension library
81
82 extern "C" int SAML_API xmltooling_extension_init(void*)
83 {
84     if (SAMLConfig::getConfig().init(false))
85         return 0;
86     return -1;
87 }
88
89 extern "C" void SAML_API xmltooling_extension_term()
90 {
91     SAMLConfig::getConfig().term(false);
92 }
93
94 DECL_XMLTOOLING_EXCEPTION_FACTORY(ArtifactException,opensaml);
95 DECL_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
96 DECL_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
97 DECL_XMLTOOLING_EXCEPTION_FACTORY(MetadataFilterException,opensaml::saml2md);
98 DECL_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
99 DECL_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
100 DECL_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
101 DECL_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
102
103 namespace opensaml {
104    SAMLInternalConfig g_config;
105 }
106
107 SAMLConfig& SAMLConfig::getConfig()
108 {
109     return g_config;
110 }
111
112 SAMLInternalConfig& SAMLInternalConfig::getInternalConfig()
113 {
114     return g_config;
115 }
116
117 SAMLConfig::SAMLConfig() : m_artifactMap(nullptr)
118 {
119 }
120
121 SAMLConfig::~SAMLConfig()
122 {
123     delete m_artifactMap;
124 }
125
126 ArtifactMap* SAMLConfig::getArtifactMap() const
127 {
128     return m_artifactMap;
129 }
130
131 void SAMLConfig::setArtifactMap(ArtifactMap* artifactMap)
132 {
133     delete m_artifactMap;
134     m_artifactMap = artifactMap;
135 }
136
137 SAMLInternalConfig::SAMLInternalConfig() : m_initCount(0), m_lock(Mutex::create())
138 {
139 }
140
141 SAMLInternalConfig::~SAMLInternalConfig()
142 {
143 }
144
145 bool SAMLInternalConfig::init(bool initXMLTooling)
146 {
147 #ifdef _DEBUG
148     xmltooling::NDC ndc("init");
149 #endif
150     Category& log=Category::getInstance(SAML_LOGCAT".Config");
151
152     Lock initLock(m_lock);
153
154     if (m_initCount == INT_MAX) {
155         log.crit("library initialized too many times");
156         return false;
157     }
158
159     if (m_initCount >= 1) {
160         ++m_initCount;
161         return true;
162     }
163
164     log.debug("library initialization started");
165
166     if (initXMLTooling && !XMLToolingConfig::getConfig().init()) {
167         return false;
168     }
169
170     XMLToolingConfig::getConfig().getPathResolver()->setDefaultPackageName("opensaml");
171
172     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ArtifactException,opensaml);
173     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
174     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
175     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataFilterException,opensaml::saml2md);
176     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
177     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
178     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
179     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
180
181     saml1::registerAssertionClasses();
182     saml1p::registerProtocolClasses();
183     saml2::registerAssertionClasses();
184     saml2p::registerProtocolClasses();
185     saml2md::registerMetadataClasses();
186     saml2md::registerMetadataProviders();
187     saml2md::registerMetadataFilters();
188     registerSAMLArtifacts();
189     registerMessageEncoders();
190     registerMessageDecoders();
191     registerSecurityPolicyRules();
192
193     log.info("%s library initialization complete", PACKAGE_STRING);
194     ++m_initCount;
195     return true;
196 }
197
198 void SAMLInternalConfig::term(bool termXMLTooling)
199 {
200 #ifdef _DEBUG
201     xmltooling::NDC ndc("term");
202 #endif
203
204     Lock initLock(m_lock);
205     if (m_initCount == 0) {
206         Category::getInstance(SAML_LOGCAT".Config").crit("term without corresponding init");
207         return;
208     }
209     else if (--m_initCount > 0) {
210         return;
211     }
212
213     MessageDecoderManager.deregisterFactories();
214     MessageEncoderManager.deregisterFactories();
215     SecurityPolicyRuleManager.deregisterFactories();
216     SAMLArtifactManager.deregisterFactories();
217     MetadataFilterManager.deregisterFactories();
218     MetadataProviderManager.deregisterFactories();
219
220     delete m_artifactMap;
221     m_artifactMap = nullptr;
222
223     if (termXMLTooling)
224         XMLToolingConfig::getConfig().term();
225     
226     Category::getInstance(SAML_LOGCAT".Config").info("%s library shutdown complete", PACKAGE_STRING);
227 }
228
229 void SAMLInternalConfig::generateRandomBytes(void* buf, unsigned int len)
230 {
231     try {
232         if (XSECPlatformUtils::g_cryptoProvider->getRandom(reinterpret_cast<unsigned char*>(buf),len)<len)
233             throw XMLSecurityException("Unable to generate random data; was PRNG seeded?");
234     }
235     catch (XSECCryptoException& e) {
236         throw XMLSecurityException("Unable to generate random data: $1",params(1,e.getMsg()));
237     }
238 }
239
240 void SAMLInternalConfig::generateRandomBytes(std::string& buf, unsigned int len)
241 {
242     buf.erase();
243     auto_arrayptr<unsigned char> hold(new unsigned char[len]);
244     generateRandomBytes(const_cast<unsigned char*>(hold.get()), len);
245     for (unsigned int i=0; i<len; i++)
246         buf+=(hold.get())[i];
247 }
248
249 XMLCh* SAMLInternalConfig::generateIdentifier()
250 {
251     unsigned char key[17];
252     generateRandomBytes(key,16);
253     
254     char hexform[34];
255     sprintf(hexform,"_%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
256             key[0],key[1],key[2],key[3],key[4],key[5],key[6],key[7],
257             key[8],key[9],key[10],key[11],key[12],key[13],key[14],key[15]);
258     hexform[33]=0;
259     return XMLString::transcode(hexform);
260 }
261
262 string SAMLInternalConfig::hashSHA1(const char* s, bool toHex)
263 {
264     return SecurityHelper::doHash("SHA1", s, strlen(s), toHex);
265 }
266
267 SignableObject::SignableObject()
268 {
269 }
270
271 SignableObject::~SignableObject()
272 {
273 }
274
275 RootObject::RootObject()
276 {
277 }
278
279 RootObject::~RootObject()
280 {
281 }
282
283 Assertion::Assertion()
284 {
285 }
286
287 Assertion::~Assertion()
288 {
289 }
290
291 Status::Status()
292 {
293 }
294
295 Status::~Status()
296 {
297 }
298
299 using namespace saml2p;
300 using namespace saml2md;
301
302 void opensaml::annotateException(XMLToolingException* e, const EntityDescriptor* entity, const Status* status, bool rethrow)
303 {
304     time_t now = time(nullptr);
305     const RoleDescriptor* role = nullptr;
306     static bool (TimeBoundSAMLObject::* isValid)(time_t) const = &TimeBoundSAMLObject::isValid;
307
308     if (entity) {
309         const XMLObject* r = find_if(
310             entity->getOrderedChildren(),
311             (ll_dynamic_cast<const RoleDescriptor*>(_1) != ((const RoleDescriptor*)nullptr) &&
312                     lambda::bind(isValid, ll_dynamic_cast<const TimeBoundSAMLObject*>(_1), now))
313             );
314         if (r)
315             role = dynamic_cast<const RoleDescriptor*>(r);
316     }
317
318     annotateException(e, role, status, rethrow);
319 }
320
321 void opensaml::annotateException(XMLToolingException* e, const RoleDescriptor* role, const Status* status, bool rethrow)
322 {
323     if (role) {
324         auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
325         e->addProperty("entityID",id.get());
326
327         const vector<ContactPerson*>& contacts=role->getContactPersons();
328         for (vector<ContactPerson*>::const_iterator c=contacts.begin(); c!=contacts.end(); ++c) {
329             const XMLCh* ctype=(*c)->getContactType();
330             if (ctype && (XMLString::equals(ctype,ContactPerson::CONTACT_SUPPORT)
331                     || XMLString::equals(ctype,ContactPerson::CONTACT_TECHNICAL))) {
332                 GivenName* fname=(*c)->getGivenName();
333                 SurName* lname=(*c)->getSurName();
334                 auto_ptr_char first(fname ? fname->getName() : nullptr);
335                 auto_ptr_char last(lname ? lname->getName() : nullptr);
336                 if (first.get() && last.get()) {
337                     string contact=string(first.get()) + ' ' + last.get();
338                     e->addProperty("contactName",contact.c_str());
339                 }
340                 else if (first.get())
341                     e->addProperty("contactName",first.get());
342                 else if (last.get())
343                     e->addProperty("contactName",last.get());
344                 const vector<EmailAddress*>& emails=const_cast<const ContactPerson*>(*c)->getEmailAddresss();
345                 if (!emails.empty()) {
346                     auto_ptr_char email(emails.front()->getAddress());
347                     if (email.get())
348                         e->addProperty("contactEmail",email.get());
349                 }
350                 break;
351             }
352         }
353
354         auto_ptr_char eurl(role->getErrorURL());
355         if (eurl.get()) {
356             e->addProperty("errorURL",eurl.get());
357         }
358     }
359
360     if (status) {
361         auto_ptr_char sc(status->getTopStatus());
362         if (sc.get() && *sc.get())
363             e->addProperty("statusCode", sc.get());
364         if (status->getSubStatus()) {
365             auto_ptr_char sc2(status->getSubStatus());
366             if (sc2.get() && *sc.get())
367                 e->addProperty("statusCode2", sc2.get());
368         }
369         if (status->getMessage()) {
370             auto_ptr_char msg(status->getMessage());
371             if (msg.get() && *msg.get())
372                 e->addProperty("statusMessage", msg.get());
373         }
374     }
375     
376     if (rethrow)
377         e->raise();
378 }