Version 4.0.2.1, tag libreoffice-4.0.2.1
[LibreOffice.git] / xmlsecurity / source / helper / documentsignaturehelper.cxx
blob2d7a921cc8935fa4a07ead02002461915add6742
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
21 #include <xmlsecurity/documentsignaturehelper.hxx>
23 #include <com/sun/star/container/XNameAccess.hpp>
24 #include <com/sun/star/lang/XComponent.hpp>
25 #include <com/sun/star/lang/DisposedException.hpp>
26 #include <com/sun/star/embed/XStorage.hpp>
27 #include <com/sun/star/embed/ElementModes.hpp>
28 #include "com/sun/star/beans/XPropertySet.hpp"
30 #include "comphelper/documentconstants.hxx"
31 #include <tools/debug.hxx>
32 #include "rtl/uri.hxx"
34 using namespace ::com::sun::star::uno;
35 using rtl::OUString;
37 namespace
39 ::rtl::OUString getElement(::rtl::OUString const & version, ::sal_Int32 * index)
41 while (*index < version.getLength() && version[*index] == '0') {
42 ++*index;
44 return version.getToken(0, '.', *index);
49 // Return 1 if version1 is greater then version 2, 0 if they are equal
50 //and -1 if version1 is less version 2
51 int compareVersions(
52 ::rtl::OUString const & version1, ::rtl::OUString const & version2)
54 for (::sal_Int32 i1 = 0, i2 = 0; i1 >= 0 || i2 >= 0;) {
55 ::rtl::OUString e1(getElement(version1, &i1));
56 ::rtl::OUString e2(getElement(version2, &i2));
57 if (e1.getLength() < e2.getLength()) {
58 return -1;
59 } else if (e1.getLength() > e2.getLength()) {
60 return 1;
61 } else if (e1 < e2) {
62 return -1;
63 } else if (e1 > e2) {
64 return 1;
67 return 0;
70 //If the OOo 3.0 mode is used then we exclude
71 //'mimetype' and all content of 'META-INF'.
72 //If the argument 'bSigning' is true then the element list is created for a signing
73 //operation in which case we use the latest signing algorithm. That is all elements
74 //we find in the zip storage are added to the list. We do not support the old signatures
75 //which did not contain all files.
76 //If 'bSigning' is false, then we validate. If the user enabled validating according to OOo 3.0
77 //then mimetype and all content of META-INF must be excluded.
78 void ImplFillElementList(
79 std::vector< rtl::OUString >& rList, const Reference < css::embed::XStorage >& rxStore,
80 const ::rtl::OUString rRootStorageName, const bool bRecursive,
81 const DocumentSignatureAlgorithm mode)
83 ::rtl::OUString aMetaInfName( "META-INF" );
84 ::rtl::OUString sMimeTypeName ("mimetype");
85 ::rtl::OUString aSep( "/" );
87 Reference < css::container::XNameAccess > xElements( rxStore, UNO_QUERY );
88 Sequence< ::rtl::OUString > aElements = xElements->getElementNames();
89 sal_Int32 nElements = aElements.getLength();
90 const ::rtl::OUString* pNames = aElements.getConstArray();
92 for ( sal_Int32 n = 0; n < nElements; n++ )
94 if (mode != OOo3_2Document
95 && (pNames[n] == aMetaInfName
96 || pNames[n] == sMimeTypeName))
98 continue;
100 else
102 ::rtl::OUString sEncName = ::rtl::Uri::encode(
103 pNames[n], rtl_UriCharClassRelSegment,
104 rtl_UriEncodeStrict, RTL_TEXTENCODING_UTF8);
105 if (sEncName.isEmpty() && !pNames[n].isEmpty())
106 throw css::uno::Exception(::rtl::OUString(
107 "Failed to encode element name of XStorage"), 0);
109 if ( rxStore->isStreamElement( pNames[n] ) )
111 //Exclude documentsignatures.xml!
112 if (pNames[n].equals(
113 DocumentSignatureHelper::GetDocumentContentSignatureDefaultStreamName()))
114 continue;
115 ::rtl::OUString aFullName( rRootStorageName + sEncName );
116 rList.push_back(aFullName);
118 else if ( bRecursive && rxStore->isStorageElement( pNames[n] ) )
120 Reference < css::embed::XStorage > xSubStore = rxStore->openStorageElement( pNames[n], css::embed::ElementModes::READ );
121 rtl::OUString aFullRootName( rRootStorageName + sEncName + aSep );
122 ImplFillElementList(rList, xSubStore, aFullRootName, bRecursive, mode);
129 bool DocumentSignatureHelper::isODFPre_1_2(const ::rtl::OUString & sVersion)
131 //The property version exists only if the document is at least version 1.2
132 //That is, if the document has version 1.1 and sVersion is empty.
133 //The constant is defined in comphelper/documentconstants.hxx
134 if (compareVersions(sVersion, ODFVER_012_TEXT) == -1)
135 return true;
136 return false;
139 bool DocumentSignatureHelper::isOOo3_2_Signature(const SignatureInformation & sigInfo)
141 ::rtl::OUString sManifestURI("META-INF/manifest.xml");
142 bool bOOo3_2 = false;
143 typedef ::std::vector< SignatureReferenceInformation >::const_iterator CIT;
144 for (CIT i = sigInfo.vSignatureReferenceInfors.begin();
145 i < sigInfo.vSignatureReferenceInfors.end(); ++i)
147 if (i->ouURI.equals(sManifestURI))
149 bOOo3_2 = true;
150 break;
153 return bOOo3_2;
156 DocumentSignatureAlgorithm
157 DocumentSignatureHelper::getDocumentAlgorithm(
158 const ::rtl::OUString & sODFVersion, const SignatureInformation & sigInfo)
160 OSL_ASSERT(!sODFVersion.isEmpty());
161 DocumentSignatureAlgorithm mode = OOo3_2Document;
162 if (!isOOo3_2_Signature(sigInfo))
164 if (isODFPre_1_2(sODFVersion))
165 mode = OOo2Document;
166 else
167 mode = OOo3_0Document;
169 return mode;
172 //The function creates a list of files which are to be signed or for which
173 //the signature is to be validated. The strings are UTF8 encoded URIs which
174 //contain '/' as path separators.
176 //The algorithm how document signatures are created and validated has
177 //changed over time. The change affects only which files within the document
178 //are changed. Document signatures created by OOo 2.x only used particular files. Since
179 //OOo 3.0 everything except "mimetype" and "META-INF" are signed. As of OOo 3.2 everything
180 //except META-INF/documentsignatures.xml is signed.
181 //Signatures are validated according to the algorithm which was then used for validation.
182 //That is, when validating a signature which was created by OOo 3.0, then mimetype and
183 //META-INF are not used.
185 //When a signature is created then we always use the latest algorithm. That is, we use
186 //that of OOo 3.2
187 std::vector< rtl::OUString >
188 DocumentSignatureHelper::CreateElementList(
189 const Reference < css::embed::XStorage >& rxStore,
190 const ::rtl::OUString /*rRootStorageName*/, DocumentSignatureMode eMode,
191 const DocumentSignatureAlgorithm mode)
193 std::vector< rtl::OUString > aElements;
194 ::rtl::OUString aSep( "/" );
196 switch ( eMode )
198 case SignatureModeDocumentContent:
200 if (mode == OOo2Document) //that is, ODF 1.0, 1.1
202 // 1) Main content
203 ImplFillElementList(aElements, rxStore, ::rtl::OUString(), false, mode);
205 // 2) Pictures...
206 rtl::OUString aSubStorageName( "Pictures" );
209 Reference < css::embed::XStorage > xSubStore = rxStore->openStorageElement( aSubStorageName, css::embed::ElementModes::READ );
210 ImplFillElementList(aElements, xSubStore, aSubStorageName+aSep, true, mode);
212 catch(css::io::IOException& )
214 ; // Doesn't have to exist...
216 // 3) OLE....
217 aSubStorageName = rtl::OUString("ObjectReplacements");
220 Reference < css::embed::XStorage > xSubStore = rxStore->openStorageElement( aSubStorageName, css::embed::ElementModes::READ );
221 ImplFillElementList(aElements, xSubStore, aSubStorageName+aSep, true, mode);
222 xSubStore.clear();
224 // Object folders...
225 rtl::OUString aMatchStr( "Object " );
226 Reference < css::container::XNameAccess > xElements( rxStore, UNO_QUERY );
227 Sequence< ::rtl::OUString > aElementNames = xElements->getElementNames();
228 sal_Int32 nElements = aElementNames.getLength();
229 const ::rtl::OUString* pNames = aElementNames.getConstArray();
230 for ( sal_Int32 n = 0; n < nElements; n++ )
232 if ( ( pNames[n].match( aMatchStr ) ) && rxStore->isStorageElement( pNames[n] ) )
234 Reference < css::embed::XStorage > xTmpSubStore = rxStore->openStorageElement( pNames[n], css::embed::ElementModes::READ );
235 ImplFillElementList(aElements, xTmpSubStore, pNames[n]+aSep, true, mode);
239 catch( com::sun::star::io::IOException& )
241 ; // Doesn't have to exist...
244 else
246 // Everything except META-INF
247 ImplFillElementList(aElements, rxStore, ::rtl::OUString(), true, mode);
250 break;
251 case SignatureModeMacros:
253 // 1) Macros
254 rtl::OUString aSubStorageName( "Basic" );
257 Reference < css::embed::XStorage > xSubStore = rxStore->openStorageElement( aSubStorageName, css::embed::ElementModes::READ );
258 ImplFillElementList(aElements, xSubStore, aSubStorageName+aSep, true, mode);
260 catch( com::sun::star::io::IOException& )
262 ; // Doesn't have to exist...
265 // 2) Dialogs
266 aSubStorageName = rtl::OUString("Dialogs") ;
269 Reference < css::embed::XStorage > xSubStore = rxStore->openStorageElement( aSubStorageName, css::embed::ElementModes::READ );
270 ImplFillElementList(aElements, xSubStore, aSubStorageName+aSep, true, mode);
272 catch( com::sun::star::io::IOException& )
274 ; // Doesn't have to exist...
276 // 3) Scripts
277 aSubStorageName = rtl::OUString("Scripts") ;
280 Reference < css::embed::XStorage > xSubStore = rxStore->openStorageElement( aSubStorageName, css::embed::ElementModes::READ );
281 ImplFillElementList(aElements, xSubStore, aSubStorageName+aSep, true, mode);
283 catch( css::io::IOException& )
285 ; // Doesn't have to exist...
288 break;
289 case SignatureModePackage:
291 // Everything except META-INF
292 ImplFillElementList(aElements, rxStore, ::rtl::OUString(), true, mode);
294 break;
297 return aElements;
300 SignatureStreamHelper DocumentSignatureHelper::OpenSignatureStream(
301 const Reference < css::embed::XStorage >& rxStore, sal_Int32 nOpenMode, DocumentSignatureMode eDocSigMode )
303 sal_Int32 nSubStorageOpenMode = css::embed::ElementModes::READ;
304 if ( nOpenMode & css::embed::ElementModes::WRITE )
305 nSubStorageOpenMode = css::embed::ElementModes::WRITE;
307 SignatureStreamHelper aHelper;
311 ::rtl::OUString aSIGStoreName( "META-INF" );
312 aHelper.xSignatureStorage = rxStore->openStorageElement( aSIGStoreName, nSubStorageOpenMode );
313 if ( aHelper.xSignatureStorage.is() )
315 ::rtl::OUString aSIGStreamName;
316 if ( eDocSigMode == SignatureModeDocumentContent )
317 aSIGStreamName = DocumentSignatureHelper::GetDocumentContentSignatureDefaultStreamName();
318 else if ( eDocSigMode == SignatureModeMacros )
319 aSIGStreamName = DocumentSignatureHelper::GetScriptingContentSignatureDefaultStreamName();
320 else
321 aSIGStreamName = DocumentSignatureHelper::GetPackageSignatureDefaultStreamName();
323 aHelper.xSignatureStream = aHelper.xSignatureStorage->openStreamElement( aSIGStreamName, nOpenMode );
326 catch(css::io::IOException& )
328 // Doesn't have to exist...
329 DBG_ASSERT( nOpenMode == css::embed::ElementModes::READ, "Error creating signature stream..." );
332 return aHelper;
335 //sElementList contains all files which are expected to be signed. Only those files must me signed,
336 //no more, no less.
337 //The DocumentSignatureAlgorithm indicates if the document was created with OOo 2.x. Then
338 //the uri s in the Reference elements in the signature, were not properly encoded.
339 // For example: <Reference URI="ObjectReplacements/Object 1">
340 bool DocumentSignatureHelper::checkIfAllFilesAreSigned(
341 const ::std::vector< ::rtl::OUString > & sElementList,
342 const SignatureInformation & sigInfo,
343 const DocumentSignatureAlgorithm alg)
345 // Can only be valid if ALL streams are signed, which means real stream count == signed stream count
346 unsigned int nRealCount = 0;
347 for ( int i = sigInfo.vSignatureReferenceInfors.size(); i; )
349 const SignatureReferenceInformation& rInf = sigInfo.vSignatureReferenceInfors[--i];
350 // There is also an extra entry of type TYPE_SAMEDOCUMENT_REFERENCE because of signature date.
351 if ( ( rInf.nType == TYPE_BINARYSTREAM_REFERENCE ) || ( rInf.nType == TYPE_XMLSTREAM_REFERENCE ) )
353 ::rtl::OUString sReferenceURI = rInf.ouURI;
354 if (alg == OOo2Document)
356 //Comparing URIs is a difficult. Therefore we kind of normalize
357 //it before comparing. We assume that our URI do not have a leading "./"
358 //and fragments at the end (...#...)
359 sReferenceURI = ::rtl::Uri::encode(
360 sReferenceURI, rtl_UriCharClassPchar,
361 rtl_UriEncodeCheckEscapes, RTL_TEXTENCODING_UTF8);
364 //find the file in the element list
365 typedef ::std::vector< ::rtl::OUString >::const_iterator CIT;
366 for (CIT aIter = sElementList.begin(); aIter != sElementList.end(); ++aIter)
368 ::rtl::OUString sElementListURI = *aIter;
369 if (alg == OOo2Document)
371 sElementListURI =
372 ::rtl::Uri::encode(
373 sElementListURI, rtl_UriCharClassPchar,
374 rtl_UriEncodeCheckEscapes, RTL_TEXTENCODING_UTF8);
376 if (sElementListURI.equals(sReferenceURI))
378 nRealCount++;
379 break;
384 return sElementList.size() == nRealCount;
387 /*Compares the Uri which are obtained from CreateElementList with
388 the path obtained from the manifest.xml.
389 Returns true if both strings are equal.
391 bool DocumentSignatureHelper::equalsReferenceUriManifestPath(
392 const OUString & rUri, const OUString & rPath)
394 bool retVal = false;
395 //split up the uri and path into segments. Both are separated by '/'
396 std::vector<OUString> vUriSegments;
397 sal_Int32 nIndex = 0;
400 OUString aToken = rUri.getToken( 0, '/', nIndex );
401 vUriSegments.push_back(aToken);
403 while (nIndex >= 0);
405 std::vector<OUString> vPathSegments;
406 nIndex = 0;
409 OUString aToken = rPath.getToken( 0, '/', nIndex );
410 vPathSegments.push_back(aToken);
412 while (nIndex >= 0);
414 //Now compare each segment of the uri with its counterpart from the path
415 if (vUriSegments.size() == vPathSegments.size())
417 retVal = true;
418 typedef std::vector<OUString>::const_iterator CIT;
419 for (CIT i = vUriSegments.begin(), j = vPathSegments.begin();
420 i != vUriSegments.end(); ++i, ++j)
422 //Decode the uri segment, so that %20 becomes ' ', etc.
423 OUString sDecUri = ::rtl::Uri::decode(
424 *i, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8);
425 if (!sDecUri.equals(*j))
427 retVal = false;
428 break;
433 return retVal;
436 ::rtl::OUString DocumentSignatureHelper::GetDocumentContentSignatureDefaultStreamName()
438 return ::rtl::OUString( "documentsignatures.xml" );
441 ::rtl::OUString DocumentSignatureHelper::GetScriptingContentSignatureDefaultStreamName()
443 return ::rtl::OUString( "macrosignatures.xml" );
446 ::rtl::OUString DocumentSignatureHelper::GetPackageSignatureDefaultStreamName()
448 return ::rtl::OUString( "packagesignatures.xml" );
451 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */