2 * Copyright 2001-2007 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * XMLSecSignatureImpl.cpp
20 * Signature class for XMLSec-based signature-handling
24 #include "exceptions.h"
26 #include "impl/UnknownElement.h"
27 #include "security/Credential.h"
28 #include "signature/KeyInfo.h"
29 #include "signature/Signature.h"
31 #include "util/XMLConstants.h"
32 #include "util/XMLHelper.h"
34 #include <xercesc/framework/MemBufInputSource.hpp>
35 #include <xercesc/framework/Wrapper4InputSource.hpp>
36 #include <xercesc/util/XMLUniDefs.hpp>
37 #include <xsec/dsig/DSIGKeyInfoX509.hpp>
38 #include <xsec/dsig/DSIGReference.hpp>
39 #include <xsec/enc/XSECCryptoException.hpp>
40 #include <xsec/framework/XSECAlgorithmHandler.hpp>
41 #include <xsec/framework/XSECAlgorithmMapper.hpp>
42 #include <xsec/framework/XSECException.hpp>
43 #include <xsec/transformers/TXFMSB.hpp>
44 #include <xsec/transformers/TXFMChain.hpp>
45 #include <xsec/transformers/TXFMOutputFile.hpp>
47 using namespace xmlsignature;
48 using namespace xmltooling::logging;
49 using namespace xmltooling;
50 using namespace xercesc;
52 using xmlconstants::XMLSIG_NS;
53 using xmlconstants::XMLSIG_PREFIX;
55 #if defined (_MSC_VER)
56 #pragma warning( push )
57 #pragma warning( disable : 4250 4251 )
60 namespace xmlsignature {
62 class XMLTOOL_DLLLOCAL XMLSecSignatureImpl : public UnknownElementImpl, public virtual Signature
65 XMLSecSignatureImpl() : AbstractXMLObject(XMLSIG_NS, Signature::LOCAL_NAME, XMLSIG_PREFIX),
66 UnknownElementImpl(XMLSIG_NS, Signature::LOCAL_NAME, XMLSIG_PREFIX),
67 m_signature(NULL), m_c14n(NULL), m_sm(NULL), m_key(NULL), m_keyInfo(NULL), m_reference(NULL) {}
68 virtual ~XMLSecSignatureImpl();
70 void releaseDOM() const;
71 void releaseChildrenDOM(bool propagateRelease=true) const {
73 m_keyInfo->releaseDOM();
75 m_keyInfo->releaseChildrenDOM();
78 XMLObject* clone() const;
79 Signature* cloneSignature() const;
81 DOMElement* marshall(DOMDocument* document=NULL, const vector<Signature*>* sigs=NULL, const Credential* credential=NULL) const;
82 DOMElement* marshall(DOMElement* parentElement, const vector<Signature*>* sigs=NULL, const Credential* credential=NULL) const;
83 XMLObject* unmarshall(DOMElement* element, bool bindDocument=false);
86 const XMLCh* getCanonicalizationMethod() const {
88 return canonicalizationMethod2UNICODEURI(m_signature->getCanonicalizationMethod());
89 return m_c14n ? m_c14n : DSIGConstants::s_unicodeStrURIEXC_C14N_NOC;
91 const XMLCh* getSignatureAlgorithm() const {
92 if (!m_sm && m_signature) {
94 if (signatureHashMethod2URI(sURI, m_signature->getSignatureMethod(), m_signature->getHashMethod()) == false)
96 m_sm = XMLString::replicate(sURI.sbStrToXMLCh());
98 return m_sm ? m_sm : DSIGConstants::s_unicodeStrURIRSA_SHA1;
101 KeyInfo* getKeyInfo() const { return m_keyInfo; }
102 ContentReference* getContentReference() const { return m_reference; }
103 DSIGSignature* getXMLSignature() const { return m_signature; }
106 void setCanonicalizationMethod(const XMLCh* c14n) { m_c14n = prepareForAssignment(m_c14n,c14n); }
107 void setSignatureAlgorithm(const XMLCh* sm) { m_sm = prepareForAssignment(m_sm,sm); }
108 void setSigningKey(XSECCryptoKey* signingKey) {
112 void setKeyInfo(KeyInfo* keyInfo) {
113 prepareForAssignment(m_keyInfo, keyInfo);
116 void setContentReference(ContentReference* reference) {
118 m_reference=reference;
121 void sign(const Credential* credential=NULL);
124 mutable DSIGSignature* m_signature;
127 XSECCryptoKey* m_key;
128 mutable KeyInfo* m_keyInfo;
129 ContentReference* m_reference;
134 #if defined (_MSC_VER)
135 #pragma warning( pop )
138 XMLSecSignatureImpl::~XMLSecSignatureImpl()
140 // Release the associated signature.
142 XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->releaseSignature(m_signature);
144 XMLString::release(&m_c14n);
145 XMLString::release(&m_sm);
151 void XMLSecSignatureImpl::releaseDOM() const
154 // This should save off the DOM
155 UnknownElementImpl::releaseDOM();
157 // Release the associated signature.
159 XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->releaseSignature(m_signature);
165 XMLObject* XMLSecSignatureImpl::clone() const
167 return cloneSignature();
170 Signature* XMLSecSignatureImpl::cloneSignature() const
172 XMLSecSignatureImpl* ret=new XMLSecSignatureImpl();
174 ret->m_c14n=XMLString::replicate(m_c14n);
175 ret->m_sm=XMLString::replicate(m_sm);
177 ret->m_key=m_key->clone();
179 ret->m_keyInfo=m_keyInfo->cloneKeyInfo();
181 // If there's no XML locally, serialize this object into the new one, otherwise just copy it over.
183 serialize(ret->m_xml);
190 void XMLSecSignatureImpl::sign(const Credential* credential)
192 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".Signature");
193 log.debug("applying signature");
196 throw SignatureException("Only a marshalled Signature object can be signed.");
197 else if (!m_reference)
198 throw SignatureException("No ContentReference object set for signature creation.");
200 XSECCryptoKey* key = credential ? credential->getPrivateKey() : m_key;
202 throw SignatureException("No signing key available for signature creation.");
205 log.debug("creating signature reference(s)");
206 DSIGReferenceList* refs = m_signature->getReferenceList();
207 while (refs && refs->getSize())
208 delete refs->removeReference(0);
209 m_reference->createReferences(m_signature);
211 log.debug("computing signature");
212 m_signature->setSigningKey(key->clone());
215 catch(XSECException& e) {
216 auto_ptr_char temp(e.getMsg());
217 throw SignatureException(string("Caught an XMLSecurity exception while signing: ") + temp.get());
219 catch(XSECCryptoException& e) {
220 throw SignatureException(string("Caught an XMLSecurity exception while signing: ") + e.getMsg());
224 DOMElement* XMLSecSignatureImpl::marshall(DOMDocument* document, const vector<Signature*>* sigs, const Credential* credential) const
227 xmltooling::NDC ndc("marshall");
230 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLObject.Signature");
231 log.debug("marshalling ds:Signature");
233 DOMElement* cachedDOM=getDOM();
235 if (!document || document==cachedDOM->getOwnerDocument()) {
236 log.debug("Signature has a usable cached DOM, reusing it");
238 setDocumentElement(cachedDOM->getOwnerDocument(),cachedDOM);
239 releaseParentDOM(true);
243 // We have a DOM but it doesn't match the document we were given. This both sucks and blows.
244 // Without an adoptNode option to maintain the child pointers, we have to either import the
245 // DOM while somehow reassigning all the nested references (which amounts to a complete
246 // *unmarshall* operation), or we just release the existing DOM and hope that we can get
247 // it back. This depends on all objects being able to preserve their DOM at all costs.
248 releaseChildrenDOM(true);
252 // If we get here, we didn't have a usable DOM.
253 bool bindDocument=false;
255 // Fresh signature, so we just create an empty one.
256 log.debug("creating empty Signature element");
258 document=DOMImplementationRegistry::getDOMImplementation(NULL)->createDocument();
261 DSIGSignature* temp=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignature();
262 temp->setDSIGNSPrefix(XMLSIG_PREFIX);
263 cachedDOM=temp->createBlankSignature(document, getCanonicalizationMethod(), getSignatureAlgorithm());
267 // We need to reparse the XML we saved off into a new DOM.
268 MemBufInputSource src(reinterpret_cast<const XMLByte*>(m_xml.c_str()),m_xml.length(),"XMLSecSignatureImpl");
269 Wrapper4InputSource dsrc(&src,false);
270 log.debug("parsing Signature XML back into DOM tree");
271 DOMDocument* internalDoc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
273 // The caller insists on using his own document, so we now have to import the thing
274 // into it. Then we're just dumping the one we built.
275 log.debug("reimporting new DOM into caller-supplied document");
276 cachedDOM=static_cast<DOMElement*>(document->importNode(internalDoc->getDocumentElement(), true));
277 internalDoc->release();
280 // We just bind the document we built to the object as the result.
281 cachedDOM=static_cast<DOMElement*>(internalDoc->getDocumentElement());
282 document=internalDoc;
286 // Now reload the signature from the DOM.
288 m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignatureFromDOM(
293 catch(XSECException& e) {
296 auto_ptr_char temp(e.getMsg());
297 throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + temp.get());
299 catch(XSECCryptoException& e) {
302 throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + e.getMsg());
306 // Marshall KeyInfo data.
310 m_keyInfo = credential->getKeyInfo();
312 if (m_keyInfo && (!m_signature->getKeyInfoList() || m_signature->getKeyInfoList()->isEmpty())) {
313 m_keyInfo->marshall(cachedDOM);
316 // Recache the DOM and clear the serialized copy.
317 setDocumentElement(document, cachedDOM);
318 log.debug("caching DOM for Signature (document is %sbound)", bindDocument ? "" : "not ");
319 setDOM(cachedDOM, bindDocument);
320 releaseParentDOM(true);
325 DOMElement* XMLSecSignatureImpl::marshall(DOMElement* parentElement, const vector<Signature*>* sigs, const Credential* credential) const
328 xmltooling::NDC ndc("marshall");
331 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLObject.Signature");
332 log.debug("marshalling ds:Signature");
334 DOMElement* cachedDOM=getDOM();
336 if (parentElement->getOwnerDocument()==cachedDOM->getOwnerDocument()) {
337 log.debug("Signature has a usable cached DOM, reusing it");
338 if (parentElement!=cachedDOM->getParentNode()) {
339 parentElement->appendChild(cachedDOM);
340 releaseParentDOM(true);
345 // We have a DOM but it doesn't match the document we were given. This both sucks and blows.
346 // Without an adoptNode option to maintain the child pointers, we have to either import the
347 // DOM while somehow reassigning all the nested references (which amounts to a complete
348 // *unmarshall* operation), or we just release the existing DOM and hope that we can get
349 // it back. This depends on all objects being able to preserve their DOM at all costs.
350 releaseChildrenDOM(true);
354 // If we get here, we didn't have a usable DOM.
356 // Fresh signature, so we just create an empty one.
357 log.debug("creating empty Signature element");
358 DSIGSignature* temp=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignature();
359 temp->setDSIGNSPrefix(XMLSIG_PREFIX);
360 cachedDOM=temp->createBlankSignature(parentElement->getOwnerDocument(), getCanonicalizationMethod(), getSignatureAlgorithm());
364 MemBufInputSource src(reinterpret_cast<const XMLByte*>(m_xml.c_str()),m_xml.length(),"XMLSecSignatureImpl");
365 Wrapper4InputSource dsrc(&src,false);
366 log.debug("parsing XML back into DOM tree");
367 DOMDocument* internalDoc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
369 log.debug("reimporting new DOM into caller-supplied document");
370 cachedDOM=static_cast<DOMElement*>(parentElement->getOwnerDocument()->importNode(internalDoc->getDocumentElement(),true));
371 internalDoc->release();
373 // Now reload the signature from the DOM.
375 m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignatureFromDOM(
376 parentElement->getOwnerDocument(), cachedDOM
380 catch(XSECException& e) {
381 auto_ptr_char temp(e.getMsg());
382 throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + temp.get());
384 catch(XSECCryptoException& e) {
385 throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + e.getMsg());
389 // Marshall KeyInfo data.
393 m_keyInfo = credential->getKeyInfo();
395 if (m_keyInfo && (!m_signature->getKeyInfoList() || m_signature->getKeyInfoList()->isEmpty())) {
396 m_keyInfo->marshall(cachedDOM);
399 // Recache the DOM and clear the serialized copy.
400 parentElement->appendChild(cachedDOM);
401 log.debug("caching DOM for Signature");
402 setDOM(cachedDOM, false);
403 releaseParentDOM(true);
408 XMLObject* XMLSecSignatureImpl::unmarshall(DOMElement* element, bool bindDocument)
410 Category::getInstance(XMLTOOLING_LOGCAT".XMLObject.Signature").debug("unmarshalling ds:Signature");
413 m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignatureFromDOM(
414 element->getOwnerDocument(), element
418 catch(XSECException& e) {
419 auto_ptr_char temp(e.getMsg());
420 throw UnmarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + temp.get());
422 catch(XSECCryptoException& e) {
423 throw UnmarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + e.getMsg());
426 setDOM(element, bindDocument);
430 #ifdef HAVE_COVARIANT_RETURNS
435 SignatureBuilder::buildObject(
436 const XMLCh* nsURI, const XMLCh* localName, const XMLCh* prefix, const xmltooling::QName* schemaType
439 if (!XMLString::equals(nsURI,XMLSIG_NS) || !XMLString::equals(localName,Signature::LOCAL_NAME))
440 throw XMLObjectException("XMLSecSignatureBuilder requires standard Signature element name.");
441 return buildObject();
444 #ifdef HAVE_COVARIANT_RETURNS
449 SignatureBuilder::buildObject() const
451 return new XMLSecSignatureImpl();
454 const XMLCh Signature::LOCAL_NAME[] = UNICODE_LITERAL_9(S,i,g,n,a,t,u,r,e);
456 // Raw signature methods.
458 unsigned int Signature::createRawSignature(
459 XSECCryptoKey* key, const XMLCh* sigAlgorithm, const char* in, unsigned int in_len, char* out, unsigned int out_len
463 XSECAlgorithmHandler* handler = XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(sigAlgorithm);
465 auto_ptr_char alg(sigAlgorithm);
466 throw SignatureException("Unsupported signature algorithm ($1).", params(1,alg.get()));
469 // Move input into a safeBuffer to source the transform chain.
471 sb.sbStrncpyIn(in,in_len);
472 TXFMSB* sbt = new TXFMSB(NULL);
473 sbt->setInput(sb, in_len);
477 unsigned int siglen = handler->signToSafeBuffer(&tx, sigAlgorithm, key, out_len-1, sbout);
478 if (siglen >= out_len)
479 throw SignatureException("Signature size exceeded output buffer size.");
481 // Push all non-whitespace into buffer.
482 unsigned int ret_len = 0;
483 const char* source = sbout.rawCharBuffer();
485 if (isspace(*source))
495 catch(XSECException& e) {
496 auto_ptr_char temp(e.getMsg());
497 throw SignatureException(string("Caught an XMLSecurity exception while creating raw signature: ") + temp.get());
499 catch(XSECCryptoException& e) {
500 throw SignatureException(string("Caught an XMLSecurity exception while creating raw signature: ") + e.getMsg());
504 bool Signature::verifyRawSignature(
505 XSECCryptoKey* key, const XMLCh* sigAlgorithm, const char* signature, const char* in, unsigned int in_len
509 XSECAlgorithmHandler* handler = XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(sigAlgorithm);
511 auto_ptr_char alg(sigAlgorithm);
512 throw SignatureException("Unsupported signature algorithm ($1).", params(1,alg.get()));
515 // Move input into a safeBuffer to source the transform chain.
517 sb.sbStrncpyIn(in,in_len);
518 TXFMSB* sbt = new TXFMSB(NULL);
519 sbt->setInput(sb, in_len);
523 return handler->verifyBase64Signature(&tx, sigAlgorithm, signature, 0, key);
525 catch(XSECException& e) {
526 auto_ptr_char temp(e.getMsg());
527 throw SignatureException(string("Caught an XMLSecurity exception while verifying raw signature: ") + temp.get());
529 catch(XSECCryptoException& e) {
530 throw SignatureException(string("Caught an XMLSecurity exception while verifying raw signature: ") + e.getMsg());