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