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