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