78f7e0f11bfb77005c1a5d3fd626d7c5b923964d
[shibboleth/opensaml2.git] / saml / SAMLConfig.cpp
1
2 /*
3  *  Copyright 2001-2007 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
58 #include <xsec/enc/XSECCryptoException.hpp>
59 #include <xsec/enc/XSECCryptoProvider.hpp>
60 #include <xsec/utils/XSECPlatformUtils.hpp>
61
62 using namespace opensaml;
63 using namespace xmlsignature;
64 using namespace xmltooling::logging;
65 using namespace xmltooling;
66 using namespace std;
67
68 // Expose entry points when used as an extension library
69
70 extern "C" int SAML_API xmltooling_extension_init(void*)
71 {
72     if (SAMLConfig::getConfig().init(false))
73         return 0;
74     return -1;
75 }
76
77 extern "C" void SAML_API xmltooling_extension_term()
78 {
79     SAMLConfig::getConfig().term(false);
80 }
81
82 DECL_XMLTOOLING_EXCEPTION_FACTORY(ArtifactException,opensaml);
83 DECL_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
84 DECL_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
85 DECL_XMLTOOLING_EXCEPTION_FACTORY(MetadataFilterException,opensaml::saml2md);
86 DECL_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
87 DECL_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
88 DECL_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
89 DECL_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
90
91 namespace opensaml {
92    SAMLInternalConfig g_config;
93 }
94
95 SAMLConfig& SAMLConfig::getConfig()
96 {
97     return g_config;
98 }
99
100 SAMLInternalConfig& SAMLInternalConfig::getInternalConfig()
101 {
102     return g_config;
103 }
104
105 void SAMLConfig::setArtifactMap(ArtifactMap* artifactMap)
106 {
107     delete m_artifactMap;
108     m_artifactMap = artifactMap;
109 }
110
111 bool SAMLInternalConfig::init(bool initXMLTooling)
112 {
113 #ifdef _DEBUG
114     xmltooling::NDC ndc("init");
115 #endif
116     Category& log=Category::getInstance(SAML_LOGCAT".SAMLConfig");
117     log.debug("library initialization started");
118
119     if (initXMLTooling)
120         XMLToolingConfig::getConfig().init();
121
122     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ArtifactException,opensaml);
123     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
124     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
125     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataFilterException,opensaml::saml2md);
126     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
127     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
128     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
129     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
130
131     saml1::registerAssertionClasses();
132     saml1p::registerProtocolClasses();
133     saml2::registerAssertionClasses();
134     saml2p::registerProtocolClasses();
135     saml2md::registerMetadataClasses();
136     saml2md::registerMetadataProviders();
137     saml2md::registerMetadataFilters();
138     registerSAMLArtifacts();
139     registerMessageEncoders();
140     registerMessageDecoders();
141     registerSecurityPolicyRules();
142
143     log.info("%s library initialization complete", PACKAGE_STRING);
144     return true;
145 }
146
147 void SAMLInternalConfig::term(bool termXMLTooling)
148 {
149 #ifdef _DEBUG
150     xmltooling::NDC ndc("term");
151 #endif
152     Category& log=Category::getInstance(SAML_LOGCAT".SAMLConfig");
153
154     MessageDecoderManager.deregisterFactories();
155     MessageEncoderManager.deregisterFactories();
156     SecurityPolicyRuleManager.deregisterFactories();
157     SAMLArtifactManager.deregisterFactories();
158     MetadataFilterManager.deregisterFactories();
159     MetadataProviderManager.deregisterFactories();
160
161     delete m_artifactMap;
162     m_artifactMap = NULL;
163
164     if (termXMLTooling)
165         XMLToolingConfig::getConfig().term();
166     
167     log.info("%s library shutdown complete", PACKAGE_STRING);
168 }
169
170 void SAMLInternalConfig::generateRandomBytes(void* buf, unsigned int len)
171 {
172     try {
173         if (XSECPlatformUtils::g_cryptoProvider->getRandom(reinterpret_cast<unsigned char*>(buf),len)<len)
174             throw XMLSecurityException("Unable to generate random data; was PRNG seeded?");
175     }
176     catch (XSECCryptoException& e) {
177         throw XMLSecurityException("Unable to generate random data: $1",params(1,e.getMsg()));
178     }
179 }
180
181 void SAMLInternalConfig::generateRandomBytes(std::string& buf, unsigned int len)
182 {
183     buf.erase();
184     auto_ptr<unsigned char> hold(new unsigned char[len]);
185     generateRandomBytes(hold.get(),len);
186     for (unsigned int i=0; i<len; i++)
187         buf+=(hold.get())[i];
188 }
189
190 XMLCh* SAMLInternalConfig::generateIdentifier()
191 {
192     unsigned char key[17];
193     generateRandomBytes(key,16);
194     
195     char hexform[34];
196     sprintf(hexform,"_%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
197             key[0],key[1],key[2],key[3],key[4],key[5],key[6],key[7],
198             key[8],key[9],key[10],key[11],key[12],key[13],key[14],key[15]);
199     hexform[33]=0;
200     return XMLString::transcode(hexform);
201 }
202
203 string SAMLInternalConfig::hashSHA1(const char* s, bool toHex)
204 {
205     static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
206
207     auto_ptr<XSECCryptoHash> hasher(XSECPlatformUtils::g_cryptoProvider->hashSHA1());
208     if (hasher.get()) {
209         unsigned char buf[21];
210         hasher->hash(reinterpret_cast<unsigned char*>(const_cast<char*>(s)),strlen(s));
211         if (hasher->finish(buf,20)==20) {
212             string ret;
213             if (toHex) {
214                 for (unsigned int i=0; i<20; i++) {
215                     ret+=(DIGITS[((unsigned char)(0xF0 & buf[i])) >> 4 ]);
216                     ret+=(DIGITS[0x0F & buf[i]]);
217                 }
218             }
219             else {
220                 for (unsigned int i=0; i<20; i++) {
221                     ret+=buf[i];
222                 }
223             }
224             return ret;
225         }
226     }
227     throw XMLSecurityException("Unable to generate SHA-1 hash.");
228 }
229
230 using namespace saml2p;
231 using namespace saml2md;
232
233 void opensaml::annotateException(XMLToolingException* e, const EntityDescriptor* entity, const Status* status, bool rethrow)
234 {
235     const RoleDescriptor* role = NULL;
236     if (entity) {
237         const list<XMLObject*>& roles=entity->getOrderedChildren();
238         for (list<XMLObject*>::const_iterator child=roles.begin(); !role && child!=roles.end(); ++child) {
239             role=dynamic_cast<RoleDescriptor*>(*child);
240             if (role && !role->isValid())
241                 role = NULL;
242         }
243     }
244     annotateException(e, role, status, rethrow);
245 }
246
247 void opensaml::annotateException(XMLToolingException* e, const RoleDescriptor* role, const Status* status, bool rethrow)
248 {
249     if (role) {
250         auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
251         e->addProperty("entityID",id.get());
252
253         const vector<ContactPerson*>& contacts=role->getContactPersons();
254         for (vector<ContactPerson*>::const_iterator c=contacts.begin(); c!=contacts.end(); ++c) {
255             const XMLCh* ctype=(*c)->getContactType();
256             if (ctype && (XMLString::equals(ctype,ContactPerson::CONTACT_SUPPORT)
257                     || XMLString::equals(ctype,ContactPerson::CONTACT_TECHNICAL))) {
258                 GivenName* fname=(*c)->getGivenName();
259                 SurName* lname=(*c)->getSurName();
260                 auto_ptr_char first(fname ? fname->getName() : NULL);
261                 auto_ptr_char last(lname ? lname->getName() : NULL);
262                 if (first.get() && last.get()) {
263                     string contact=string(first.get()) + ' ' + last.get();
264                     e->addProperty("contactName",contact.c_str());
265                 }
266                 else if (first.get())
267                     e->addProperty("contactName",first.get());
268                 else if (last.get())
269                     e->addProperty("contactName",last.get());
270                 const vector<EmailAddress*>& emails=const_cast<const ContactPerson*>(*c)->getEmailAddresss();
271                 if (!emails.empty()) {
272                     auto_ptr_char email(emails.front()->getAddress());
273                     if (email.get())
274                         e->addProperty("contactEmail",email.get());
275                 }
276                 break;
277             }
278         }
279
280         auto_ptr_char eurl(role->getErrorURL());
281         if (eurl.get()) {
282             e->addProperty("errorURL",eurl.get());
283         }
284     }
285     
286     if (status) {
287         auto_ptr_char sc(status->getStatusCode() ? status->getStatusCode()->getValue() : NULL);
288         if (sc.get() && *sc.get())
289             e->addProperty("statusCode", sc.get());
290         if (status->getStatusCode()->getStatusCode()) {
291             auto_ptr_char sc2(status->getStatusCode()->getStatusCode()->getValue());
292             if (sc2.get() && *sc.get())
293                 e->addProperty("statusCode2", sc2.get());
294         }
295         if (status->getStatusMessage()) {
296             auto_ptr_char msg(status->getStatusMessage()->getMessage());
297             if (msg.get() && *msg.get())
298                 e->addProperty("statusMessage", msg.get());
299         }
300     }
301     
302     if (rethrow)
303         e->raise();
304 }