xref: /core/comphelper/source/misc/docpasswordhelper.cxx (revision 234b42d44933f371f386340d6918111f15264c3a)
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * This file is part of the LibreOffice project.
4  *
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/.
8  *
9  * This file incorporates work covered by the following license notice:
10  *
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 .
18  */
19 
20 #include <config_gpgme.h>
21 
22 #include <algorithm>
23 #include <string_view>
24 
25 #include <comphelper/docpasswordhelper.hxx>
26 #include <comphelper/propertyvalue.hxx>
27 #include <comphelper/storagehelper.hxx>
28 #include <comphelper/hash.hxx>
29 #include <comphelper/base64.hxx>
30 #include <comphelper/sequence.hxx>
31 #include <com/sun/star/beans/NamedValue.hpp>
32 #include <com/sun/star/beans/PropertyValue.hpp>
33 #include <com/sun/star/task/XInteractionHandler.hpp>
34 
35 #include <osl/diagnose.h>
36 #include <sal/log.hxx>
37 #include <rtl/digest.h>
38 #include <rtl/random.h>
39 #include <string.h>
40 
41 #if HAVE_FEATURE_GPGME
42 # include <context.h>
43 # include <data.h>
44 # include <decryptionresult.h>
45 #endif
46 
47 using ::com::sun::star::uno::Sequence;
48 using ::com::sun::star::uno::Exception;
49 using ::com::sun::star::uno::Reference;
50 using ::com::sun::star::task::PasswordRequestMode;
51 using ::com::sun::star::task::PasswordRequestMode_PASSWORD_ENTER;
52 using ::com::sun::star::task::PasswordRequestMode_PASSWORD_REENTER;
53 using ::com::sun::star::task::XInteractionHandler;
54 
55 using namespace ::com::sun::star;
56 
57 namespace comphelper {
58 
59 
GeneratePBKDF2Hash(std::u16string_view aPassword,const uno::Sequence<sal_Int8> & aSalt,sal_Int32 nCount,sal_Int32 nHashLength)60 static uno::Sequence< sal_Int8 > GeneratePBKDF2Hash( std::u16string_view aPassword, const uno::Sequence< sal_Int8 >& aSalt, sal_Int32 nCount, sal_Int32 nHashLength )
61 {
62     uno::Sequence< sal_Int8 > aResult;
63 
64     if ( !aPassword.empty() && aSalt.hasElements() && nCount && nHashLength )
65     {
66         OString aBytePass = OUStringToOString( aPassword, RTL_TEXTENCODING_UTF8 );
67         // FIXME this is subject to the SHA1-bug tdf#114939 - see also
68         // RequestPassword() in filedlghelper.cxx
69         aResult.realloc( 16 );
70         rtl_digest_PBKDF2( reinterpret_cast < sal_uInt8 * > ( aResult.getArray() ),
71                            aResult.getLength(),
72                            reinterpret_cast < const sal_uInt8 * > ( aBytePass.getStr() ),
73                            aBytePass.getLength(),
74                            reinterpret_cast < const sal_uInt8 * > ( aSalt.getConstArray() ),
75                            aSalt.getLength(),
76                            nCount );
77     }
78 
79     return aResult;
80 }
81 
82 
~IDocPasswordVerifier()83 IDocPasswordVerifier::~IDocPasswordVerifier()
84 {
85 }
86 
87 
GenerateNewModifyPasswordInfo(std::u16string_view aPassword)88 uno::Sequence< beans::PropertyValue > DocPasswordHelper::GenerateNewModifyPasswordInfo( std::u16string_view aPassword )
89 {
90     uno::Sequence< beans::PropertyValue > aResult;
91 
92     uno::Sequence< sal_Int8 > aSalt = GenerateRandomByteSequence( 16 );
93     sal_Int32 const nPBKDF2IterationCount = 100000;
94 
95     uno::Sequence< sal_Int8 > aNewHash = GeneratePBKDF2Hash(aPassword, aSalt, nPBKDF2IterationCount, 16);
96     if ( aNewHash.hasElements() )
97     {
98         aResult = { comphelper::makePropertyValue(u"algorithm-name"_ustr, u"PBKDF2"_ustr),
99                     comphelper::makePropertyValue(u"salt"_ustr, aSalt),
100                     comphelper::makePropertyValue(u"iteration-count"_ustr, nPBKDF2IterationCount),
101                     comphelper::makePropertyValue(u"hash"_ustr, aNewHash) };
102     }
103 
104     return aResult;
105 }
106 
107 
108 uno::Sequence<beans::PropertyValue>
GenerateNewModifyPasswordInfoOOXML(std::u16string_view aPassword)109 DocPasswordHelper::GenerateNewModifyPasswordInfoOOXML(std::u16string_view aPassword)
110 {
111     uno::Sequence<beans::PropertyValue> aResult;
112 
113     if (!aPassword.empty())
114     {
115         uno::Sequence<sal_Int8> aSalt = GenerateRandomByteSequence(16);
116         OUStringBuffer aBuffer(22);
117         comphelper::Base64::encode(aBuffer, aSalt);
118         OUString sSalt = aBuffer.makeStringAndClear();
119 
120         sal_Int32 const nIterationCount = 100000;
121         OUString sAlgorithm(u"SHA-512"_ustr);
122 
123         const OUString sHash(GetOoxHashAsBase64(aPassword, sSalt, nIterationCount,
124                                                 comphelper::Hash::IterCount::APPEND, sAlgorithm));
125 
126         if (!sHash.isEmpty())
127         {
128             aResult = { comphelper::makePropertyValue(u"algorithm-name"_ustr, sAlgorithm),
129                         comphelper::makePropertyValue(u"salt"_ustr, sSalt),
130                         comphelper::makePropertyValue(u"iteration-count"_ustr, nIterationCount),
131                         comphelper::makePropertyValue(u"hash"_ustr, sHash) };
132         }
133     }
134 
135     return aResult;
136 }
137 
138 
ConvertPasswordInfo(const uno::Sequence<beans::PropertyValue> & aInfo)139 uno::Sequence< beans::PropertyValue > DocPasswordHelper::ConvertPasswordInfo( const uno::Sequence< beans::PropertyValue >& aInfo )
140 {
141     uno::Sequence< beans::PropertyValue > aResult;
142     OUString sAlgorithm, sHash, sSalt, sCount;
143     sal_Int32 nAlgorithm = 0;
144 
145     for ( const auto & prop : aInfo )
146     {
147         if ( prop.Name == "cryptAlgorithmSid" )
148         {
149             prop.Value >>= sAlgorithm;
150             nAlgorithm = sAlgorithm.toInt32();
151         }
152         else if ( prop.Name == "salt" )
153             prop.Value >>= sSalt;
154         else if ( prop.Name == "cryptSpinCount" )
155             prop.Value >>= sCount;
156         else if ( prop.Name == "hash" )
157             prop.Value >>= sHash;
158     }
159 
160     if (nAlgorithm == 1)
161         sAlgorithm = "MD2";
162     else if (nAlgorithm == 2)
163         sAlgorithm = "MD4";
164     else if (nAlgorithm == 3)
165         sAlgorithm = "MD5";
166     else if (nAlgorithm == 4)
167         sAlgorithm = "SHA-1";
168     else if (nAlgorithm == 5)
169         sAlgorithm = "MAC";
170     else if (nAlgorithm == 6)
171         sAlgorithm = "RIPEMD";
172     else if (nAlgorithm == 7)
173         sAlgorithm = "RIPEMD-160";
174     else if (nAlgorithm == 9)
175         sAlgorithm = "HMAC";
176     else if (nAlgorithm == 12)
177         sAlgorithm = "SHA-256";
178     else if (nAlgorithm == 13)
179         sAlgorithm = "SHA-384";
180     else if (nAlgorithm == 14)
181         sAlgorithm = "SHA-512";
182 
183     if ( !sCount.isEmpty() )
184     {
185         sal_Int32 nCount = sCount.toInt32();
186         aResult = { comphelper::makePropertyValue(u"algorithm-name"_ustr, sAlgorithm),
187                     comphelper::makePropertyValue(u"salt"_ustr, sSalt),
188                     comphelper::makePropertyValue(u"iteration-count"_ustr, nCount),
189                     comphelper::makePropertyValue(u"hash"_ustr, sHash) };
190     }
191 
192     return aResult;
193 }
194 
195 
IsModifyPasswordCorrect(std::u16string_view aPassword,const uno::Sequence<beans::PropertyValue> & aInfo)196 bool DocPasswordHelper::IsModifyPasswordCorrect( std::u16string_view aPassword, const uno::Sequence< beans::PropertyValue >& aInfo )
197 {
198     bool bResult = false;
199     if ( !aPassword.empty() && aInfo.hasElements() )
200     {
201         OUString sAlgorithm;
202         uno::Any aSalt, aHash;
203         sal_Int32 nCount = 0;
204 
205         for ( const auto & prop : aInfo )
206         {
207             if ( prop.Name == "algorithm-name" )
208                 prop.Value >>= sAlgorithm;
209             else if ( prop.Name == "salt" )
210                 aSalt = prop.Value;
211             else if ( prop.Name == "iteration-count" )
212                 prop.Value >>= nCount;
213             else if ( prop.Name == "hash" )
214                 aHash = prop.Value;
215         }
216 
217         if ( sAlgorithm == "PBKDF2" )
218         {
219             uno::Sequence<sal_Int8> aIntSalt, aIntHash;
220             aSalt >>= aIntSalt;
221             aHash >>= aIntHash;
222             if (aIntSalt.hasElements() && nCount > 0 && aIntHash.hasElements())
223             {
224                 uno::Sequence<sal_Int8> aNewHash
225                     = GeneratePBKDF2Hash(aPassword, aIntSalt, nCount, aIntHash.getLength());
226                 for (sal_Int32 nInd = 0; nInd < aNewHash.getLength() && nInd < aIntHash.getLength()
227                                          && aNewHash[nInd] == aIntHash[nInd];
228                      nInd++)
229                 {
230                     if (nInd == aNewHash.getLength() - 1 && nInd == aIntHash.getLength() - 1)
231                         bResult = true;
232                 }
233             }
234         }
235         else if (nCount > 0)
236         {
237             OUString sSalt, sHash;
238             aSalt >>= sSalt;
239             aHash >>= sHash;
240             if (!sSalt.isEmpty() && !sHash.isEmpty())
241             {
242                 const OUString aNewHash(GetOoxHashAsBase64(aPassword, sSalt, nCount,
243                                                            comphelper::Hash::IterCount::APPEND,
244                                                            sAlgorithm));
245                 if (!aNewHash.isEmpty())
246                     bResult = aNewHash == sHash;
247             }
248         }
249     }
250 
251     return bResult;
252 }
253 
254 
GetWordHashAsUINT32(std::u16string_view aUString)255 sal_uInt32 DocPasswordHelper::GetWordHashAsUINT32(
256                 std::u16string_view aUString )
257 {
258     static const sal_uInt16 pInitialCode[] = {
259         0xE1F0, // 1
260         0x1D0F, // 2
261         0xCC9C, // 3
262         0x84C0, // 4
263         0x110C, // 5
264         0x0E10, // 6
265         0xF1CE, // 7
266         0x313E, // 8
267         0x1872, // 9
268         0xE139, // 10
269         0xD40F, // 11
270         0x84F9, // 12
271         0x280C, // 13
272         0xA96A, // 14
273         0x4EC3  // 15
274     };
275 
276     static const sal_uInt16 pEncryptionMatrix[15][7] = {
277         { 0xAEFC, 0x4DD9, 0x9BB2, 0x2745, 0x4E8A, 0x9D14, 0x2A09}, // last-14
278         { 0x7B61, 0xF6C2, 0xFDA5, 0xEB6B, 0xC6F7, 0x9DCF, 0x2BBF}, // last-13
279         { 0x4563, 0x8AC6, 0x05AD, 0x0B5A, 0x16B4, 0x2D68, 0x5AD0}, // last-12
280         { 0x0375, 0x06EA, 0x0DD4, 0x1BA8, 0x3750, 0x6EA0, 0xDD40}, // last-11
281         { 0xD849, 0xA0B3, 0x5147, 0xA28E, 0x553D, 0xAA7A, 0x44D5}, // last-10
282         { 0x6F45, 0xDE8A, 0xAD35, 0x4A4B, 0x9496, 0x390D, 0x721A}, // last-9
283         { 0xEB23, 0xC667, 0x9CEF, 0x29FF, 0x53FE, 0xA7FC, 0x5FD9}, // last-8
284         { 0x47D3, 0x8FA6, 0x8FA6, 0x1EDA, 0x3DB4, 0x7B68, 0xF6D0}, // last-7
285         { 0xB861, 0x60E3, 0xC1C6, 0x93AD, 0x377B, 0x6EF6, 0xDDEC}, // last-6
286         { 0x45A0, 0x8B40, 0x06A1, 0x0D42, 0x1A84, 0x3508, 0x6A10}, // last-5
287         { 0xAA51, 0x4483, 0x8906, 0x022D, 0x045A, 0x08B4, 0x1168}, // last-4
288         { 0x76B4, 0xED68, 0xCAF1, 0x85C3, 0x1BA7, 0x374E, 0x6E9C}, // last-3
289         { 0x3730, 0x6E60, 0xDCC0, 0xA9A1, 0x4363, 0x86C6, 0x1DAD}, // last-2
290         { 0x3331, 0x6662, 0xCCC4, 0x89A9, 0x0373, 0x06E6, 0x0DCC}, // last-1
291         { 0x1021, 0x2042, 0x4084, 0x8108, 0x1231, 0x2462, 0x48C4}  // last
292     };
293 
294     sal_uInt32 nResult = 0;
295     size_t nLen = aUString.size();
296 
297     if ( nLen )
298     {
299         if ( nLen > 15 )
300             nLen = 15;
301 
302         sal_uInt16 nHighResult = pInitialCode[nLen - 1];
303         sal_uInt16 nLowResult = 0;
304 
305         for ( size_t nInd = 0; nInd < nLen; nInd++ )
306         {
307             // NO Encoding during conversion!
308             // The specification says that the low byte should be used in case it is not NULL
309             char nHighChar = static_cast<char>( aUString[nInd] >> 8 );
310             char nLowChar = static_cast<char>( aUString[nInd] & 0xFF );
311             char nChar = nLowChar ? nLowChar : nHighChar;
312 
313             for ( int nMatrixInd = 0; nMatrixInd < 7; ++nMatrixInd )
314             {
315                 if ( ( nChar & ( 1 << nMatrixInd ) ) != 0 )
316                     nHighResult = nHighResult ^ pEncryptionMatrix[15 - nLen + nInd][nMatrixInd];
317             }
318 
319             nLowResult = ( ( ( nLowResult >> 14 ) & 0x0001 ) | ( ( nLowResult << 1 ) & 0x7FFF ) ) ^ nChar;
320         }
321 
322         nLowResult = static_cast<sal_uInt16>( ( ( ( nLowResult >> 14 ) & 0x001 ) | ( ( nLowResult << 1 ) & 0x7FF ) ) ^ nLen ^ 0xCE4B );
323 
324         nResult = ( nHighResult << 16 ) | nLowResult;
325     }
326 
327     return nResult;
328 }
329 
330 
GetXLHashAsUINT16(std::u16string_view aUString,rtl_TextEncoding nEnc)331 sal_uInt16 DocPasswordHelper::GetXLHashAsUINT16(
332                 std::u16string_view aUString,
333                 rtl_TextEncoding nEnc )
334 {
335     sal_uInt16 nResult = 0;
336 
337     OString aString = OUStringToOString( aUString, nEnc );
338 
339     if ( !aString.isEmpty() && aString.getLength() <= SAL_MAX_UINT16 )
340     {
341         for ( sal_Int32 nInd = aString.getLength() - 1; nInd >= 0; nInd-- )
342         {
343             nResult = ( ( nResult >> 14 ) & 0x01 ) | ( ( nResult << 1 ) & 0x7FFF );
344             nResult ^= aString[nInd];
345         }
346 
347         nResult = ( ( nResult >> 14 ) & 0x01 ) | ( ( nResult << 1 ) & 0x7FFF );
348         nResult ^= ( 0x8000 | ( 'N' << 8 ) | 'K' );
349         nResult ^= aString.getLength();
350     }
351 
352     return nResult;
353 }
354 
355 
GetXLHashAsSequence(std::u16string_view aUString)356 Sequence< sal_Int8 > DocPasswordHelper::GetXLHashAsSequence(
357                 std::u16string_view aUString )
358 {
359     sal_uInt16 nHash = GetXLHashAsUINT16( aUString );
360     return {sal_Int8(nHash >> 8), sal_Int8(nHash & 0xFF)};
361 }
362 
363 
GetOoxHashAsVector(std::u16string_view rPassword,const std::vector<unsigned char> & rSaltValue,sal_uInt32 nSpinCount,comphelper::Hash::IterCount eIterCount,std::u16string_view rAlgorithmName)364 std::vector<unsigned char> DocPasswordHelper::GetOoxHashAsVector(
365         std::u16string_view rPassword,
366         const std::vector<unsigned char>& rSaltValue,
367         sal_uInt32 nSpinCount,
368         comphelper::Hash::IterCount eIterCount,
369          std::u16string_view rAlgorithmName)
370 {
371     comphelper::HashType eType;
372     if (rAlgorithmName == u"SHA-512" || rAlgorithmName == u"SHA512")
373         eType = comphelper::HashType::SHA512;
374     else if (rAlgorithmName == u"SHA-256" || rAlgorithmName == u"SHA256")
375         eType = comphelper::HashType::SHA256;
376     else if (rAlgorithmName == u"SHA-384" || rAlgorithmName == u"SHA384")
377         eType = comphelper::HashType::SHA384;
378     else if (rAlgorithmName == u"SHA-1" || rAlgorithmName == u"SHA1") // "SHA1" might be in the wild
379         eType = comphelper::HashType::SHA1;
380     else if (rAlgorithmName == u"MD5")
381         eType = comphelper::HashType::MD5;
382     else
383         return std::vector<unsigned char>();
384 
385     return comphelper::Hash::calculateHash( rPassword, rSaltValue, nSpinCount, eIterCount, eType);
386 }
387 
388 
GetOoxHashAsSequence(std::u16string_view rPassword,std::u16string_view rSaltValue,sal_uInt32 nSpinCount,comphelper::Hash::IterCount eIterCount,std::u16string_view rAlgorithmName)389 css::uno::Sequence<sal_Int8> DocPasswordHelper::GetOoxHashAsSequence(
390         std::u16string_view rPassword,
391         std::u16string_view rSaltValue,
392         sal_uInt32 nSpinCount,
393         comphelper::Hash::IterCount eIterCount,
394         std::u16string_view rAlgorithmName)
395 {
396     std::vector<unsigned char> aSaltVec;
397     if (!rSaltValue.empty())
398     {
399         css::uno::Sequence<sal_Int8> aSaltSeq;
400         comphelper::Base64::decode( aSaltSeq, rSaltValue);
401         aSaltVec = comphelper::sequenceToContainer<std::vector<unsigned char>>( aSaltSeq);
402     }
403 
404     std::vector<unsigned char> hash( GetOoxHashAsVector( rPassword, aSaltVec, nSpinCount, eIterCount, rAlgorithmName));
405 
406     return comphelper::containerToSequence<sal_Int8>( hash);
407 }
408 
GetOoxHashAsBase64(std::u16string_view rPassword,std::u16string_view rSaltValue,sal_uInt32 nSpinCount,comphelper::Hash::IterCount eIterCount,std::u16string_view rAlgorithmName)409 OUString DocPasswordHelper::GetOoxHashAsBase64(
410         std::u16string_view rPassword,
411         std::u16string_view rSaltValue,
412         sal_uInt32 nSpinCount,
413         comphelper::Hash::IterCount eIterCount,
414         std::u16string_view rAlgorithmName)
415 {
416     css::uno::Sequence<sal_Int8> aSeq( GetOoxHashAsSequence( rPassword, rSaltValue, nSpinCount,
417                 eIterCount, rAlgorithmName));
418 
419     OUStringBuffer aBuf((aSeq.getLength()+2)/3*4);
420     comphelper::Base64::encode( aBuf, aSeq);
421     return aBuf.makeStringAndClear();
422 }
423 
424 
GenerateRandomByteSequence(sal_Int32 nLength)425 /*static*/ uno::Sequence< sal_Int8 > DocPasswordHelper::GenerateRandomByteSequence( sal_Int32 nLength )
426 {
427     uno::Sequence< sal_Int8 > aResult( nLength );
428 
429     if (rtl_random_getBytes(nullptr, aResult.getArray(), nLength) != rtl_Random_E_None)
430     {
431         throw uno::RuntimeException(u"rtl_random_getBytes failed"_ustr);
432     }
433 
434     return aResult;
435 }
436 
437 
GenerateStd97Key(std::u16string_view aPassword,const uno::Sequence<sal_Int8> & aDocId)438 /*static*/ uno::Sequence< sal_Int8 > DocPasswordHelper::GenerateStd97Key( std::u16string_view aPassword, const uno::Sequence< sal_Int8 >& aDocId )
439 {
440     uno::Sequence< sal_Int8 > aResultKey;
441     if ( !aPassword.empty() && aDocId.getLength() == 16 )
442     {
443         sal_uInt16 pPassData[16] = {};
444 
445         sal_Int32 nPassLen = std::min< sal_Int32 >( aPassword.size(), 15 );
446         std::copy( aPassword.data(), aPassword.data() + nPassLen, pPassData );
447 
448         aResultKey = GenerateStd97Key( pPassData, aDocId );
449     }
450 
451     return aResultKey;
452 }
453 
454 
GenerateStd97Key(const sal_uInt16 pPassData[16],const uno::Sequence<sal_Int8> & aDocId)455 /*static*/ uno::Sequence< sal_Int8 > DocPasswordHelper::GenerateStd97Key( const sal_uInt16 pPassData[16], const uno::Sequence< sal_Int8 >& aDocId )
456 {
457     uno::Sequence< sal_Int8 > aResultKey;
458 
459     if ( aDocId.getLength() == 16 )
460         aResultKey = GenerateStd97Key(pPassData, reinterpret_cast<const sal_uInt8*>(aDocId.getConstArray()));
461 
462     return aResultKey;
463 }
464 
465 
GenerateStd97Key(const sal_uInt16 pPassData[16],const sal_uInt8 pDocId[16])466 /*static*/ uno::Sequence< sal_Int8 > DocPasswordHelper::GenerateStd97Key( const sal_uInt16 pPassData[16], const sal_uInt8 pDocId[16] )
467 {
468     uno::Sequence< sal_Int8 > aResultKey;
469     if ( pPassData[0] )
470     {
471         sal_uInt8 pKeyData[64] = {};
472 
473         sal_Int32 nInd = 0;
474 
475         // Fill PassData into KeyData.
476         for ( nInd = 0; nInd < 16 && pPassData[nInd]; nInd++)
477         {
478             pKeyData[2*nInd] = sal::static_int_cast< sal_uInt8 >( (pPassData[nInd] >> 0) & 0xff );
479             pKeyData[2*nInd + 1] = sal::static_int_cast< sal_uInt8 >( (pPassData[nInd] >> 8) & 0xff );
480         }
481 
482         pKeyData[2*nInd] = 0x80;
483         pKeyData[56] = sal::static_int_cast< sal_uInt8 >( nInd << 4 );
484 
485         // Fill raw digest of KeyData into KeyData.
486         rtlDigest hDigest = rtl_digest_create ( rtl_Digest_AlgorithmMD5 );
487         (void)rtl_digest_updateMD5 (
488             hDigest, pKeyData, sizeof(pKeyData));
489         (void)rtl_digest_rawMD5 (
490             hDigest, pKeyData, RTL_DIGEST_LENGTH_MD5);
491 
492         // Update digest with KeyData and Unique.
493         for ( nInd = 0; nInd < 16; nInd++ )
494         {
495             rtl_digest_updateMD5( hDigest, pKeyData, 5 );
496             rtl_digest_updateMD5( hDigest, pDocId, 16 );
497         }
498 
499         // Update digest with padding.
500         pKeyData[16] = 0x80;
501         memset( pKeyData + 17, 0, sizeof(pKeyData) - 17 );
502         pKeyData[56] = 0x80;
503         pKeyData[57] = 0x0a;
504 
505         rtl_digest_updateMD5( hDigest, &(pKeyData[16]), sizeof(pKeyData) - 16 );
506 
507         // Fill raw digest of above updates
508         aResultKey.realloc( RTL_DIGEST_LENGTH_MD5 );
509         rtl_digest_rawMD5 ( hDigest, reinterpret_cast<sal_uInt8*>(aResultKey.getArray()), aResultKey.getLength() );
510 
511         // Erase KeyData array and leave.
512         rtl_secureZeroMemory (pKeyData, sizeof(pKeyData));
513 
514         rtl_digest_destroy(hDigest);
515     }
516 
517     return aResultKey;
518 }
519 
520 
requestAndVerifyDocPassword(IDocPasswordVerifier & rVerifier,const css::uno::Sequence<css::beans::NamedValue> & rMediaEncData,const OUString & rMediaPassword,const Reference<XInteractionHandler> & rxInteractHandler,const OUString & rDocumentUrl,DocPasswordRequestType eRequestType,const std::vector<OUString> * pDefaultPasswords,bool * pbIsDefaultPassword)521 /*static*/ css::uno::Sequence< css::beans::NamedValue > DocPasswordHelper::requestAndVerifyDocPassword(
522         IDocPasswordVerifier& rVerifier,
523         const css::uno::Sequence< css::beans::NamedValue >& rMediaEncData,
524         const OUString& rMediaPassword,
525         const Reference< XInteractionHandler >& rxInteractHandler,
526         const OUString& rDocumentUrl,
527         DocPasswordRequestType eRequestType,
528         const std::vector< OUString >* pDefaultPasswords,
529         bool* pbIsDefaultPassword )
530 {
531     css::uno::Sequence< css::beans::NamedValue > aEncData;
532     OUString aPassword;
533     DocPasswordVerifierResult eResult = DocPasswordVerifierResult::WrongPassword;
534 
535     sal_Int32 nMediaEncDataCount = rMediaEncData.getLength();
536 
537     // tdf#93389: if the document is being restored from autorecovery, we need to add encryption
538     // data also for real document type.
539     // TODO: get real filter name here (from CheckPasswd_Impl), to only add necessary data
540     bool bForSalvage = false;
541     if (nMediaEncDataCount)
542     {
543         for (auto& val : rMediaEncData)
544         {
545             if (val.Name == "ForSalvage")
546             {
547                 --nMediaEncDataCount; // don't consider this element below
548                 val.Value >>= bForSalvage;
549                 break;
550             }
551         }
552     }
553 
554     // first, try provided default passwords
555     if( pbIsDefaultPassword )
556         *pbIsDefaultPassword = false;
557     if( pDefaultPasswords )
558     {
559         for( const auto& rPassword : *pDefaultPasswords )
560         {
561             OSL_ENSURE( !rPassword.isEmpty(), "DocPasswordHelper::requestAndVerifyDocPassword - unexpected empty default password" );
562             if( !rPassword.isEmpty() )
563             {
564                 eResult = rVerifier.verifyPassword( rPassword, aEncData );
565                 if (eResult == DocPasswordVerifierResult::OK)
566                 {
567                     aPassword = rPassword;
568                     if (pbIsDefaultPassword)
569                         *pbIsDefaultPassword = true;
570                 }
571                 if( eResult != DocPasswordVerifierResult::WrongPassword )
572                     break;
573             }
574         }
575     }
576 
577     // try media encryption data (skip, if result is OK or ABORT)
578     if( eResult == DocPasswordVerifierResult::WrongPassword )
579     {
580         if (nMediaEncDataCount)
581         {
582             eResult = rVerifier.verifyEncryptionData( rMediaEncData );
583             if( eResult == DocPasswordVerifierResult::OK )
584                 aEncData = rMediaEncData;
585         }
586     }
587 
588     // try media password (skip, if result is OK or ABORT)
589     if( eResult == DocPasswordVerifierResult::WrongPassword )
590     {
591         if( !rMediaPassword.isEmpty() )
592         {
593             eResult = rVerifier.verifyPassword( rMediaPassword, aEncData );
594             if (eResult == DocPasswordVerifierResult::OK)
595                 aPassword = rMediaPassword;
596         }
597     }
598 
599     // request a password (skip, if result is OK or ABORT)
600     if( (eResult == DocPasswordVerifierResult::WrongPassword) && rxInteractHandler.is() ) try
601     {
602         PasswordRequestMode eRequestMode = PasswordRequestMode_PASSWORD_ENTER;
603         while( eResult == DocPasswordVerifierResult::WrongPassword )
604         {
605             rtl::Reference<DocPasswordRequest> pRequest = new DocPasswordRequest( eRequestType, eRequestMode, rDocumentUrl );
606             rxInteractHandler->handle( pRequest );
607             if( pRequest->isPassword() )
608             {
609                 if( !pRequest->getPassword().isEmpty() )
610                     eResult = rVerifier.verifyPassword( pRequest->getPassword(), aEncData );
611                 if (eResult == DocPasswordVerifierResult::OK)
612                     aPassword = pRequest->getPassword();
613             }
614             else
615             {
616                 eResult = DocPasswordVerifierResult::Abort;
617             }
618             eRequestMode = PasswordRequestMode_PASSWORD_REENTER;
619         }
620     }
621     catch( Exception& )
622     {
623     }
624 
625     if (eResult == DocPasswordVerifierResult::OK && !aPassword.isEmpty())
626     {
627         if (std::none_of(std::cbegin(aEncData), std::cend(aEncData),
628                          [](const css::beans::NamedValue& val) {
629                              return val.Name == PACKAGE_ENCRYPTIONDATA_SHA256UTF8;
630                          }))
631         {
632             // tdf#118639: We need ODF encryption data for autorecovery, where password
633             // will already be unavailable, so generate and append it here
634             aEncData = comphelper::concatSequences(
635                 aEncData, OStorageHelper::CreatePackageEncryptionData(aPassword));
636         }
637 
638         if (bForSalvage)
639         {
640             // TODO: add individual methods for different target filter, and only call what's needed
641 
642             // 1. Prepare binary MS formats encryption data
643             auto aUniqueID = GenerateRandomByteSequence(16);
644             auto aEnc97Key = GenerateStd97Key(aPassword, aUniqueID);
645             // 2. Add MS binary and OOXML encryption data to result
646             aEncData = comphelper::concatSequences(
647                 aEncData, std::initializer_list<beans::NamedValue>{
648                               { u"STD97EncryptionKey"_ustr, css::uno::Any(aEnc97Key) },
649                               { u"STD97UniqueID"_ustr, css::uno::Any(aUniqueID) },
650                               { u"OOXPassword"_ustr, css::uno::Any(aPassword) },
651                           });
652         }
653     }
654 
655     return (eResult == DocPasswordVerifierResult::OK) ? aEncData : uno::Sequence< beans::NamedValue >();
656 }
657 
658 /*static*/ uno::Sequence< css::beans::NamedValue >
decryptGpgSession(const uno::Sequence<uno::Sequence<beans::NamedValue>> & rGpgProperties)659     DocPasswordHelper::decryptGpgSession(
660         const uno::Sequence< uno::Sequence< beans::NamedValue > >& rGpgProperties )
661 {
662 #if HAVE_FEATURE_GPGME
663     if ( !rGpgProperties.hasElements() )
664         return uno::Sequence< beans::NamedValue >();
665 
666     uno::Sequence< beans::NamedValue > aEncryptionData;
667     std::unique_ptr<GpgME::Context> ctx;
668     GpgME::initializeLibrary();
669     GpgME::Error err = GpgME::checkEngine(GpgME::OpenPGP);
670     if (err)
671         throw uno::RuntimeException(u"The GpgME library failed to initialize for the OpenPGP protocol."_ustr);
672 
673     ctx.reset( GpgME::Context::createForProtocol(GpgME::OpenPGP) );
674     if (ctx == nullptr)
675         throw uno::RuntimeException(u"The GpgME library failed to initialize for the OpenPGP protocol."_ustr);
676     ctx->setArmor(false);
677 
678     for (auto& rSequence : rGpgProperties)
679     {
680         if (rSequence.getLength() == 3)
681         {
682             // take CipherValue and try to decrypt that - stop after
683             // the first successful decryption
684 
685             // ctx is setup now, let's decrypt the lot!
686             uno::Sequence < sal_Int8 > aVector;
687             rSequence[2].Value >>= aVector;
688 
689             GpgME::Data cipher(
690                 reinterpret_cast<const char*>(aVector.getConstArray()),
691                 size_t(aVector.getLength()), false);
692             GpgME::Data plain;
693 
694             GpgME::DecryptionResult crypt_res = ctx->decrypt(
695                 cipher, plain);
696 
697             // NO_SECKEY -> skip
698             // BAD_PASSPHRASE -> retry?
699 
700             off_t result = plain.seek(0,SEEK_SET);
701             (void) result;
702             assert(result == 0);
703             int len=0, curr=0; char buf;
704             while( (curr=plain.read(&buf, 1)) )
705                 len += curr;
706 
707             if(crypt_res.error() || !len)
708                 continue; // can't use this key, take next one
709 
710             uno::Sequence < sal_Int8 > aKeyValue(len);
711             result = plain.seek(0,SEEK_SET);
712             assert(result == 0);
713             if( plain.read(aKeyValue.getArray(), len) != len )
714                 throw uno::RuntimeException(u"The GpgME library failed to read the encrypted value."_ustr);
715 
716             SAL_INFO("comphelper.crypto", "Extracted gpg session key of length: " << len);
717 
718             aEncryptionData = { { PACKAGE_ENCRYPTIONDATA_SHA256UTF8, uno::Any(aKeyValue) } };
719             break;
720         }
721     }
722 
723     if ( aEncryptionData.hasElements() )
724     {
725         uno::Sequence< beans::NamedValue > aContainer{
726             { u"GpgInfos"_ustr, uno::Any(rGpgProperties) }, { u"EncryptionKey"_ustr, uno::Any(aEncryptionData) }
727         };
728 
729         return aContainer;
730     }
731 #else
732     (void)rGpgProperties;
733 #endif
734     return uno::Sequence< beans::NamedValue >();
735 }
736 
737 } // namespace comphelper
738 
739 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
740