Boost related changes
[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     delete m_lock;
144 }
145
146 bool SAMLInternalConfig::init(bool initXMLTooling)
147 {
148 #ifdef _DEBUG
149     xmltooling::NDC ndc("init");
150 #endif
151     Category& log=Category::getInstance(SAML_LOGCAT".Config");
152
153     Lock initLock(m_lock);
154
155     if (m_initCount == INT_MAX) {
156         log.crit("library initialized too many times");
157         return false;
158     }
159
160     if (m_initCount >= 1) {
161         ++m_initCount;
162         return true;
163     }
164
165     log.debug("library initialization started");
166
167     if (initXMLTooling && !XMLToolingConfig::getConfig().init()) {
168         return false;
169     }
170
171     XMLToolingConfig::getConfig().getPathResolver()->setDefaultPackageName("opensaml");
172
173     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ArtifactException,opensaml);
174     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
175     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
176     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataFilterException,opensaml::saml2md);
177     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
178     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
179     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
180     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
181
182     saml1::registerAssertionClasses();
183     saml1p::registerProtocolClasses();
184     saml2::registerAssertionClasses();
185     saml2p::registerProtocolClasses();
186     saml2md::registerMetadataClasses();
187     saml2md::registerMetadataProviders();
188     saml2md::registerMetadataFilters();
189     registerSAMLArtifacts();
190     registerMessageEncoders();
191     registerMessageDecoders();
192     registerSecurityPolicyRules();
193
194     log.info("%s library initialization complete", PACKAGE_STRING);
195     ++m_initCount;
196     return true;
197 }
198
199 void SAMLInternalConfig::term(bool termXMLTooling)
200 {
201 #ifdef _DEBUG
202     xmltooling::NDC ndc("term");
203 #endif
204
205     Lock initLock(m_lock);
206     if (m_initCount == 0) {
207         Category::getInstance(SAML_LOGCAT".Config").crit("term without corresponding init");
208         return;
209     }
210     else if (--m_initCount > 0) {
211         return;
212     }
213
214     MessageDecoderManager.deregisterFactories();
215     MessageEncoderManager.deregisterFactories();
216     SecurityPolicyRuleManager.deregisterFactories();
217     SAMLArtifactManager.deregisterFactories();
218     MetadataFilterManager.deregisterFactories();
219     MetadataProviderManager.deregisterFactories();
220
221     delete m_artifactMap;
222     m_artifactMap = nullptr;
223
224     if (termXMLTooling)
225         XMLToolingConfig::getConfig().term();
226     
227     Category::getInstance(SAML_LOGCAT".Config").info("%s library shutdown complete", PACKAGE_STRING);
228 }
229
230 void SAMLInternalConfig::generateRandomBytes(void* buf, unsigned int len)
231 {
232     try {
233         if (XSECPlatformUtils::g_cryptoProvider->getRandom(reinterpret_cast<unsigned char*>(buf),len)<len)
234             throw XMLSecurityException("Unable to generate random data; was PRNG seeded?");
235     }
236     catch (XSECCryptoException& e) {
237         throw XMLSecurityException("Unable to generate random data: $1",params(1,e.getMsg()));
238     }
239 }
240
241 void SAMLInternalConfig::generateRandomBytes(std::string& buf, unsigned int len)
242 {
243     buf.erase();
244     auto_arrayptr<unsigned char> hold(new unsigned char[len]);
245     generateRandomBytes(const_cast<unsigned char*>(hold.get()), len);
246     for (unsigned int i=0; i<len; i++)
247         buf+=(hold.get())[i];
248 }
249
250 XMLCh* SAMLInternalConfig::generateIdentifier()
251 {
252     unsigned char key[17];
253     generateRandomBytes(key,16);
254     
255     char hexform[34];
256     sprintf(hexform,"_%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
257             key[0],key[1],key[2],key[3],key[4],key[5],key[6],key[7],
258             key[8],key[9],key[10],key[11],key[12],key[13],key[14],key[15]);
259     hexform[33]=0;
260     return XMLString::transcode(hexform);
261 }
262
263 string SAMLInternalConfig::hashSHA1(const char* s, bool toHex)
264 {
265     return SecurityHelper::doHash("SHA1", s, strlen(s), toHex);
266 }
267
268 SignableObject::SignableObject()
269 {
270 }
271
272 SignableObject::~SignableObject()
273 {
274 }
275
276 RootObject::RootObject()
277 {
278 }
279
280 RootObject::~RootObject()
281 {
282 }
283
284 Assertion::Assertion()
285 {
286 }
287
288 Assertion::~Assertion()
289 {
290 }
291
292 using namespace saml2p;
293 using namespace saml2md;
294
295 void opensaml::annotateException(XMLToolingException* e, const EntityDescriptor* entity, const Status* status, bool rethrow)
296 {
297     time_t now = time(nullptr);
298     const RoleDescriptor* role = nullptr;
299     static bool (TimeBoundSAMLObject::* isValid)(time_t) const = &TimeBoundSAMLObject::isValid;
300
301     if (entity) {
302         const XMLObject* r = find_if(
303             entity->getOrderedChildren(),
304             (ll_dynamic_cast<const RoleDescriptor*>(_1) != nullptr && lambda::bind(isValid, ll_dynamic_cast<const TimeBoundSAMLObject*>(_1), now))
305             );
306         if (r)
307             role = dynamic_cast<const RoleDescriptor*>(r);
308     }
309
310     annotateException(e, role, status, rethrow);
311 }
312
313 void opensaml::annotateException(XMLToolingException* e, const RoleDescriptor* role, const Status* status, bool rethrow)
314 {
315     if (role) {
316         auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
317         e->addProperty("entityID",id.get());
318
319         const vector<ContactPerson*>& contacts=role->getContactPersons();
320         for (vector<ContactPerson*>::const_iterator c=contacts.begin(); c!=contacts.end(); ++c) {
321             const XMLCh* ctype=(*c)->getContactType();
322             if (ctype && (XMLString::equals(ctype,ContactPerson::CONTACT_SUPPORT)
323                     || XMLString::equals(ctype,ContactPerson::CONTACT_TECHNICAL))) {
324                 GivenName* fname=(*c)->getGivenName();
325                 SurName* lname=(*c)->getSurName();
326                 auto_ptr_char first(fname ? fname->getName() : nullptr);
327                 auto_ptr_char last(lname ? lname->getName() : nullptr);
328                 if (first.get() && last.get()) {
329                     string contact=string(first.get()) + ' ' + last.get();
330                     e->addProperty("contactName",contact.c_str());
331                 }
332                 else if (first.get())
333                     e->addProperty("contactName",first.get());
334                 else if (last.get())
335                     e->addProperty("contactName",last.get());
336                 const vector<EmailAddress*>& emails=const_cast<const ContactPerson*>(*c)->getEmailAddresss();
337                 if (!emails.empty()) {
338                     auto_ptr_char email(emails.front()->getAddress());
339                     if (email.get())
340                         e->addProperty("contactEmail",email.get());
341                 }
342                 break;
343             }
344         }
345
346         auto_ptr_char eurl(role->getErrorURL());
347         if (eurl.get()) {
348             e->addProperty("errorURL",eurl.get());
349         }
350     }
351     
352     if (status) {
353         auto_ptr_char sc(status->getStatusCode() ? status->getStatusCode()->getValue() : nullptr);
354         if (sc.get() && *sc.get())
355             e->addProperty("statusCode", sc.get());
356         if (status->getStatusCode()->getStatusCode()) {
357             auto_ptr_char sc2(status->getStatusCode()->getStatusCode()->getValue());
358             if (sc2.get() && *sc.get())
359                 e->addProperty("statusCode2", sc2.get());
360         }
361         if (status->getStatusMessage()) {
362             auto_ptr_char msg(status->getStatusMessage()->getMessage());
363             if (msg.get() && *msg.get())
364                 e->addProperty("statusMessage", msg.get());
365         }
366     }
367     
368     if (rethrow)
369         e->raise();
370 }