12e60e1d706811ffbfa7204b3cd5f247b4eccfb9
[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/security/SecurityHelper.h>
56 #include <xmltooling/signature/Signature.h>
57 #include <xmltooling/util/NDC.h>
58 #include <xmltooling/util/PathResolver.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(NULL)
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 bool SAMLInternalConfig::init(bool initXMLTooling)
127 {
128 #ifdef _DEBUG
129     xmltooling::NDC ndc("init");
130 #endif
131     Category& log=Category::getInstance(SAML_LOGCAT".SAMLConfig");
132     log.debug("library initialization started");
133
134     if (initXMLTooling)
135         XMLToolingConfig::getConfig().init();
136     XMLToolingConfig::getConfig().getPathResolver()->setDefaultPackageName("opensaml");
137
138     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ArtifactException,opensaml);
139     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
140     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
141     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataFilterException,opensaml::saml2md);
142     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
143     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
144     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
145     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
146
147     saml1::registerAssertionClasses();
148     saml1p::registerProtocolClasses();
149     saml2::registerAssertionClasses();
150     saml2p::registerProtocolClasses();
151     saml2md::registerMetadataClasses();
152     saml2md::registerMetadataProviders();
153     saml2md::registerMetadataFilters();
154     registerSAMLArtifacts();
155     registerMessageEncoders();
156     registerMessageDecoders();
157     registerSecurityPolicyRules();
158
159     log.info("%s library initialization complete", PACKAGE_STRING);
160     return true;
161 }
162
163 void SAMLInternalConfig::term(bool termXMLTooling)
164 {
165 #ifdef _DEBUG
166     xmltooling::NDC ndc("term");
167 #endif
168     Category& log=Category::getInstance(SAML_LOGCAT".SAMLConfig");
169
170     MessageDecoderManager.deregisterFactories();
171     MessageEncoderManager.deregisterFactories();
172     SecurityPolicyRuleManager.deregisterFactories();
173     SAMLArtifactManager.deregisterFactories();
174     MetadataFilterManager.deregisterFactories();
175     MetadataProviderManager.deregisterFactories();
176
177     delete m_artifactMap;
178     m_artifactMap = NULL;
179
180     if (termXMLTooling)
181         XMLToolingConfig::getConfig().term();
182     
183     log.info("%s library shutdown complete", PACKAGE_STRING);
184 }
185
186 void SAMLInternalConfig::generateRandomBytes(void* buf, unsigned int len)
187 {
188     try {
189         if (XSECPlatformUtils::g_cryptoProvider->getRandom(reinterpret_cast<unsigned char*>(buf),len)<len)
190             throw XMLSecurityException("Unable to generate random data; was PRNG seeded?");
191     }
192     catch (XSECCryptoException& e) {
193         throw XMLSecurityException("Unable to generate random data: $1",params(1,e.getMsg()));
194     }
195 }
196
197 void SAMLInternalConfig::generateRandomBytes(std::string& buf, unsigned int len)
198 {
199     buf.erase();
200     auto_ptr<unsigned char> hold(new unsigned char[len]);
201     generateRandomBytes(hold.get(),len);
202     for (unsigned int i=0; i<len; i++)
203         buf+=(hold.get())[i];
204 }
205
206 XMLCh* SAMLInternalConfig::generateIdentifier()
207 {
208     unsigned char key[17];
209     generateRandomBytes(key,16);
210     
211     char hexform[34];
212     sprintf(hexform,"_%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
213             key[0],key[1],key[2],key[3],key[4],key[5],key[6],key[7],
214             key[8],key[9],key[10],key[11],key[12],key[13],key[14],key[15]);
215     hexform[33]=0;
216     return XMLString::transcode(hexform);
217 }
218
219 string SAMLInternalConfig::hashSHA1(const char* s, bool toHex)
220 {
221     return SecurityHelper::doHash("SHA1", s, strlen(s), toHex);
222 }
223
224 SignableObject::SignableObject()
225 {
226 }
227
228 SignableObject::~SignableObject()
229 {
230 }
231
232 RootObject::RootObject()
233 {
234 }
235
236 RootObject::~RootObject()
237 {
238 }
239
240 Assertion::Assertion()
241 {
242 }
243
244 Assertion::~Assertion()
245 {
246 }
247
248 using namespace saml2p;
249 using namespace saml2md;
250
251 void opensaml::annotateException(XMLToolingException* e, const EntityDescriptor* entity, const Status* status, bool rethrow)
252 {
253     const RoleDescriptor* role = NULL;
254     if (entity) {
255         const list<XMLObject*>& roles=entity->getOrderedChildren();
256         for (list<XMLObject*>::const_iterator child=roles.begin(); !role && child!=roles.end(); ++child) {
257             role=dynamic_cast<RoleDescriptor*>(*child);
258             if (role && !role->isValid())
259                 role = NULL;
260         }
261     }
262     annotateException(e, role, status, rethrow);
263 }
264
265 void opensaml::annotateException(XMLToolingException* e, const RoleDescriptor* role, const Status* status, bool rethrow)
266 {
267     if (role) {
268         auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
269         e->addProperty("entityID",id.get());
270
271         const vector<ContactPerson*>& contacts=role->getContactPersons();
272         for (vector<ContactPerson*>::const_iterator c=contacts.begin(); c!=contacts.end(); ++c) {
273             const XMLCh* ctype=(*c)->getContactType();
274             if (ctype && (XMLString::equals(ctype,ContactPerson::CONTACT_SUPPORT)
275                     || XMLString::equals(ctype,ContactPerson::CONTACT_TECHNICAL))) {
276                 GivenName* fname=(*c)->getGivenName();
277                 SurName* lname=(*c)->getSurName();
278                 auto_ptr_char first(fname ? fname->getName() : NULL);
279                 auto_ptr_char last(lname ? lname->getName() : NULL);
280                 if (first.get() && last.get()) {
281                     string contact=string(first.get()) + ' ' + last.get();
282                     e->addProperty("contactName",contact.c_str());
283                 }
284                 else if (first.get())
285                     e->addProperty("contactName",first.get());
286                 else if (last.get())
287                     e->addProperty("contactName",last.get());
288                 const vector<EmailAddress*>& emails=const_cast<const ContactPerson*>(*c)->getEmailAddresss();
289                 if (!emails.empty()) {
290                     auto_ptr_char email(emails.front()->getAddress());
291                     if (email.get())
292                         e->addProperty("contactEmail",email.get());
293                 }
294                 break;
295             }
296         }
297
298         auto_ptr_char eurl(role->getErrorURL());
299         if (eurl.get()) {
300             e->addProperty("errorURL",eurl.get());
301         }
302     }
303     
304     if (status) {
305         auto_ptr_char sc(status->getStatusCode() ? status->getStatusCode()->getValue() : NULL);
306         if (sc.get() && *sc.get())
307             e->addProperty("statusCode", sc.get());
308         if (status->getStatusCode()->getStatusCode()) {
309             auto_ptr_char sc2(status->getStatusCode()->getStatusCode()->getValue());
310             if (sc2.get() && *sc.get())
311                 e->addProperty("statusCode2", sc2.get());
312         }
313         if (status->getStatusMessage()) {
314             auto_ptr_char msg(status->getStatusMessage()->getMessage());
315             if (msg.get() && *msg.get())
316                 e->addProperty("statusMessage", msg.get());
317         }
318     }
319     
320     if (rethrow)
321         e->raise();
322 }