292d7718d667189ccc5ee2c681c4c44127a79b68
[shibboleth/cpp-xmltooling.git] / xmltooling / signature / impl / XMLSecSignatureImpl.cpp
1 /*\r
2 *  Copyright 2001-2006 Internet2\r
3  * \r
4 * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *     http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 /**\r
18  * XMLSecSignatureImpl.cpp\r
19  * \r
20  * Signature class for XMLSec-based signature-handling\r
21  */\r
22 \r
23 #include "internal.h"\r
24 #include "exceptions.h"\r
25 #include "impl/UnknownElement.h"\r
26 #include "signature/Signature.h"\r
27 #include "util/NDC.h"\r
28 #include "util/XMLConstants.h"\r
29 #include "util/XMLHelper.h"\r
30 #include "validation/ValidatingXMLObject.h"\r
31 \r
32 #include <log4cpp/Category.hh>\r
33 #include <xercesc/framework/MemBufInputSource.hpp>\r
34 #include <xercesc/framework/Wrapper4InputSource.hpp>\r
35 #include <xercesc/util/XMLUniDefs.hpp>\r
36 #include <xsec/dsig/DSIGKeyInfoX509.hpp>\r
37 #include <xsec/enc/XSECCryptoException.hpp>\r
38 #include <xsec/framework/XSECException.hpp>\r
39 \r
40 using namespace xmlsignature;\r
41 using namespace xmltooling;\r
42 using namespace log4cpp;\r
43 using namespace std;\r
44 \r
45 #if defined (_MSC_VER)\r
46     #pragma warning( push )\r
47     #pragma warning( disable : 4250 4251 )\r
48 #endif\r
49 \r
50 namespace xmlsignature {\r
51     \r
52     class XMLTOOL_DLLLOCAL XMLSecSignatureImpl\r
53         : public UnknownElementImpl, public virtual Signature, public virtual ValidatingXMLObject\r
54     {\r
55     public:\r
56         XMLSecSignatureImpl() : UnknownElementImpl(XMLConstants::XMLSIG_NS, Signature::LOCAL_NAME, XMLConstants::XMLSIG_PREFIX),\r
57             m_signature(NULL), m_c14n(NULL), m_sm(NULL), m_key(NULL), m_keyInfo(NULL), m_reference(NULL) {}\r
58         virtual ~XMLSecSignatureImpl();\r
59         \r
60         void releaseDOM() const;\r
61         void releaseChildrenDOM(bool propagateRelease=true) const {\r
62             if (m_keyInfo) {\r
63                 m_keyInfo->releaseDOM();\r
64                 if (propagateRelease)\r
65                     m_keyInfo->releaseChildrenDOM();\r
66             }\r
67         }\r
68         XMLObject* clone() const;\r
69         Signature* cloneSignature() const;\r
70 \r
71         DOMElement* marshall(DOMDocument* document=NULL, const vector<Signature*>* sigs=NULL) const;\r
72         DOMElement* marshall(DOMElement* parentElement, const vector<Signature*>* sigs=NULL) const;\r
73         XMLObject* unmarshall(DOMElement* element, bool bindDocument=false);\r
74         \r
75         // Getters\r
76         const XMLCh* getCanonicalizationMethod() const { return m_c14n ? m_c14n : DSIGConstants::s_unicodeStrURIEXC_C14N_NOC; }\r
77         const XMLCh* getSignatureAlgorithm() const { return m_sm ? m_sm : DSIGConstants::s_unicodeStrURIRSA_SHA1; }\r
78         KeyInfo* getKeyInfo() const { return m_keyInfo; }\r
79         ContentReference* getContentReference() const { return m_reference; }\r
80         DSIGSignature* getXMLSignature() const { return m_signature; }\r
81         \r
82         // Setters\r
83         void setCanonicalizationMethod(const XMLCh* c14n) { m_c14n = prepareForAssignment(m_c14n,c14n); }\r
84         void setSignatureAlgorithm(const XMLCh* sm) { m_sm = prepareForAssignment(m_sm,sm); }\r
85         void setSigningKey(XSECCryptoKey* signingKey) {\r
86             delete m_key;\r
87             m_key=signingKey;\r
88             if (m_key)\r
89                 releaseThisandParentDOM();\r
90         }\r
91         void setKeyInfo(KeyInfo* keyInfo) {\r
92             prepareForAssignment(m_keyInfo, keyInfo);\r
93             m_keyInfo=keyInfo;\r
94         }\r
95         void setContentReference(ContentReference* reference) {\r
96             delete m_reference;\r
97             m_reference=reference;\r
98             releaseThisandParentDOM();\r
99         }\r
100         \r
101         void sign();\r
102 \r
103         void registerValidator(Validator* validator);\r
104         void deregisterValidator(Validator* validator);\r
105         void deregisterAll();\r
106         void validate(bool validateDescendants) const;\r
107 \r
108     private:\r
109         mutable DSIGSignature* m_signature;\r
110         XMLCh* m_c14n;\r
111         XMLCh* m_sm;\r
112         XSECCryptoKey* m_key;\r
113         KeyInfo* m_keyInfo;\r
114         ContentReference* m_reference;\r
115         vector<Validator*> m_validators;\r
116     };\r
117     \r
118 };\r
119 \r
120 #if defined (_MSC_VER)\r
121     #pragma warning( pop )\r
122 #endif\r
123 \r
124 XMLSecSignatureImpl::~XMLSecSignatureImpl()\r
125 {\r
126     // Release the associated signature.\r
127     if (m_signature)\r
128         XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->releaseSignature(m_signature);\r
129 \r
130     XMLString::release(&m_c14n);\r
131     XMLString::release(&m_sm);\r
132     delete m_key;\r
133     delete m_keyInfo;\r
134     delete m_reference;\r
135     for_each(m_validators.begin(),m_validators.end(),cleanup<Validator>());\r
136 }\r
137 \r
138 void XMLSecSignatureImpl::releaseDOM() const\r
139 {\r
140     if (getDOM()) {\r
141         // This should save off the DOM\r
142         UnknownElementImpl::releaseDOM();\r
143         \r
144         // Release the associated signature.\r
145         if (m_signature) {\r
146             XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->releaseSignature(m_signature);\r
147             m_signature=NULL;\r
148         }\r
149     }\r
150 }\r
151 \r
152 XMLObject* XMLSecSignatureImpl::clone() const\r
153 {\r
154     return cloneSignature();\r
155 }\r
156 \r
157 Signature* XMLSecSignatureImpl::cloneSignature() const\r
158 {\r
159     XMLSecSignatureImpl* ret=new XMLSecSignatureImpl();\r
160 \r
161     ret->m_c14n=XMLString::replicate(m_c14n);\r
162     ret->m_sm=XMLString::replicate(m_sm);\r
163     if (m_key)\r
164         ret->m_key=m_key->clone();\r
165     if (m_keyInfo)\r
166         ret->m_keyInfo=m_keyInfo->cloneKeyInfo();\r
167 \r
168     xmltooling::clone(m_validators,ret->m_validators);\r
169 \r
170     // If there's no XML locally, serialize this object into the new one, otherwise just copy it over.\r
171     if (m_xml.empty())\r
172         serialize(ret->m_xml);\r
173     else\r
174         ret->m_xml=m_xml;\r
175 \r
176     return ret;\r
177 }\r
178 \r
179 void XMLSecSignatureImpl::sign()\r
180 {\r
181     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".Signature");\r
182     log.debug("applying signature");\r
183 \r
184     if (!m_signature)\r
185         throw SignatureException("Only a marshalled Signature object can be signed.");\r
186     else if (!m_key)\r
187         throw SignatureException("No signing key available for signature creation.");\r
188     else if (!m_reference)\r
189         throw SignatureException("No ContentReference object set for signature creation.");\r
190 \r
191     try {\r
192         log.debug("creating signature reference(s)");\r
193         m_reference->createReferences(m_signature);\r
194         \r
195         log.debug("computing signature");\r
196         m_signature->setSigningKey(m_key->clone());\r
197         m_signature->sign();\r
198     }\r
199     catch(XSECException& e) {\r
200         auto_ptr_char temp(e.getMsg());\r
201         throw SignatureException(string("Caught an XMLSecurity exception while signing: ") + temp.get());\r
202     }\r
203     catch(XSECCryptoException& e) {\r
204         throw SignatureException(string("Caught an XMLSecurity exception while signing: ") + e.getMsg());\r
205     }\r
206 }\r
207 \r
208 DOMElement* XMLSecSignatureImpl::marshall(DOMDocument* document, const vector<Signature*>* sigs) const\r
209 {\r
210 #ifdef _DEBUG\r
211     xmltooling::NDC ndc("marshall");\r
212 #endif\r
213     \r
214     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".Signature");\r
215     log.debug("marshalling ds:Signature");\r
216 \r
217     DOMElement* cachedDOM=getDOM();\r
218     if (cachedDOM) {\r
219         if (!document || document==cachedDOM->getOwnerDocument()) {\r
220             log.debug("Signature has a usable cached DOM, reusing it");\r
221             if (document)\r
222                 setDocumentElement(cachedDOM->getOwnerDocument(),cachedDOM);\r
223             releaseParentDOM(true);\r
224             return cachedDOM;\r
225         }\r
226         \r
227         // We have a DOM but it doesn't match the document we were given. This both sucks and blows.\r
228         // Without an adoptNode option to maintain the child pointers, we have to either import the\r
229         // DOM while somehow reassigning all the nested references (which amounts to a complete\r
230         // *unmarshall* operation), or we just release the existing DOM and hope that we can get\r
231         // it back. This depends on all objects being able to preserve their DOM at all costs.\r
232         releaseChildrenDOM(true);\r
233         releaseDOM();\r
234     }\r
235     \r
236     // If we get here, we didn't have a usable DOM.\r
237     bool bindDocument=false;\r
238     if (m_xml.empty()) {\r
239         // Fresh signature, so we just create an empty one.\r
240         log.debug("creating empty Signature element");\r
241         if (!document) {\r
242             document=DOMImplementationRegistry::getDOMImplementation(NULL)->createDocument();\r
243             bindDocument=true;\r
244         }\r
245         m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignature();\r
246         m_signature->setDSIGNSPrefix(XMLConstants::XMLSIG_PREFIX);\r
247         cachedDOM=m_signature->createBlankSignature(document, getCanonicalizationMethod(), getSignatureAlgorithm());\r
248     }\r
249     else {\r
250         // We need to reparse the XML we saved off into a new DOM.\r
251         MemBufInputSource src(reinterpret_cast<const XMLByte*>(m_xml.c_str()),m_xml.length(),"XMLSecSignatureImpl");\r
252         Wrapper4InputSource dsrc(&src,false);\r
253         log.debug("parsing Signature XML back into DOM tree");\r
254         DOMDocument* internalDoc=XMLToolingConfig::getConfig().getParser().parse(dsrc);\r
255         if (document) {\r
256             // The caller insists on using his own document, so we now have to import the thing\r
257             // into it. Then we're just dumping the one we built.\r
258             log.debug("reimporting new DOM into caller-supplied document");\r
259             cachedDOM=static_cast<DOMElement*>(document->importNode(internalDoc->getDocumentElement(), true));\r
260             internalDoc->release();\r
261         }\r
262         else {\r
263             // We just bind the document we built to the object as the result.\r
264             cachedDOM=static_cast<DOMElement*>(internalDoc->getDocumentElement());\r
265             document=internalDoc;\r
266             bindDocument=true;\r
267         }\r
268 \r
269         // Now reload the signature from the DOM.\r
270         try {\r
271             m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignatureFromDOM(\r
272                 document, cachedDOM\r
273                 );\r
274             m_signature->load();\r
275         }\r
276         catch(XSECException& e) {\r
277             if (bindDocument)\r
278                 document->release();\r
279             auto_ptr_char temp(e.getMsg());\r
280             throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + temp.get());\r
281         }\r
282         catch(XSECCryptoException& e) {\r
283             if (bindDocument)\r
284                 document->release();\r
285             throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + e.getMsg());\r
286         }\r
287     }\r
288     \r
289     // Marshall KeyInfo data.\r
290     if (m_keyInfo && (!m_signature->getKeyInfoList() || m_signature->getKeyInfoList()->isEmpty())) {\r
291         m_keyInfo->marshall(cachedDOM);\r
292     }\r
293 \r
294     // Recache the DOM and clear the serialized copy.\r
295     setDocumentElement(document, cachedDOM);\r
296     log.debug("caching DOM for Signature (document is %sbound)", bindDocument ? "" : "not ");\r
297     setDOM(cachedDOM, bindDocument);\r
298     releaseParentDOM(true);\r
299     m_xml.erase();\r
300     return cachedDOM;\r
301 }\r
302 \r
303 DOMElement* XMLSecSignatureImpl::marshall(DOMElement* parentElement, const vector<Signature*>* sigs) const\r
304 {\r
305 #ifdef _DEBUG\r
306     xmltooling::NDC ndc("marshall");\r
307 #endif\r
308     \r
309     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".Signature");\r
310     log.debug("marshalling ds:Signature");\r
311 \r
312     DOMElement* cachedDOM=getDOM();\r
313     if (cachedDOM) {\r
314         if (parentElement->getOwnerDocument()==cachedDOM->getOwnerDocument()) {\r
315             log.debug("Signature has a usable cached DOM, reusing it");\r
316             if (parentElement!=cachedDOM->getParentNode()) {\r
317                 parentElement->appendChild(cachedDOM);\r
318                 releaseParentDOM(true);\r
319             }\r
320             return cachedDOM;\r
321         }\r
322         \r
323         // We have a DOM but it doesn't match the document we were given. This both sucks and blows.\r
324         // Without an adoptNode option to maintain the child pointers, we have to either import the\r
325         // DOM while somehow reassigning all the nested references (which amounts to a complete\r
326         // *unmarshall* operation), or we just release the existing DOM and hope that we can get\r
327         // it back. This depends on all objects being able to preserve their DOM at all costs.\r
328         releaseChildrenDOM(true);\r
329         releaseDOM();\r
330     }\r
331     \r
332     // If we get here, we didn't have a usable DOM.\r
333     if (m_xml.empty()) {\r
334         // Fresh signature, so we just create an empty one.\r
335         log.debug("creating empty Signature element");\r
336         m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignature();\r
337         m_signature->setDSIGNSPrefix(XMLConstants::XMLSIG_PREFIX);\r
338         cachedDOM=m_signature->createBlankSignature(\r
339             parentElement->getOwnerDocument(), getCanonicalizationMethod(), getSignatureAlgorithm()\r
340             );\r
341     }\r
342     else {\r
343         MemBufInputSource src(reinterpret_cast<const XMLByte*>(m_xml.c_str()),m_xml.length(),"XMLSecSignatureImpl");\r
344         Wrapper4InputSource dsrc(&src,false);\r
345         log.debug("parsing XML back into DOM tree");\r
346         DOMDocument* internalDoc=XMLToolingConfig::getConfig().getParser().parse(dsrc);\r
347         \r
348         log.debug("reimporting new DOM into caller-supplied document");\r
349         cachedDOM=static_cast<DOMElement*>(parentElement->getOwnerDocument()->importNode(internalDoc->getDocumentElement(),true));\r
350         internalDoc->release();\r
351 \r
352         // Now reload the signature from the DOM.\r
353         try {\r
354             m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignatureFromDOM(\r
355                 parentElement->getOwnerDocument(), cachedDOM\r
356                 );\r
357             m_signature->load();\r
358         }\r
359         catch(XSECException& e) {\r
360             auto_ptr_char temp(e.getMsg());\r
361             throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + temp.get());\r
362         }\r
363         catch(XSECCryptoException& e) {\r
364             throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + e.getMsg());\r
365         }\r
366     }\r
367 \r
368     // Marshall KeyInfo data.\r
369     if (m_keyInfo && (!m_signature->getKeyInfoList() || m_signature->getKeyInfoList()->isEmpty())) {\r
370         m_keyInfo->marshall(cachedDOM);\r
371     }\r
372 \r
373     // Recache the DOM and clear the serialized copy.\r
374     parentElement->appendChild(cachedDOM);\r
375     log.debug("caching DOM for Signature");\r
376     setDOM(cachedDOM, false);\r
377     releaseParentDOM(true);\r
378     m_xml.erase();\r
379     return cachedDOM;\r
380 }\r
381 \r
382 XMLObject* XMLSecSignatureImpl::unmarshall(DOMElement* element, bool bindDocument)\r
383 {\r
384     Category::getInstance(XMLTOOLING_LOGCAT".Signature").debug("unmarshalling ds:Signature");\r
385 \r
386     try {\r
387         m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignatureFromDOM(\r
388             element->getOwnerDocument(), element\r
389             );\r
390         m_signature->load();\r
391     }\r
392     catch(XSECException& e) {\r
393         auto_ptr_char temp(e.getMsg());\r
394         throw UnmarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + temp.get());\r
395     }\r
396     catch(XSECCryptoException& e) {\r
397         throw UnmarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + e.getMsg());\r
398     }\r
399 \r
400     setDOM(element, bindDocument);\r
401     return this;\r
402 }\r
403 \r
404 void XMLSecSignatureImpl::registerValidator(Validator* validator)\r
405 {\r
406     m_validators.push_back(validator);\r
407 }\r
408 \r
409 void XMLSecSignatureImpl::deregisterValidator(Validator* validator)\r
410 {\r
411     for (vector<Validator*>::iterator i=m_validators.begin(); i!=m_validators.end(); i++) {\r
412         if ((*i)==validator) {\r
413             m_validators.erase(i);\r
414             return;\r
415         }\r
416     }\r
417 }\r
418 \r
419 void XMLSecSignatureImpl::deregisterAll()\r
420 {\r
421     for_each(m_validators.begin(),m_validators.end(),cleanup<Validator>());\r
422     m_validators.clear();\r
423 }\r
424 \r
425 class _validate : public binary_function<const XMLObject*,bool,void> {\r
426 public:\r
427     void operator()(const XMLObject* obj, bool propagate) const {\r
428         const ValidatingXMLObject* val = dynamic_cast<const ValidatingXMLObject*>(obj);\r
429         if (val) {\r
430             val->validate(propagate);\r
431         }\r
432     }\r
433 };\r
434 \r
435 void XMLSecSignatureImpl::validate(bool validateDescendants) const\r
436 {\r
437     for_each(\r
438         m_validators.begin(),m_validators.end(),\r
439         bind2nd(mem_fun<void,Validator,const XMLObject*>(&Validator::validate),this)\r
440         );\r
441     \r
442     if (validateDescendants && m_keyInfo) {\r
443         m_keyInfo->validate(validateDescendants);\r
444     }\r
445 }\r
446 \r
447 Signature* SignatureBuilder::buildObject(\r
448     const XMLCh* nsURI, const XMLCh* localName, const XMLCh* prefix, const QName* schemaType\r
449     ) const\r
450 {\r
451     if (!XMLString::equals(nsURI,XMLConstants::XMLSIG_NS) || !XMLString::equals(localName,Signature::LOCAL_NAME))\r
452         throw XMLObjectException("XMLSecSignatureBuilder requires standard Signature element name.");\r
453     return buildObject();\r
454 }\r
455 \r
456 Signature* SignatureBuilder::buildObject() const\r
457 {\r
458     return new XMLSecSignatureImpl();\r
459 }\r
460 \r
461 const XMLCh Signature::LOCAL_NAME[] = UNICODE_LITERAL_9(S,i,g,n,a,t,u,r,e);\r