Stop auto-cloning ContentReferences.
[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();\r
61         void releaseChildrenDOM(bool propagateRelease=true) {\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()\r
139 {\r
140     // This should save off the DOM\r
141     UnknownElementImpl::releaseDOM();\r
142     \r
143     // Release the associated signature.\r
144     if (m_signature) {\r
145         XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->releaseSignature(m_signature);\r
146         m_signature=NULL;\r
147     }\r
148 }\r
149 \r
150 XMLObject* XMLSecSignatureImpl::clone() const\r
151 {\r
152     return cloneSignature();\r
153 }\r
154 \r
155 Signature* XMLSecSignatureImpl::cloneSignature() const\r
156 {\r
157     XMLSecSignatureImpl* ret=new XMLSecSignatureImpl();\r
158 \r
159     ret->m_c14n=XMLString::replicate(m_c14n);\r
160     ret->m_sm=XMLString::replicate(m_sm);\r
161     if (m_key)\r
162         ret->m_key=m_key->clone();\r
163     if (m_keyInfo)\r
164         ret->m_keyInfo=m_keyInfo->cloneKeyInfo();\r
165 \r
166     xmltooling::clone(m_validators,ret->m_validators);\r
167 \r
168     // If there's no XML locally, serialize this object into the new one, otherwise just copy it over.\r
169     if (m_xml.empty())\r
170         serialize(ret->m_xml);\r
171     else\r
172         ret->m_xml=m_xml;\r
173 \r
174     return ret;\r
175 }\r
176 \r
177 void XMLSecSignatureImpl::sign()\r
178 {\r
179     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".Signature");\r
180     log.debug("applying signature");\r
181 \r
182     if (!m_signature)\r
183         throw SignatureException("Only a marshalled Signature object can be signed.");\r
184     else if (!m_key)\r
185         throw SignatureException("No signing key available for signature creation.");\r
186     else if (!m_reference)\r
187         throw SignatureException("No ContentReference object set for signature creation.");\r
188 \r
189     try {\r
190         log.debug("creating signature reference(s)");\r
191         m_reference->createReferences(m_signature);\r
192         if (m_keyInfo) {\r
193             m_keyInfo->marshall(getDOM());\r
194         }\r
195         \r
196         log.debug("computing signature");\r
197         m_signature->setSigningKey(m_key->clone());\r
198         m_signature->sign();\r
199     }\r
200     catch(XSECException& e) {\r
201         auto_ptr_char temp(e.getMsg());\r
202         throw SignatureException(string("Caught an XMLSecurity exception while signing: ") + temp.get());\r
203     }\r
204     catch(XSECCryptoException& e) {\r
205         throw SignatureException(string("Caught an XMLSecurity exception while signing: ") + e.getMsg());\r
206     }\r
207 }\r
208 \r
209 DOMElement* XMLSecSignatureImpl::marshall(DOMDocument* document, const vector<Signature*>* sigs) const\r
210 {\r
211 #ifdef _DEBUG\r
212     xmltooling::NDC ndc("marshall");\r
213 #endif\r
214     \r
215     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".Signature");\r
216     log.debug("marshalling ds:Signature");\r
217 \r
218     DOMElement* cachedDOM=getDOM();\r
219     if (cachedDOM) {\r
220         if (!document || document==cachedDOM->getOwnerDocument()) {\r
221             log.debug("Signature has a usable cached DOM, reusing it");\r
222             if (document)\r
223                 setDocumentElement(cachedDOM->getOwnerDocument(),cachedDOM);\r
224             releaseParentDOM(true);\r
225             return cachedDOM;\r
226         }\r
227         \r
228         // We have a DOM but it doesn't match the document we were given, so we import\r
229         // it into the new document.\r
230         cachedDOM=static_cast<DOMElement*>(document->importNode(cachedDOM, true));\r
231 \r
232         try {\r
233             XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->releaseSignature(m_signature);\r
234             m_signature=NULL;\r
235             m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignatureFromDOM(\r
236                 document, cachedDOM\r
237                 );\r
238             m_signature->load();\r
239         }\r
240         catch(XSECException& e) {\r
241             auto_ptr_char temp(e.getMsg());\r
242             throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + temp.get());\r
243         }\r
244         catch(XSECCryptoException& e) {\r
245             throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + e.getMsg());\r
246         }\r
247 \r
248         // Recache the DOM.\r
249         setDocumentElement(document, cachedDOM);\r
250         log.debug("caching imported DOM for Signature");\r
251         setDOM(cachedDOM, false);\r
252         releaseParentDOM(true);\r
253         return cachedDOM;\r
254     }\r
255     \r
256     // If we get here, we didn't have a usable DOM.\r
257     bool bindDocument=false;\r
258     if (m_xml.empty()) {\r
259         // Fresh signature, so we just create an empty one.\r
260         log.debug("creating empty Signature element");\r
261         if (!document) {\r
262             document=DOMImplementationRegistry::getDOMImplementation(NULL)->createDocument();\r
263             bindDocument=true;\r
264         }\r
265         m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignature();\r
266         m_signature->setDSIGNSPrefix(XMLConstants::XMLSIG_PREFIX);\r
267         cachedDOM=m_signature->createBlankSignature(document, getCanonicalizationMethod(), getSignatureAlgorithm());\r
268     }\r
269     else {\r
270         // We need to reparse the XML we saved off into a new DOM.\r
271         MemBufInputSource src(reinterpret_cast<const XMLByte*>(m_xml.c_str()),m_xml.length(),"XMLSecSignatureImpl");\r
272         Wrapper4InputSource dsrc(&src,false);\r
273         log.debug("parsing Signature XML back into DOM tree");\r
274         DOMDocument* internalDoc=XMLToolingConfig::getConfig().getParser().parse(dsrc);\r
275         if (document) {\r
276             // The caller insists on using his own document, so we now have to import the thing\r
277             // into it. Then we're just dumping the one we built.\r
278             log.debug("reimporting new DOM into caller-supplied document");\r
279             cachedDOM=static_cast<DOMElement*>(document->importNode(internalDoc->getDocumentElement(), true));\r
280             internalDoc->release();\r
281         }\r
282         else {\r
283             // We just bind the document we built to the object as the result.\r
284             cachedDOM=static_cast<DOMElement*>(internalDoc->getDocumentElement());\r
285             document=internalDoc;\r
286             bindDocument=true;\r
287         }\r
288 \r
289         // Now reload the signature from the DOM.\r
290         try {\r
291             m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignatureFromDOM(\r
292                 document, cachedDOM\r
293                 );\r
294             m_signature->load();\r
295         }\r
296         catch(XSECException& e) {\r
297             if (bindDocument)\r
298                 document->release();\r
299             auto_ptr_char temp(e.getMsg());\r
300             throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + temp.get());\r
301         }\r
302         catch(XSECCryptoException& e) {\r
303             if (bindDocument)\r
304                 document->release();\r
305             throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + e.getMsg());\r
306         }\r
307     }\r
308     \r
309     // Recache the DOM and clear the serialized copy.\r
310     setDocumentElement(document, cachedDOM);\r
311     log.debug("caching DOM for Signature (document is %sbound)", bindDocument ? "" : "not ");\r
312     setDOM(cachedDOM, bindDocument);\r
313     releaseParentDOM(true);\r
314     m_xml.erase();\r
315     return cachedDOM;\r
316 }\r
317 \r
318 DOMElement* XMLSecSignatureImpl::marshall(DOMElement* parentElement, const vector<Signature*>* sigs) const\r
319 {\r
320 #ifdef _DEBUG\r
321     xmltooling::NDC ndc("marshall");\r
322 #endif\r
323     \r
324     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".Signature");\r
325     log.debug("marshalling ds:Signature");\r
326 \r
327     DOMElement* cachedDOM=getDOM();\r
328     if (cachedDOM) {\r
329         if (parentElement->getOwnerDocument()==cachedDOM->getOwnerDocument()) {\r
330             log.debug("Signature has a usable cached DOM, reusing it");\r
331             parentElement->appendChild(cachedDOM);\r
332             releaseParentDOM(true);\r
333             return cachedDOM;\r
334         }\r
335         \r
336         // We have a DOM but it doesn't match the document we were given, so we import\r
337         // it into the new document.\r
338         cachedDOM=static_cast<DOMElement*>(parentElement->getOwnerDocument()->importNode(cachedDOM, true));\r
339 \r
340         try {\r
341             XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->releaseSignature(m_signature);\r
342             m_signature=NULL;\r
343             m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignatureFromDOM(\r
344                 parentElement->getOwnerDocument(), cachedDOM\r
345                 );\r
346             m_signature->load();\r
347         }\r
348         catch(XSECException& e) {\r
349             auto_ptr_char temp(e.getMsg());\r
350             throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + temp.get());\r
351         }\r
352         catch(XSECCryptoException& e) {\r
353             throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + e.getMsg());\r
354         }\r
355 \r
356         // Recache the DOM.\r
357         parentElement->appendChild(cachedDOM);\r
358         log.debug("caching imported DOM for Signature");\r
359         setDOM(cachedDOM, false);\r
360         releaseParentDOM(true);\r
361         return cachedDOM;\r
362     }\r
363     \r
364     // If we get here, we didn't have a usable DOM.\r
365     if (m_xml.empty()) {\r
366         // Fresh signature, so we just create an empty one.\r
367         log.debug("creating empty Signature element");\r
368         m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignature();\r
369         m_signature->setDSIGNSPrefix(XMLConstants::XMLSIG_PREFIX);\r
370         cachedDOM=m_signature->createBlankSignature(\r
371             parentElement->getOwnerDocument(), getCanonicalizationMethod(), getSignatureAlgorithm()\r
372             );\r
373     }\r
374     else {\r
375         MemBufInputSource src(reinterpret_cast<const XMLByte*>(m_xml.c_str()),m_xml.length(),"XMLSecSignatureImpl");\r
376         Wrapper4InputSource dsrc(&src,false);\r
377         log.debug("parsing XML back into DOM tree");\r
378         DOMDocument* internalDoc=XMLToolingConfig::getConfig().getParser().parse(dsrc);\r
379         \r
380         log.debug("reimporting new DOM into caller-supplied document");\r
381         cachedDOM=static_cast<DOMElement*>(parentElement->getOwnerDocument()->importNode(internalDoc->getDocumentElement(),true));\r
382         internalDoc->release();\r
383 \r
384         // Now reload the signature from the DOM.\r
385         try {\r
386             m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignatureFromDOM(\r
387                 parentElement->getOwnerDocument(), cachedDOM\r
388                 );\r
389             m_signature->load();\r
390         }\r
391         catch(XSECException& e) {\r
392             auto_ptr_char temp(e.getMsg());\r
393             throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + temp.get());\r
394         }\r
395         catch(XSECCryptoException& e) {\r
396             throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + e.getMsg());\r
397         }\r
398     }\r
399 \r
400     // Recache the DOM and clear the serialized copy.\r
401     parentElement->appendChild(cachedDOM);\r
402     log.debug("caching DOM for Signature");\r
403     setDOM(cachedDOM, false);\r
404     releaseParentDOM(true);\r
405     m_xml.erase();\r
406     return cachedDOM;\r
407 }\r
408 \r
409 XMLObject* XMLSecSignatureImpl::unmarshall(DOMElement* element, bool bindDocument)\r
410 {\r
411     Category::getInstance(XMLTOOLING_LOGCAT".Signature").debug("unmarshalling ds:Signature");\r
412 \r
413     try {\r
414         m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignatureFromDOM(\r
415             element->getOwnerDocument(), element\r
416             );\r
417         m_signature->load();\r
418     }\r
419     catch(XSECException& e) {\r
420         auto_ptr_char temp(e.getMsg());\r
421         throw UnmarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + temp.get());\r
422     }\r
423     catch(XSECCryptoException& e) {\r
424         throw UnmarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + e.getMsg());\r
425     }\r
426 \r
427     setDOM(element, bindDocument);\r
428     return this;\r
429 }\r
430 \r
431 void XMLSecSignatureImpl::registerValidator(Validator* validator)\r
432 {\r
433     m_validators.push_back(validator);\r
434 }\r
435 \r
436 void XMLSecSignatureImpl::deregisterValidator(Validator* validator)\r
437 {\r
438     for (vector<Validator*>::iterator i=m_validators.begin(); i!=m_validators.end(); i++) {\r
439         if ((*i)==validator) {\r
440             m_validators.erase(i);\r
441             return;\r
442         }\r
443     }\r
444 }\r
445 \r
446 void XMLSecSignatureImpl::deregisterAll()\r
447 {\r
448     for_each(m_validators.begin(),m_validators.end(),cleanup<Validator>());\r
449     m_validators.clear();\r
450 }\r
451 \r
452 class _validate : public binary_function<const XMLObject*,bool,void> {\r
453 public:\r
454     void operator()(const XMLObject* obj, bool propagate) const {\r
455         const ValidatingXMLObject* val = dynamic_cast<const ValidatingXMLObject*>(obj);\r
456         if (val) {\r
457             val->validate(propagate);\r
458         }\r
459     }\r
460 };\r
461 \r
462 void XMLSecSignatureImpl::validate(bool validateDescendants) const\r
463 {\r
464     for_each(\r
465         m_validators.begin(),m_validators.end(),\r
466         bind2nd(mem_fun<void,Validator,const XMLObject*>(&Validator::validate),this)\r
467         );\r
468     \r
469     if (validateDescendants && m_keyInfo) {\r
470         m_keyInfo->validate(validateDescendants);\r
471     }\r
472 }\r
473 \r
474 Signature* SignatureBuilder::buildObject(\r
475     const XMLCh* nsURI, const XMLCh* localName, const XMLCh* prefix, const QName* schemaType\r
476     ) const\r
477 {\r
478     if (!XMLString::equals(nsURI,XMLConstants::XMLSIG_NS) || !XMLString::equals(localName,Signature::LOCAL_NAME))\r
479         throw XMLObjectException("XMLSecSignatureBuilder requires standard Signature element name.");\r
480     return buildObject();\r
481 }\r
482 \r
483 Signature* SignatureBuilder::buildObject() const\r
484 {\r
485     return new XMLSecSignatureImpl();\r
486 }\r
487 \r
488 const XMLCh Signature::LOCAL_NAME[] = UNICODE_LITERAL_9(S,i,g,n,a,t,u,r,e);\r