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;
51 using xmlconstants::XMLSIG_NS;
52 using xmlconstants::XMLSIG_PREFIX;
54 #if defined (_MSC_VER)
55 #pragma warning( push )
56 #pragma warning( disable : 4250 4251 )
59 namespace xmlsignature {
61 class XMLTOOL_DLLLOCAL XMLSecSignatureImpl : public UnknownElementImpl, public virtual Signature
64 XMLSecSignatureImpl() : AbstractXMLObject(XMLSIG_NS, Signature::LOCAL_NAME, XMLSIG_PREFIX),
65 UnknownElementImpl(XMLSIG_NS, Signature::LOCAL_NAME, XMLSIG_PREFIX),
66 m_signature(NULL), m_c14n(NULL), m_sm(NULL), m_key(NULL), m_keyInfo(NULL), m_reference(NULL) {}
67 virtual ~XMLSecSignatureImpl();
69 void releaseDOM() const;
70 void releaseChildrenDOM(bool propagateRelease=true) const {
72 m_keyInfo->releaseDOM();
74 m_keyInfo->releaseChildrenDOM();
77 XMLObject* clone() const;
78 Signature* cloneSignature() const;
80 DOMElement* marshall(DOMDocument* document=NULL, const vector<Signature*>* sigs=NULL, const Credential* credential=NULL) const;
81 DOMElement* marshall(DOMElement* parentElement, const vector<Signature*>* sigs=NULL, const Credential* credential=NULL) const;
82 XMLObject* unmarshall(DOMElement* element, bool bindDocument=false);
85 const XMLCh* getCanonicalizationMethod() const {
87 return canonicalizationMethod2UNICODEURI(m_signature->getCanonicalizationMethod());
88 return m_c14n ? m_c14n : DSIGConstants::s_unicodeStrURIEXC_C14N_NOC;
90 const XMLCh* getSignatureAlgorithm() const {
91 if (!m_sm && m_signature) {
93 if (signatureHashMethod2URI(sURI, m_signature->getSignatureMethod(), m_signature->getHashMethod()) == false)
95 m_sm = XMLString::replicate(sURI.sbStrToXMLCh());
97 return m_sm ? m_sm : DSIGConstants::s_unicodeStrURIRSA_SHA1;
100 KeyInfo* getKeyInfo() const { return m_keyInfo; }
101 ContentReference* getContentReference() const { return m_reference; }
102 DSIGSignature* getXMLSignature() const { return m_signature; }
105 void setCanonicalizationMethod(const XMLCh* c14n) { m_c14n = prepareForAssignment(m_c14n,c14n); }
106 void setSignatureAlgorithm(const XMLCh* sm) { m_sm = prepareForAssignment(m_sm,sm); }
107 void setSigningKey(XSECCryptoKey* signingKey) {
111 void setKeyInfo(KeyInfo* keyInfo) {
112 prepareForAssignment(m_keyInfo, keyInfo);
115 void setContentReference(ContentReference* reference) {
117 m_reference=reference;
120 void sign(const Credential* credential=NULL);
123 mutable DSIGSignature* m_signature;
126 XSECCryptoKey* m_key;
127 mutable KeyInfo* m_keyInfo;
128 ContentReference* m_reference;
133 #if defined (_MSC_VER)
134 #pragma warning( pop )
137 XMLSecSignatureImpl::~XMLSecSignatureImpl()
139 // Release the associated signature.
141 XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->releaseSignature(m_signature);
143 XMLString::release(&m_c14n);
144 XMLString::release(&m_sm);
150 void XMLSecSignatureImpl::releaseDOM() const
153 // This should save off the DOM
154 UnknownElementImpl::releaseDOM();
156 // Release the associated signature.
158 XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->releaseSignature(m_signature);
164 XMLObject* XMLSecSignatureImpl::clone() const
166 return cloneSignature();
169 Signature* XMLSecSignatureImpl::cloneSignature() const
171 XMLSecSignatureImpl* ret=new XMLSecSignatureImpl();
173 ret->m_c14n=XMLString::replicate(m_c14n);
174 ret->m_sm=XMLString::replicate(m_sm);
176 ret->m_key=m_key->clone();
178 ret->m_keyInfo=m_keyInfo->cloneKeyInfo();
180 // If there's no XML locally, serialize this object into the new one, otherwise just copy it over.
182 serialize(ret->m_xml);
189 void XMLSecSignatureImpl::sign(const Credential* credential)
191 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".Signature");
192 log.debug("applying signature");
195 throw SignatureException("Only a marshalled Signature object can be signed.");
196 else if (!m_reference)
197 throw SignatureException("No ContentReference object set for signature creation.");
199 XSECCryptoKey* key = credential ? credential->getPrivateKey() : m_key;
201 throw SignatureException("No signing key available for signature creation.");
204 log.debug("creating signature reference(s)");
205 DSIGReferenceList* refs = m_signature->getReferenceList();
206 while (refs && refs->getSize())
207 delete refs->removeReference(0);
208 m_reference->createReferences(m_signature);
210 log.debug("computing signature");
211 m_signature->setSigningKey(key->clone());
214 catch(XSECException& e) {
215 auto_ptr_char temp(e.getMsg());
216 throw SignatureException(string("Caught an XMLSecurity exception while signing: ") + temp.get());
218 catch(XSECCryptoException& e) {
219 throw SignatureException(string("Caught an XMLSecurity exception while signing: ") + e.getMsg());
223 DOMElement* XMLSecSignatureImpl::marshall(DOMDocument* document, const vector<Signature*>* sigs, const Credential* credential) const
226 xmltooling::NDC ndc("marshall");
229 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLObject.Signature");
230 log.debug("marshalling ds:Signature");
232 DOMElement* cachedDOM=getDOM();
234 if (!document || document==cachedDOM->getOwnerDocument()) {
235 log.debug("Signature has a usable cached DOM, reusing it");
237 setDocumentElement(cachedDOM->getOwnerDocument(),cachedDOM);
238 releaseParentDOM(true);
242 // We have a DOM but it doesn't match the document we were given. This both sucks and blows.
243 // Without an adoptNode option to maintain the child pointers, we have to either import the
244 // DOM while somehow reassigning all the nested references (which amounts to a complete
245 // *unmarshall* operation), or we just release the existing DOM and hope that we can get
246 // it back. This depends on all objects being able to preserve their DOM at all costs.
247 releaseChildrenDOM(true);
251 // If we get here, we didn't have a usable DOM.
252 bool bindDocument=false;
254 // Fresh signature, so we just create an empty one.
255 log.debug("creating empty Signature element");
257 document=DOMImplementationRegistry::getDOMImplementation(NULL)->createDocument();
260 DSIGSignature* temp=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignature();
261 temp->setDSIGNSPrefix(XMLSIG_PREFIX);
262 cachedDOM=temp->createBlankSignature(document, getCanonicalizationMethod(), getSignatureAlgorithm());
266 // We need to reparse the XML we saved off into a new DOM.
267 MemBufInputSource src(reinterpret_cast<const XMLByte*>(m_xml.c_str()),m_xml.length(),"XMLSecSignatureImpl");
268 Wrapper4InputSource dsrc(&src,false);
269 log.debug("parsing Signature XML back into DOM tree");
270 DOMDocument* internalDoc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
272 // The caller insists on using his own document, so we now have to import the thing
273 // into it. Then we're just dumping the one we built.
274 log.debug("reimporting new DOM into caller-supplied document");
275 cachedDOM=static_cast<DOMElement*>(document->importNode(internalDoc->getDocumentElement(), true));
276 internalDoc->release();
279 // We just bind the document we built to the object as the result.
280 cachedDOM=static_cast<DOMElement*>(internalDoc->getDocumentElement());
281 document=internalDoc;
285 // Now reload the signature from the DOM.
287 m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignatureFromDOM(
292 catch(XSECException& e) {
295 auto_ptr_char temp(e.getMsg());
296 throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + temp.get());
298 catch(XSECCryptoException& e) {
301 throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + e.getMsg());
305 // Marshall KeyInfo data.
309 m_keyInfo = credential->getKeyInfo();
311 if (m_keyInfo && (!m_signature->getKeyInfoList() || m_signature->getKeyInfoList()->isEmpty())) {
312 m_keyInfo->marshall(cachedDOM);
315 // Recache the DOM and clear the serialized copy.
316 setDocumentElement(document, cachedDOM);
317 log.debug("caching DOM for Signature (document is %sbound)", bindDocument ? "" : "not ");
318 setDOM(cachedDOM, bindDocument);
319 releaseParentDOM(true);
324 DOMElement* XMLSecSignatureImpl::marshall(DOMElement* parentElement, const vector<Signature*>* sigs, const Credential* credential) const
327 xmltooling::NDC ndc("marshall");
330 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLObject.Signature");
331 log.debug("marshalling ds:Signature");
333 DOMElement* cachedDOM=getDOM();
335 if (parentElement->getOwnerDocument()==cachedDOM->getOwnerDocument()) {
336 log.debug("Signature has a usable cached DOM, reusing it");
337 if (parentElement!=cachedDOM->getParentNode()) {
338 parentElement->appendChild(cachedDOM);
339 releaseParentDOM(true);
344 // We have a DOM but it doesn't match the document we were given. This both sucks and blows.
345 // Without an adoptNode option to maintain the child pointers, we have to either import the
346 // DOM while somehow reassigning all the nested references (which amounts to a complete
347 // *unmarshall* operation), or we just release the existing DOM and hope that we can get
348 // it back. This depends on all objects being able to preserve their DOM at all costs.
349 releaseChildrenDOM(true);
353 // If we get here, we didn't have a usable DOM.
355 // Fresh signature, so we just create an empty one.
356 log.debug("creating empty Signature element");
357 DSIGSignature* temp=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignature();
358 temp->setDSIGNSPrefix(XMLSIG_PREFIX);
359 cachedDOM=temp->createBlankSignature(parentElement->getOwnerDocument(), getCanonicalizationMethod(), getSignatureAlgorithm());
363 MemBufInputSource src(reinterpret_cast<const XMLByte*>(m_xml.c_str()),m_xml.length(),"XMLSecSignatureImpl");
364 Wrapper4InputSource dsrc(&src,false);
365 log.debug("parsing XML back into DOM tree");
366 DOMDocument* internalDoc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
368 log.debug("reimporting new DOM into caller-supplied document");
369 cachedDOM=static_cast<DOMElement*>(parentElement->getOwnerDocument()->importNode(internalDoc->getDocumentElement(),true));
370 internalDoc->release();
372 // Now reload the signature from the DOM.
374 m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignatureFromDOM(
375 parentElement->getOwnerDocument(), cachedDOM
379 catch(XSECException& e) {
380 auto_ptr_char temp(e.getMsg());
381 throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + temp.get());
383 catch(XSECCryptoException& e) {
384 throw MarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + e.getMsg());
388 // Marshall KeyInfo data.
392 m_keyInfo = credential->getKeyInfo();
394 if (m_keyInfo && (!m_signature->getKeyInfoList() || m_signature->getKeyInfoList()->isEmpty())) {
395 m_keyInfo->marshall(cachedDOM);
398 // Recache the DOM and clear the serialized copy.
399 parentElement->appendChild(cachedDOM);
400 log.debug("caching DOM for Signature");
401 setDOM(cachedDOM, false);
402 releaseParentDOM(true);
407 XMLObject* XMLSecSignatureImpl::unmarshall(DOMElement* element, bool bindDocument)
409 Category::getInstance(XMLTOOLING_LOGCAT".XMLObject.Signature").debug("unmarshalling ds:Signature");
412 m_signature=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newSignatureFromDOM(
413 element->getOwnerDocument(), element
417 catch(XSECException& e) {
418 auto_ptr_char temp(e.getMsg());
419 throw UnmarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + temp.get());
421 catch(XSECCryptoException& e) {
422 throw UnmarshallingException(string("Caught an XMLSecurity exception while loading signature: ") + e.getMsg());
425 setDOM(element, bindDocument);
429 #ifdef HAVE_COVARIANT_RETURNS
434 SignatureBuilder::buildObject(
435 const XMLCh* nsURI, const XMLCh* localName, const XMLCh* prefix, const QName* schemaType
438 if (!XMLString::equals(nsURI,XMLSIG_NS) || !XMLString::equals(localName,Signature::LOCAL_NAME))
439 throw XMLObjectException("XMLSecSignatureBuilder requires standard Signature element name.");
440 return buildObject();
443 #ifdef HAVE_COVARIANT_RETURNS
448 SignatureBuilder::buildObject() const
450 return new XMLSecSignatureImpl();
453 const XMLCh Signature::LOCAL_NAME[] = UNICODE_LITERAL_9(S,i,g,n,a,t,u,r,e);
455 // Raw signature methods.
457 unsigned int Signature::createRawSignature(
458 XSECCryptoKey* key, const XMLCh* sigAlgorithm, const char* in, unsigned int in_len, char* out, unsigned int out_len
462 XSECAlgorithmHandler* handler = XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(sigAlgorithm);
464 auto_ptr_char alg(sigAlgorithm);
465 throw SignatureException("Unsupported signature algorithm ($1).", params(1,alg.get()));
468 // Move input into a safeBuffer to source the transform chain.
470 sb.sbStrncpyIn(in,in_len);
471 TXFMSB* sbt = new TXFMSB(NULL);
472 sbt->setInput(sb, in_len);
476 unsigned int siglen = handler->signToSafeBuffer(&tx, sigAlgorithm, key, out_len-1, sbout);
477 if (siglen >= out_len)
478 throw SignatureException("Signature size exceeded output buffer size.");
480 // Push all non-whitespace into buffer.
481 unsigned int ret_len = 0;
482 const char* source = sbout.rawCharBuffer();
484 if (isspace(*source))
494 catch(XSECException& e) {
495 auto_ptr_char temp(e.getMsg());
496 throw SignatureException(string("Caught an XMLSecurity exception while creating raw signature: ") + temp.get());
498 catch(XSECCryptoException& e) {
499 throw SignatureException(string("Caught an XMLSecurity exception while creating raw signature: ") + e.getMsg());
503 bool Signature::verifyRawSignature(
504 XSECCryptoKey* key, const XMLCh* sigAlgorithm, const char* signature, const char* in, unsigned int in_len
508 XSECAlgorithmHandler* handler = XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(sigAlgorithm);
510 auto_ptr_char alg(sigAlgorithm);
511 throw SignatureException("Unsupported signature algorithm ($1).", params(1,alg.get()));
514 // Move input into a safeBuffer to source the transform chain.
516 sb.sbStrncpyIn(in,in_len);
517 TXFMSB* sbt = new TXFMSB(NULL);
518 sbt->setInput(sb, in_len);
522 return handler->verifyBase64Signature(&tx, sigAlgorithm, signature, 0, key);
524 catch(XSECException& e) {
525 auto_ptr_char temp(e.getMsg());
526 throw SignatureException(string("Caught an XMLSecurity exception while verifying raw signature: ") + temp.get());
528 catch(XSECCryptoException& e) {
529 throw SignatureException(string("Caught an XMLSecurity exception while verifying raw signature: ") + e.getMsg());