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