Annotate exceptions with status information.
[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 saml2p;
221 using namespace saml2md;
222
223 void opensaml::annotateException(XMLToolingException* e, const EntityDescriptor* entity, const Status* status, bool rethrow)
224 {
225     const RoleDescriptor* role = NULL;
226     if (entity) {
227         const list<XMLObject*>& roles=entity->getOrderedChildren();
228         for (list<XMLObject*>::const_iterator child=roles.begin(); !role && child!=roles.end(); ++child) {
229             role=dynamic_cast<RoleDescriptor*>(*child);
230             if (role && !role->isValid())
231                 role = NULL;
232         }
233     }
234     annotateException(e, role, status, rethrow);
235 }
236
237 void opensaml::annotateException(XMLToolingException* e, const RoleDescriptor* role, const Status* status, bool rethrow)
238 {
239     if (role) {
240         auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
241         e->addProperty("entityID",id.get());
242
243         const vector<ContactPerson*>& contacts=role->getContactPersons();
244         for (vector<ContactPerson*>::const_iterator c=contacts.begin(); c!=contacts.end(); ++c) {
245             const XMLCh* ctype=(*c)->getContactType();
246             if (ctype && (XMLString::equals(ctype,ContactPerson::CONTACT_SUPPORT)
247                     || XMLString::equals(ctype,ContactPerson::CONTACT_TECHNICAL))) {
248                 GivenName* fname=(*c)->getGivenName();
249                 SurName* lname=(*c)->getSurName();
250                 auto_ptr_char first(fname ? fname->getName() : NULL);
251                 auto_ptr_char last(lname ? lname->getName() : NULL);
252                 if (first.get() && last.get()) {
253                     string contact=string(first.get()) + ' ' + last.get();
254                     e->addProperty("contactName",contact.c_str());
255                 }
256                 else if (first.get())
257                     e->addProperty("contactName",first.get());
258                 else if (last.get())
259                     e->addProperty("contactName",last.get());
260                 const vector<EmailAddress*>& emails=const_cast<const ContactPerson*>(*c)->getEmailAddresss();
261                 if (!emails.empty()) {
262                     auto_ptr_char email(emails.front()->getAddress());
263                     if (email.get())
264                         e->addProperty("contactEmail",email.get());
265                 }
266                 break;
267             }
268         }
269
270         auto_ptr_char eurl(role->getErrorURL());
271         if (eurl.get()) {
272             e->addProperty("errorURL",eurl.get());
273         }
274     }
275     
276     if (status) {
277         auto_ptr_char sc(status->getStatusCode() ? status->getStatusCode()->getValue() : NULL);
278         if (sc.get() && *sc.get())
279             e->addProperty("statusCode", sc.get());
280         if (status->getStatusCode()->getStatusCode()) {
281             auto_ptr_char sc2(status->getStatusCode()->getStatusCode()->getValue());
282             if (sc2.get() && *sc.get())
283                 e->addProperty("statusCode2", sc2.get());
284         }
285         if (status->getStatusMessage()) {
286             auto_ptr_char msg(status->getStatusMessage()->getMessage());
287             if (msg.get() && *msg.get())
288                 e->addProperty("statusMessage", msg.get());
289         }
290     }
291     
292     if (rethrow)
293         e->raise();
294 }