LibreOffice Module comphelper (master)  1
docpasswordhelper.cxx
Go to the documentation of this file.
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 
27 #include <comphelper/hash.hxx>
28 #include <comphelper/base64.hxx>
29 #include <comphelper/sequence.hxx>
30 #include <com/sun/star/beans/NamedValue.hpp>
31 #include <com/sun/star/beans/PropertyValue.hpp>
32 #include <com/sun/star/task/XInteractionHandler.hpp>
33 
34 #include <osl/diagnose.h>
35 #include <sal/log.hxx>
36 #include <rtl/digest.h>
37 #include <rtl/random.h>
38 #include <string.h>
39 
40 #if HAVE_FEATURE_GPGME
41 # include <context.h>
42 # include <data.h>
43 # include <decryptionresult.h>
44 #endif
45 
46 using ::com::sun::star::uno::Sequence;
47 using ::com::sun::star::uno::Exception;
48 using ::com::sun::star::uno::Reference;
49 using ::com::sun::star::task::PasswordRequestMode;
50 using ::com::sun::star::task::PasswordRequestMode_PASSWORD_ENTER;
51 using ::com::sun::star::task::PasswordRequestMode_PASSWORD_REENTER;
52 using ::com::sun::star::task::XInteractionHandler;
53 using ::com::sun::star::task::XInteractionRequest;
54 
55 using namespace ::com::sun::star;
56 
57 namespace comphelper {
58 
59 
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 
84 {
85 }
86 
87 
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.realloc( 4 );
99  aResult[0].Name = "algorithm-name";
100  aResult[0].Value <<= OUString( "PBKDF2" );
101  aResult[1].Name = "salt";
102  aResult[1].Value <<= aSalt;
103  aResult[2].Name = "iteration-count";
104  aResult[2].Value <<= nPBKDF2IterationCount;
105  aResult[3].Name = "hash";
106  aResult[3].Value <<= aNewHash;
107  }
108 
109  return aResult;
110 }
111 
112 
113 bool DocPasswordHelper::IsModifyPasswordCorrect( std::u16string_view aPassword, const uno::Sequence< beans::PropertyValue >& aInfo )
114 {
115  bool bResult = false;
116  if ( !aPassword.empty() && aInfo.hasElements() )
117  {
118  OUString sAlgorithm;
119  uno::Sequence< sal_Int8 > aSalt;
120  uno::Sequence< sal_Int8 > aHash;
121  sal_Int32 nCount = 0;
122 
123  for ( const auto & prop : aInfo )
124  {
125  if ( prop.Name == "algorithm-name" )
126  prop.Value >>= sAlgorithm;
127  else if ( prop.Name == "salt" )
128  prop.Value >>= aSalt;
129  else if ( prop.Name == "iteration-count" )
130  prop.Value >>= nCount;
131  else if ( prop.Name == "hash" )
132  prop.Value >>= aHash;
133  }
134 
135  if ( sAlgorithm == "PBKDF2" && aSalt.hasElements() && nCount > 0 && aHash.hasElements() )
136  {
137  uno::Sequence< sal_Int8 > aNewHash = GeneratePBKDF2Hash( aPassword, aSalt, nCount, aHash.getLength() );
138  for ( sal_Int32 nInd = 0; nInd < aNewHash.getLength() && nInd < aHash.getLength() && aNewHash[nInd] == aHash[nInd]; nInd ++ )
139  {
140  if ( nInd == aNewHash.getLength() - 1 && nInd == aHash.getLength() - 1 )
141  bResult = true;
142  }
143  }
144  }
145 
146  return bResult;
147 }
148 
149 
151  const OUString& aUString )
152 {
153  static const sal_uInt16 pInitialCode[] = {
154  0xE1F0, // 1
155  0x1D0F, // 2
156  0xCC9C, // 3
157  0x84C0, // 4
158  0x110C, // 5
159  0x0E10, // 6
160  0xF1CE, // 7
161  0x313E, // 8
162  0x1872, // 9
163  0xE139, // 10
164  0xD40F, // 11
165  0x84F9, // 12
166  0x280C, // 13
167  0xA96A, // 14
168  0x4EC3 // 15
169  };
170 
171  static const sal_uInt16 pEncryptionMatrix[15][7] = {
172  { 0xAEFC, 0x4DD9, 0x9BB2, 0x2745, 0x4E8A, 0x9D14, 0x2A09}, // last-14
173  { 0x7B61, 0xF6C2, 0xFDA5, 0xEB6B, 0xC6F7, 0x9DCF, 0x2BBF}, // last-13
174  { 0x4563, 0x8AC6, 0x05AD, 0x0B5A, 0x16B4, 0x2D68, 0x5AD0}, // last-12
175  { 0x0375, 0x06EA, 0x0DD4, 0x1BA8, 0x3750, 0x6EA0, 0xDD40}, // last-11
176  { 0xD849, 0xA0B3, 0x5147, 0xA28E, 0x553D, 0xAA7A, 0x44D5}, // last-10
177  { 0x6F45, 0xDE8A, 0xAD35, 0x4A4B, 0x9496, 0x390D, 0x721A}, // last-9
178  { 0xEB23, 0xC667, 0x9CEF, 0x29FF, 0x53FE, 0xA7FC, 0x5FD9}, // last-8
179  { 0x47D3, 0x8FA6, 0x8FA6, 0x1EDA, 0x3DB4, 0x7B68, 0xF6D0}, // last-7
180  { 0xB861, 0x60E3, 0xC1C6, 0x93AD, 0x377B, 0x6EF6, 0xDDEC}, // last-6
181  { 0x45A0, 0x8B40, 0x06A1, 0x0D42, 0x1A84, 0x3508, 0x6A10}, // last-5
182  { 0xAA51, 0x4483, 0x8906, 0x022D, 0x045A, 0x08B4, 0x1168}, // last-4
183  { 0x76B4, 0xED68, 0xCAF1, 0x85C3, 0x1BA7, 0x374E, 0x6E9C}, // last-3
184  { 0x3730, 0x6E60, 0xDCC0, 0xA9A1, 0x4363, 0x86C6, 0x1DAD}, // last-2
185  { 0x3331, 0x6662, 0xCCC4, 0x89A9, 0x0373, 0x06E6, 0x0DCC}, // last-1
186  { 0x1021, 0x2042, 0x4084, 0x8108, 0x1231, 0x2462, 0x48C4} // last
187  };
188 
189  sal_uInt32 nResult = 0;
190  sal_uInt32 nLen = aUString.getLength();
191 
192  if ( nLen )
193  {
194  if ( nLen > 15 )
195  nLen = 15;
196 
197  sal_uInt16 nHighResult = pInitialCode[nLen - 1];
198  sal_uInt16 nLowResult = 0;
199 
200  for ( sal_uInt32 nInd = 0; nInd < nLen; nInd++ )
201  {
202  // NO Encoding during conversion!
203  // The specification says that the low byte should be used in case it is not NULL
204  char nHighChar = static_cast<char>( aUString[nInd] >> 8 );
205  char nLowChar = static_cast<char>( aUString[nInd] & 0xFF );
206  char nChar = nLowChar ? nLowChar : nHighChar;
207 
208  for ( int nMatrixInd = 0; nMatrixInd < 7; ++nMatrixInd )
209  {
210  if ( ( nChar & ( 1 << nMatrixInd ) ) != 0 )
211  nHighResult = nHighResult ^ pEncryptionMatrix[15 - nLen + nInd][nMatrixInd];
212  }
213 
214  nLowResult = ( ( ( nLowResult >> 14 ) & 0x0001 ) | ( ( nLowResult << 1 ) & 0x7FFF ) ) ^ nChar;
215  }
216 
217  nLowResult = static_cast<sal_uInt16>( ( ( ( nLowResult >> 14 ) & 0x001 ) | ( ( nLowResult << 1 ) & 0x7FF ) ) ^ nLen ^ 0xCE4B );
218 
219  nResult = ( nHighResult << 16 ) | nLowResult;
220  }
221 
222  return nResult;
223 }
224 
225 
227  std::u16string_view aUString,
228  rtl_TextEncoding nEnc )
229 {
230  sal_uInt16 nResult = 0;
231 
232  OString aString = OUStringToOString( aUString, nEnc );
233 
234  if ( !aString.isEmpty() && aString.getLength() <= SAL_MAX_UINT16 )
235  {
236  for ( sal_Int32 nInd = aString.getLength() - 1; nInd >= 0; nInd-- )
237  {
238  nResult = ( ( nResult >> 14 ) & 0x01 ) | ( ( nResult << 1 ) & 0x7FFF );
239  nResult ^= aString[nInd];
240  }
241 
242  nResult = ( ( nResult >> 14 ) & 0x01 ) | ( ( nResult << 1 ) & 0x7FFF );
243  nResult ^= ( 0x8000 | ( 'N' << 8 ) | 'K' );
244  nResult ^= aString.getLength();
245  }
246 
247  return nResult;
248 }
249 
250 
252  std::u16string_view aUString )
253 {
254  sal_uInt16 nHash = GetXLHashAsUINT16( aUString );
255  return {sal_Int8(nHash >> 8), sal_Int8(nHash & 0xFF)};
256 }
257 
258 
259 std::vector<unsigned char> DocPasswordHelper::GetOoxHashAsVector(
260  const OUString& rPassword,
261  const std::vector<unsigned char>& rSaltValue,
262  sal_uInt32 nSpinCount,
263  comphelper::Hash::IterCount eIterCount,
264  std::u16string_view rAlgorithmName)
265 {
267  if (rAlgorithmName == u"SHA-512" || rAlgorithmName == u"SHA512")
269  else if (rAlgorithmName == u"SHA-256" || rAlgorithmName == u"SHA256")
271  else if (rAlgorithmName == u"SHA-1" || rAlgorithmName == u"SHA1") // "SHA1" might be in the wild
273  else if (rAlgorithmName == u"MD5")
275  else
276  return std::vector<unsigned char>();
277 
278  return comphelper::Hash::calculateHash( rPassword, rSaltValue, nSpinCount, eIterCount, eType);
279 }
280 
281 
282 css::uno::Sequence<sal_Int8> DocPasswordHelper::GetOoxHashAsSequence(
283  const OUString& rPassword,
284  const OUString& rSaltValue,
285  sal_uInt32 nSpinCount,
286  comphelper::Hash::IterCount eIterCount,
287  std::u16string_view rAlgorithmName)
288 {
289  std::vector<unsigned char> aSaltVec;
290  if (!rSaltValue.isEmpty())
291  {
292  css::uno::Sequence<sal_Int8> aSaltSeq;
293  comphelper::Base64::decode( aSaltSeq, rSaltValue);
294  aSaltVec = comphelper::sequenceToContainer<std::vector<unsigned char>>( aSaltSeq);
295  }
296 
297  std::vector<unsigned char> hash( GetOoxHashAsVector( rPassword, aSaltVec, nSpinCount, eIterCount, rAlgorithmName));
298 
299  return comphelper::containerToSequence<sal_Int8>( hash);
300 }
301 
303  const OUString& rPassword,
304  const OUString& rSaltValue,
305  sal_uInt32 nSpinCount,
306  comphelper::Hash::IterCount eIterCount,
307  std::u16string_view rAlgorithmName)
308 {
309  css::uno::Sequence<sal_Int8> aSeq( GetOoxHashAsSequence( rPassword, rSaltValue, nSpinCount,
310  eIterCount, rAlgorithmName));
311 
312  OUStringBuffer aBuf((aSeq.getLength()+2)/3*4);
313  comphelper::Base64::encode( aBuf, aSeq);
314  return aBuf.makeStringAndClear();
315 }
316 
317 
318 /*static*/ uno::Sequence< sal_Int8 > DocPasswordHelper::GenerateRandomByteSequence( sal_Int32 nLength )
319 {
320  uno::Sequence< sal_Int8 > aResult( nLength );
321 
322  rtlRandomPool aRandomPool = rtl_random_createPool ();
323  rtl_random_getBytes ( aRandomPool, aResult.getArray(), nLength );
324  rtl_random_destroyPool ( aRandomPool );
325 
326  return aResult;
327 }
328 
329 
330 /*static*/ uno::Sequence< sal_Int8 > DocPasswordHelper::GenerateStd97Key( const OUString& aPassword, const uno::Sequence< sal_Int8 >& aDocId )
331 {
332  uno::Sequence< sal_Int8 > aResultKey;
333  if ( !aPassword.isEmpty() && aDocId.getLength() == 16 )
334  {
335  sal_uInt16 pPassData[16] = {};
336 
337  sal_Int32 nPassLen = std::min< sal_Int32 >( aPassword.getLength(), 15 );
338  memcpy( pPassData, aPassword.getStr(), nPassLen * sizeof(pPassData[0]) );
339 
340  aResultKey = GenerateStd97Key( pPassData, aDocId );
341  }
342 
343  return aResultKey;
344 }
345 
346 
347 /*static*/ uno::Sequence< sal_Int8 > DocPasswordHelper::GenerateStd97Key( const sal_uInt16 pPassData[16], const uno::Sequence< sal_Int8 >& aDocId )
348 {
349  uno::Sequence< sal_Int8 > aResultKey;
350 
351  if ( aDocId.getLength() == 16 )
352  aResultKey = GenerateStd97Key(pPassData, reinterpret_cast<const sal_uInt8*>(aDocId.getConstArray()));
353 
354  return aResultKey;
355 }
356 
357 
358 /*static*/ uno::Sequence< sal_Int8 > DocPasswordHelper::GenerateStd97Key( const sal_uInt16 pPassData[16], const sal_uInt8 pDocId[16] )
359 {
360  uno::Sequence< sal_Int8 > aResultKey;
361  if ( pPassData[0] )
362  {
363  sal_uInt8 pKeyData[64] = {};
364 
365  sal_Int32 nInd = 0;
366 
367  // Fill PassData into KeyData.
368  for ( nInd = 0; nInd < 16 && pPassData[nInd]; nInd++)
369  {
370  pKeyData[2*nInd] = sal::static_int_cast< sal_uInt8 >( (pPassData[nInd] >> 0) & 0xff );
371  pKeyData[2*nInd + 1] = sal::static_int_cast< sal_uInt8 >( (pPassData[nInd] >> 8) & 0xff );
372  }
373 
374  pKeyData[2*nInd] = 0x80;
375  pKeyData[56] = sal::static_int_cast< sal_uInt8 >( nInd << 4 );
376 
377  // Fill raw digest of KeyData into KeyData.
378  rtlDigest hDigest = rtl_digest_create ( rtl_Digest_AlgorithmMD5 );
379  (void)rtl_digest_updateMD5 (
380  hDigest, pKeyData, sizeof(pKeyData));
381  (void)rtl_digest_rawMD5 (
382  hDigest, pKeyData, RTL_DIGEST_LENGTH_MD5);
383 
384  // Update digest with KeyData and Unique.
385  for ( nInd = 0; nInd < 16; nInd++ )
386  {
387  rtl_digest_updateMD5( hDigest, pKeyData, 5 );
388  rtl_digest_updateMD5( hDigest, pDocId, 16 );
389  }
390 
391  // Update digest with padding.
392  pKeyData[16] = 0x80;
393  memset( pKeyData + 17, 0, sizeof(pKeyData) - 17 );
394  pKeyData[56] = 0x80;
395  pKeyData[57] = 0x0a;
396 
397  rtl_digest_updateMD5( hDigest, &(pKeyData[16]), sizeof(pKeyData) - 16 );
398 
399  // Fill raw digest of above updates
400  aResultKey.realloc( RTL_DIGEST_LENGTH_MD5 );
401  rtl_digest_rawMD5 ( hDigest, reinterpret_cast<sal_uInt8*>(aResultKey.getArray()), aResultKey.getLength() );
402 
403  // Erase KeyData array and leave.
404  rtl_secureZeroMemory (pKeyData, sizeof(pKeyData));
405 
406  rtl_digest_destroy(hDigest);
407  }
408 
409  return aResultKey;
410 }
411 
412 
413 /*static*/ css::uno::Sequence< css::beans::NamedValue > DocPasswordHelper::requestAndVerifyDocPassword(
414  IDocPasswordVerifier& rVerifier,
415  const css::uno::Sequence< css::beans::NamedValue >& rMediaEncData,
416  const OUString& rMediaPassword,
417  const Reference< XInteractionHandler >& rxInteractHandler,
418  const OUString& rDocumentUrl,
419  DocPasswordRequestType eRequestType,
420  const std::vector< OUString >* pDefaultPasswords,
421  bool* pbIsDefaultPassword )
422 {
423  css::uno::Sequence< css::beans::NamedValue > aEncData;
424  OUString aPassword;
426 
427  sal_Int32 nMediaEncDataCount = rMediaEncData.getLength();
428 
429  // tdf#93389: if the document is being restored from autorecovery, we need to add encryption
430  // data also for real document type.
431  // TODO: get real filter name here (from CheckPasswd_Impl), to only add necessary data
432  bool bForSalvage = false;
433  if (nMediaEncDataCount)
434  {
435  for (auto& val : rMediaEncData)
436  {
437  if (val.Name == "ForSalvage")
438  {
439  --nMediaEncDataCount; // don't consider this element below
440  val.Value >>= bForSalvage;
441  break;
442  }
443  }
444  }
445 
446  // first, try provided default passwords
447  if( pbIsDefaultPassword )
448  *pbIsDefaultPassword = false;
449  if( pDefaultPasswords )
450  {
451  for( const auto& rPassword : *pDefaultPasswords )
452  {
453  OSL_ENSURE( !rPassword.isEmpty(), "DocPasswordHelper::requestAndVerifyDocPassword - unexpected empty default password" );
454  if( !rPassword.isEmpty() )
455  {
456  eResult = rVerifier.verifyPassword( rPassword, aEncData );
457  if (eResult == DocPasswordVerifierResult::OK)
458  {
459  aPassword = rPassword;
460  if (pbIsDefaultPassword)
461  *pbIsDefaultPassword = true;
462  }
464  break;
465  }
466  }
467  }
468 
469  // try media encryption data (skip, if result is OK or ABORT)
471  {
472  if (nMediaEncDataCount)
473  {
474  eResult = rVerifier.verifyEncryptionData( rMediaEncData );
475  if( eResult == DocPasswordVerifierResult::OK )
476  aEncData = rMediaEncData;
477  }
478  }
479 
480  // try media password (skip, if result is OK or ABORT)
482  {
483  if( !rMediaPassword.isEmpty() )
484  {
485  eResult = rVerifier.verifyPassword( rMediaPassword, aEncData );
486  if (eResult == DocPasswordVerifierResult::OK)
487  aPassword = rMediaPassword;
488  }
489  }
490 
491  // request a password (skip, if result is OK or ABORT)
492  if( (eResult == DocPasswordVerifierResult::WrongPassword) && rxInteractHandler.is() ) try
493  {
494  PasswordRequestMode eRequestMode = PasswordRequestMode_PASSWORD_ENTER;
495  while( eResult == DocPasswordVerifierResult::WrongPassword )
496  {
497  rtl::Reference<DocPasswordRequest> pRequest = new DocPasswordRequest( eRequestType, eRequestMode, rDocumentUrl );
498  rxInteractHandler->handle( pRequest );
499  if( pRequest->isPassword() )
500  {
501  if( !pRequest->getPassword().isEmpty() )
502  eResult = rVerifier.verifyPassword( pRequest->getPassword(), aEncData );
503  if (eResult == DocPasswordVerifierResult::OK)
504  aPassword = pRequest->getPassword();
505  }
506  else
507  {
509  }
510  eRequestMode = PasswordRequestMode_PASSWORD_REENTER;
511  }
512  }
513  catch( Exception& )
514  {
515  }
516 
517  if (eResult == DocPasswordVerifierResult::OK && !aPassword.isEmpty())
518  {
519  if (std::find_if(std::cbegin(aEncData), std::cend(aEncData),
520  [](const css::beans::NamedValue& val) {
521  return val.Name == PACKAGE_ENCRYPTIONDATA_SHA256UTF8;
522  })
523  == std::cend(aEncData))
524  {
525  // tdf#118639: We need ODF encryption data for autorecovery, where password
526  // will already be unavailable, so generate and append it here
527  aEncData = comphelper::concatSequences(
528  aEncData, OStorageHelper::CreatePackageEncryptionData(aPassword));
529  }
530 
531  if (bForSalvage)
532  {
533  // TODO: add individual methods for different target filter, and only call what's needed
534 
535  // 1. Prepare binary MS formats encryption data
536  auto aUniqueID = GenerateRandomByteSequence(16);
537  auto aEnc97Key = GenerateStd97Key(aPassword, aUniqueID);
538  // 2. Add MS binary and OOXML encryption data to result
539  aEncData = comphelper::concatSequences(
540  aEncData, std::initializer_list<beans::NamedValue>{
541  { "STD97EncryptionKey", css::uno::Any(aEnc97Key) },
542  { "STD97UniqueID", css::uno::Any(aUniqueID) },
543  { "OOXPassword", css::uno::Any(aPassword) },
544  });
545  }
546  }
547 
548  return (eResult == DocPasswordVerifierResult::OK) ? aEncData : uno::Sequence< beans::NamedValue >();
549 }
550 
551 /*static*/ uno::Sequence< css::beans::NamedValue >
553  const uno::Sequence< uno::Sequence< beans::NamedValue > >& rGpgProperties )
554 {
555 #if HAVE_FEATURE_GPGME
556  if ( !rGpgProperties.hasElements() )
557  return uno::Sequence< beans::NamedValue >();
558 
559  uno::Sequence< beans::NamedValue > aEncryptionData(1);
560  std::unique_ptr<GpgME::Context> ctx;
561  GpgME::initializeLibrary();
562  GpgME::Error err = GpgME::checkEngine(GpgME::OpenPGP);
563  if (err)
564  throw uno::RuntimeException("The GpgME library failed to initialize for the OpenPGP protocol.");
565 
566  ctx.reset( GpgME::Context::createForProtocol(GpgME::OpenPGP) );
567  if (ctx == nullptr)
568  throw uno::RuntimeException("The GpgME library failed to initialize for the OpenPGP protocol.");
569  ctx->setArmor(false);
570 
571  const uno::Sequence < beans::NamedValue > *pSequence = rGpgProperties.getConstArray();
572  const sal_Int32 nLength = rGpgProperties.getLength();
573  for ( sal_Int32 i = 0; i < nLength ; i++, pSequence++ )
574  {
575  const beans::NamedValue *pValues = pSequence->getConstArray();
576  if ( pSequence->getLength() == 3 )
577  {
578  // take CipherValue and try to decrypt that - stop after
579  // the first successful decryption
580 
581  // ctx is setup now, let's decrypt the lot!
582  uno::Sequence < sal_Int8 > aVector;
583  pValues[2].Value >>= aVector;
584 
585  GpgME::Data cipher(
586  reinterpret_cast<const char*>(aVector.getConstArray()),
587  size_t(aVector.getLength()), false);
588  GpgME::Data plain;
589 
590  GpgME::DecryptionResult crypt_res = ctx->decrypt(
591  cipher, plain);
592 
593  // NO_SECKEY -> skip
594  // BAD_PASSPHRASE -> retry?
595 
596  off_t result = plain.seek(0,SEEK_SET);
597  (void) result;
598  assert(result == 0);
599  int len=0, curr=0; char buf;
600  while( (curr=plain.read(&buf, 1)) )
601  len += curr;
602 
603  if(crypt_res.error() || !len)
604  continue; // can't use this key, take next one
605 
606  uno::Sequence < sal_Int8 > aKeyValue(len);
607  result = plain.seek(0,SEEK_SET);
608  assert(result == 0);
609  if( plain.read(aKeyValue.getArray(), len) != len )
610  throw uno::RuntimeException("The GpgME library failed to read the encrypted value.");
611 
612  SAL_INFO("comphelper.crypto", "Extracted gpg session key of length: " << len);
613 
614  aEncryptionData[0].Name = PACKAGE_ENCRYPTIONDATA_SHA256UTF8;
615  aEncryptionData[0].Value <<= aKeyValue;
616  break;
617  }
618  }
619 
620  if ( aEncryptionData[0].Value.hasValue() )
621  {
622  uno::Sequence< beans::NamedValue > aContainer(2);
623  aContainer[0].Name = "GpgInfos";
624  aContainer[0].Value <<= rGpgProperties;
625  aContainer[1].Name = "EncryptionKey";
626  aContainer[1].Value <<= aEncryptionData;
627 
628  return aContainer;
629  }
630 #else
631  (void)rGpgProperties;
632 #endif
633  return uno::Sequence< beans::NamedValue >();
634 }
635 
636 } // namespace comphelper
637 
638 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
static std::vector< unsigned char > GetOoxHashAsVector(const OUString &rPassword, const std::vector< unsigned char > &rSaltValue, sal_uInt32 nSpinCount, comphelper::Hash::IterCount eIterCount, std::u16string_view rAlgorithmName)
Convenience function to calculate a salted hash with iterations as specified in https://msdn.microsoft.com/en-us/library/dd920692 for the OOXML sheetProtection and fileSharing elements, or https://msdn.microsoft.com/en-us/library/dd924776 and https://msdn.microsoft.com/en-us/library/dd925430 for Standard and Agile Encryption.
Implements the task.XInteractionRequest interface for requesting a password string for a document...
signed char sal_Int8
virtual DocPasswordVerifierResult verifyEncryptionData(const css::uno::Sequence< css::beans::NamedValue > &o_rEncryptionData)=0
Will be called every time an encryption data needs to be verified.
aBuf
static bool IsModifyPasswordCorrect(std::u16string_view aPassword, const css::uno::Sequence< css::beans::PropertyValue > &aInfo)
This helper function allows to check whether the "Password to modify" provided by user is the correct...
Value
#define SAL_MAX_UINT16
int nCount
static css::uno::Sequence< css::beans::NamedValue > CreatePackageEncryptionData(std::u16string_view aPassword)
static OUString GetOoxHashAsBase64(const OUString &rPassword, const OUString &rSaltValue, sal_uInt32 nSpinCount, comphelper::Hash::IterCount eIterCount, std::u16string_view rAlgorithmName)
Convenience function to calculate a salted hash with iterations as specified in https://msdn.microsoft.com/en-us/library/dd920692 for the OOXML sheetProtection and fileSharing elements, or https://msdn.microsoft.com/en-us/library/dd924776 and https://msdn.microsoft.com/en-us/library/dd925430 for Standard and Agile Encryption.
OString OUStringToOString(std::u16string_view str, ConnectionSettings const *settings)
static void encode(OUStringBuffer &aStrBuffer, const css::uno::Sequence< sal_Int8 > &aPass)
encodes the given byte sequence into Base64
DocumentType eType
err
int i
static css::uno::Sequence< css::beans::NamedValue > decryptGpgSession(const css::uno::Sequence< css::uno::Sequence< css::beans::NamedValue > > &rGpgProperties)
static sal_uInt16 GetXLHashAsUINT16(std::u16string_view aString, rtl_TextEncoding nEnc=RTL_TEXTENCODING_UTF8)
This helper function generates the hash code based on the algorithm specified by MS for "Password to ...
static void decode(css::uno::Sequence< sal_Int8 > &aPass, const OUString &sBuffer)
Definition: base64.cxx:139
float u
static css::uno::Sequence< sal_Int8 > GenerateStd97Key(const OUString &aPassword, const css::uno::Sequence< sal_Int8 > &aDocId)
This helper function generates a byte sequence representing the key digest value used by MSCodec_Std9...
static css::uno::Sequence< sal_Int8 > GetXLHashAsSequence(std::u16string_view aString)
This helper function generates the hash code based on the algorithm specified by MS for "Password to ...
tuple ctx
css::uno::Sequence< T > concatSequences(const css::uno::Sequence< T > &rS1, const Ss &...rSn)
concat several sequences
Definition: sequence.hxx:49
DocPasswordRequestType
Selects which UNO document password request type to use.
static css::uno::Sequence< css::beans::PropertyValue > GenerateNewModifyPasswordInfo(std::u16string_view aPassword)
This helper function generates the information related to "Password to modify" provided by user...
static css::uno::Sequence< sal_Int8 > GenerateRandomByteSequence(sal_Int32 nLength)
This helper function generates a random sequence of bytes of requested length.
const PropertyValue * pValues
void * rtlRandomPool
unsigned char sal_uInt8
#define PACKAGE_ENCRYPTIONDATA_SHA256UTF8
Base class for a password verifier used by the DocPasswordHelper class below.
static css::uno::Sequence< css::beans::NamedValue > requestAndVerifyDocPassword(IDocPasswordVerifier &rVerifier, const css::uno::Sequence< css::beans::NamedValue > &rMediaEncData, const OUString &rMediaPassword, const css::uno::Reference< css::task::XInteractionHandler > &rxInteractHandler, const OUString &rDocumentUrl, DocPasswordRequestType eRequestType, const ::std::vector< OUString > *pDefaultPasswords=nullptr, bool *pbIsDefaultPassword=nullptr)
This helper function tries to request and verify a password to load a protected document.
#define SAL_INFO(area, stream)
Sequence< sal_Int8 > aSeq
static sal_uInt32 GetWordHashAsUINT32(const OUString &aString)
This helper function generates the hash code based on the algorithm specified by MS for "Password to ...
static std::vector< unsigned char > calculateHash(const unsigned char *pInput, size_t length, HashType eType)
Definition: hash.cxx:154
Any result
static uno::Sequence< sal_Int8 > GeneratePBKDF2Hash(std::u16string_view aPassword, const uno::Sequence< sal_Int8 > &aSalt, sal_Int32 nCount, sal_Int32 nHashLength)
sal_Int32 nLength
virtual DocPasswordVerifierResult verifyPassword(const OUString &rPassword, css::uno::Sequence< css::beans::NamedValue > &o_rEncryptionData)=0
Will be called every time a password needs to be verified.
static css::uno::Sequence< sal_Int8 > GetOoxHashAsSequence(const OUString &rPassword, const OUString &rSaltValue, sal_uInt32 nSpinCount, comphelper::Hash::IterCount eIterCount, std::u16string_view rAlgorithmName)
Convenience function to calculate a salted hash with iterations as specified in https://msdn.microsoft.com/en-us/library/dd920692 for the OOXML sheetProtection and fileSharing elements, or https://msdn.microsoft.com/en-us/library/dd924776 and https://msdn.microsoft.com/en-us/library/dd925430 for Standard and Agile Encryption.
typedef void(CALLTYPE *GetFuncDataPtr)(sal_uInt16 &nNo