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