20#include <config_gpgme.h>
31#include <com/sun/star/beans/NamedValue.hpp>
32#include <com/sun/star/beans/PropertyValue.hpp>
33#include <com/sun/star/task/XInteractionHandler.hpp>
35#include <osl/diagnose.h>
37#include <rtl/digest.h>
38#include <rtl/random.h>
44# include <decryptionresult.h>
47using ::com::sun::star::uno::Sequence;
48using ::com::sun::star::uno::Exception;
49using ::com::sun::star::uno::Reference;
50using ::com::sun::star::task::PasswordRequestMode;
51using ::com::sun::star::task::PasswordRequestMode_PASSWORD_ENTER;
52using ::com::sun::star::task::PasswordRequestMode_PASSWORD_REENTER;
53using ::com::sun::star::task::XInteractionHandler;
60static uno::Sequence< sal_Int8 >
GeneratePBKDF2Hash( std::u16string_view aPassword,
const uno::Sequence< sal_Int8 >& aSalt, sal_Int32 nCount, sal_Int32 nHashLength )
62 uno::Sequence< sal_Int8 > aResult;
64 if ( !aPassword.empty() && aSalt.hasElements() &&
nCount && nHashLength )
69 aResult.realloc( 16 );
70 rtl_digest_PBKDF2(
reinterpret_cast < sal_uInt8 *
> ( aResult.getArray() ),
72 reinterpret_cast < const sal_uInt8 *
> ( aBytePass.getStr() ),
73 aBytePass.getLength(),
74 reinterpret_cast < const sal_uInt8 *
> ( aSalt.getConstArray() ),
90 uno::Sequence< beans::PropertyValue > aResult;
93 sal_Int32
const nPBKDF2IterationCount = 100000;
95 uno::Sequence< sal_Int8 > aNewHash =
GeneratePBKDF2Hash(aPassword, aSalt, nPBKDF2IterationCount, 16);
96 if ( aNewHash.hasElements() )
108uno::Sequence<beans::PropertyValue>
111 uno::Sequence<beans::PropertyValue> aResult;
113 if (!aPassword.empty())
118 OUString sSalt =
aBuffer.makeStringAndClear();
120 sal_Int32
const nIterationCount = 100000;
121 OUString sAlgorithm(
"SHA-512");
126 if (!
sHash.isEmpty())
141 uno::Sequence< beans::PropertyValue > aResult;
142 OUString sAlgorithm,
sHash, sSalt, sCount;
143 sal_Int32 nAlgorithm = 0;
145 for (
const auto & prop : aInfo )
147 if ( prop.Name ==
"cryptAlgorithmSid" )
149 prop.Value >>= sAlgorithm;
150 nAlgorithm = sAlgorithm.toInt32();
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;
162 else if (nAlgorithm == 2)
164 else if (nAlgorithm == 3)
166 else if (nAlgorithm == 4)
167 sAlgorithm =
"SHA-1";
168 else if (nAlgorithm == 5)
170 else if (nAlgorithm == 6)
171 sAlgorithm =
"RIPEMD";
172 else if (nAlgorithm == 7)
173 sAlgorithm =
"RIPEMD-160";
174 else if (nAlgorithm == 9)
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";
183 if ( !sCount.isEmpty() )
185 sal_Int32
nCount = sCount.toInt32();
198 bool bResult =
false;
199 if ( !aPassword.empty() && aInfo.hasElements() )
205 for (
const auto & prop : aInfo )
207 if ( prop.Name ==
"algorithm-name" )
208 prop.Value >>= sAlgorithm;
209 else if ( prop.Name ==
"salt" )
211 else if ( prop.Name ==
"iteration-count" )
213 else if ( prop.Name ==
"hash" )
217 if ( sAlgorithm ==
"PBKDF2" )
219 uno::Sequence<sal_Int8> aIntSalt, aIntHash;
222 if (aIntSalt.hasElements() &&
nCount > 0 && aIntHash.hasElements())
224 uno::Sequence<sal_Int8> aNewHash
226 for (sal_Int32 nInd = 0; nInd < aNewHash.getLength() && nInd < aIntHash.getLength()
227 && aNewHash[nInd] == aIntHash[nInd];
230 if (nInd == aNewHash.getLength() - 1 && nInd == aIntHash.getLength() - 1)
237 OUString sSalt,
sHash;
240 if (!sSalt.isEmpty() && !
sHash.isEmpty())
245 if (!aNewHash.isEmpty())
246 bResult = aNewHash ==
sHash;
256 std::u16string_view aUString )
258 static const sal_uInt16 pInitialCode[] = {
276 static const sal_uInt16 pEncryptionMatrix[15][7] = {
277 { 0xAEFC, 0x4DD9, 0x9BB2, 0x2745, 0x4E8A, 0x9D14, 0x2A09},
278 { 0x7B61, 0xF6C2, 0xFDA5, 0xEB6B, 0xC6F7, 0x9DCF, 0x2BBF},
279 { 0x4563, 0x8AC6, 0x05AD, 0x0B5A, 0x16B4, 0x2D68, 0x5AD0},
280 { 0x0375, 0x06EA, 0x0DD4, 0x1BA8, 0x3750, 0x6EA0, 0xDD40},
281 { 0xD849, 0xA0B3, 0x5147, 0xA28E, 0x553D, 0xAA7A, 0x44D5},
282 { 0x6F45, 0xDE8A, 0xAD35, 0x4A4B, 0x9496, 0x390D, 0x721A},
283 { 0xEB23, 0xC667, 0x9CEF, 0x29FF, 0x53FE, 0xA7FC, 0x5FD9},
284 { 0x47D3, 0x8FA6, 0x8FA6, 0x1EDA, 0x3DB4, 0x7B68, 0xF6D0},
285 { 0xB861, 0x60E3, 0xC1C6, 0x93AD, 0x377B, 0x6EF6, 0xDDEC},
286 { 0x45A0, 0x8B40, 0x06A1, 0x0D42, 0x1A84, 0x3508, 0x6A10},
287 { 0xAA51, 0x4483, 0x8906, 0x022D, 0x045A, 0x08B4, 0x1168},
288 { 0x76B4, 0xED68, 0xCAF1, 0x85C3, 0x1BA7, 0x374E, 0x6E9C},
289 { 0x3730, 0x6E60, 0xDCC0, 0xA9A1, 0x4363, 0x86C6, 0x1DAD},
290 { 0x3331, 0x6662, 0xCCC4, 0x89A9, 0x0373, 0x06E6, 0x0DCC},
291 { 0x1021, 0x2042, 0x4084, 0x8108, 0x1231, 0x2462, 0x48C4}
294 sal_uInt32 nResult = 0;
295 size_t nLen = aUString.size();
302 sal_uInt16 nHighResult = pInitialCode[nLen - 1];
303 sal_uInt16 nLowResult = 0;
305 for (
size_t nInd = 0; nInd < nLen; nInd++ )
309 char nHighChar =
static_cast<char>( aUString[nInd] >> 8 );
310 char nLowChar =
static_cast<char>( aUString[nInd] & 0xFF );
311 char nChar = nLowChar ? nLowChar : nHighChar;
313 for (
int nMatrixInd = 0; nMatrixInd < 7; ++nMatrixInd )
315 if ( ( nChar & ( 1 << nMatrixInd ) ) != 0 )
316 nHighResult = nHighResult ^ pEncryptionMatrix[15 - nLen + nInd][nMatrixInd];
319 nLowResult = ( ( ( nLowResult >> 14 ) & 0x0001 ) | ( ( nLowResult << 1 ) & 0x7FFF ) ) ^ nChar;
322 nLowResult =
static_cast<sal_uInt16
>( ( ( ( nLowResult >> 14 ) & 0x001 ) | ( ( nLowResult << 1 ) & 0x7FF ) ) ^ nLen ^ 0xCE4B );
324 nResult = ( nHighResult << 16 ) | nLowResult;
332 std::u16string_view aUString,
333 rtl_TextEncoding nEnc )
335 sal_uInt16 nResult = 0;
339 if ( !aString.isEmpty() && aString.getLength() <=
SAL_MAX_UINT16 )
341 for ( sal_Int32 nInd = aString.getLength() - 1; nInd >= 0; nInd-- )
343 nResult = ( ( nResult >> 14 ) & 0x01 ) | ( ( nResult << 1 ) & 0x7FFF );
344 nResult ^= aString[nInd];
347 nResult = ( ( nResult >> 14 ) & 0x01 ) | ( ( nResult << 1 ) & 0x7FFF );
348 nResult ^= ( 0x8000 | (
'N' << 8 ) |
'K' );
349 nResult ^= aString.getLength();
357 std::u16string_view aUString )
365 const OUString& rPassword,
366 const std::vector<unsigned char>& rSaltValue,
367 sal_uInt32 nSpinCount,
369 std::u16string_view rAlgorithmName)
372 if (rAlgorithmName ==
u"SHA-512" || rAlgorithmName ==
u"SHA512")
374 else if (rAlgorithmName ==
u"SHA-256" || rAlgorithmName ==
u"SHA256")
376 else if (rAlgorithmName ==
u"SHA-1" || rAlgorithmName ==
u"SHA1")
378 else if (rAlgorithmName ==
u"MD5")
381 return std::vector<unsigned char>();
388 const OUString& rPassword,
389 std::u16string_view rSaltValue,
390 sal_uInt32 nSpinCount,
392 std::u16string_view rAlgorithmName)
394 std::vector<unsigned char> aSaltVec;
395 if (!rSaltValue.empty())
397 css::uno::Sequence<sal_Int8> aSaltSeq;
399 aSaltVec = comphelper::sequenceToContainer<std::vector<unsigned char>>( aSaltSeq);
402 std::vector<unsigned char> hash(
GetOoxHashAsVector( rPassword, aSaltVec, nSpinCount, eIterCount, rAlgorithmName));
404 return comphelper::containerToSequence<sal_Int8>( hash);
408 const OUString& rPassword,
409 std::u16string_view rSaltValue,
410 sal_uInt32 nSpinCount,
412 std::u16string_view rAlgorithmName)
415 eIterCount, rAlgorithmName));
417 OUStringBuffer
aBuf((
aSeq.getLength()+2)/3*4);
419 return aBuf.makeStringAndClear();
425 uno::Sequence< sal_Int8 > aResult(
nLength );
428 rtl_random_getBytes ( aRandomPool, aResult.getArray(),
nLength );
429 rtl_random_destroyPool ( aRandomPool );
437 uno::Sequence< sal_Int8 > aResultKey;
438 if ( !aPassword.empty() && aDocId.getLength() == 16 )
440 sal_uInt16 pPassData[16] = {};
442 sal_Int32 nPassLen = std::min< sal_Int32 >( aPassword.size(), 15 );
443 memcpy( pPassData, aPassword.data(), nPassLen *
sizeof(pPassData[0]) );
454 uno::Sequence< sal_Int8 > aResultKey;
456 if ( aDocId.getLength() == 16 )
465 uno::Sequence< sal_Int8 > aResultKey;
473 for ( nInd = 0; nInd < 16 && pPassData[nInd]; nInd++)
475 pKeyData[2*nInd] = sal::static_int_cast< sal_uInt8 >( (pPassData[nInd] >> 0) & 0xff );
476 pKeyData[2*nInd + 1] = sal::static_int_cast< sal_uInt8 >( (pPassData[nInd] >> 8) & 0xff );
479 pKeyData[2*nInd] = 0x80;
480 pKeyData[56] = sal::static_int_cast< sal_uInt8 >( nInd << 4 );
483 rtlDigest hDigest = rtl_digest_create ( rtl_Digest_AlgorithmMD5 );
484 (void)rtl_digest_updateMD5 (
485 hDigest, pKeyData,
sizeof(pKeyData));
486 (void)rtl_digest_rawMD5 (
487 hDigest, pKeyData, RTL_DIGEST_LENGTH_MD5);
490 for ( nInd = 0; nInd < 16; nInd++ )
492 rtl_digest_updateMD5( hDigest, pKeyData, 5 );
493 rtl_digest_updateMD5( hDigest, pDocId, 16 );
498 memset( pKeyData + 17, 0,
sizeof(pKeyData) - 17 );
502 rtl_digest_updateMD5( hDigest, &(pKeyData[16]),
sizeof(pKeyData) - 16 );
505 aResultKey.realloc( RTL_DIGEST_LENGTH_MD5 );
506 rtl_digest_rawMD5 ( hDigest,
reinterpret_cast<sal_uInt8*
>(aResultKey.getArray()), aResultKey.getLength() );
509 rtl_secureZeroMemory (pKeyData,
sizeof(pKeyData));
511 rtl_digest_destroy(hDigest);
520 const css::uno::Sequence< css::beans::NamedValue >& rMediaEncData,
521 const OUString& rMediaPassword,
522 const Reference< XInteractionHandler >& rxInteractHandler,
523 const OUString& rDocumentUrl,
525 const std::vector< OUString >* pDefaultPasswords,
526 bool* pbIsDefaultPassword )
528 css::uno::Sequence< css::beans::NamedValue > aEncData;
532 sal_Int32 nMediaEncDataCount = rMediaEncData.getLength();
537 bool bForSalvage =
false;
538 if (nMediaEncDataCount)
540 for (
auto& val : rMediaEncData)
542 if (val.Name ==
"ForSalvage")
544 --nMediaEncDataCount;
545 val.Value >>= bForSalvage;
552 if( pbIsDefaultPassword )
553 *pbIsDefaultPassword =
false;
554 if( pDefaultPasswords )
556 for(
const auto& rPassword : *pDefaultPasswords )
558 OSL_ENSURE( !rPassword.isEmpty(),
"DocPasswordHelper::requestAndVerifyDocPassword - unexpected empty default password" );
559 if( !rPassword.isEmpty() )
564 aPassword = rPassword;
565 if (pbIsDefaultPassword)
566 *pbIsDefaultPassword =
true;
577 if (nMediaEncDataCount)
581 aEncData = rMediaEncData;
588 if( !rMediaPassword.isEmpty() )
592 aPassword = rMediaPassword;
599 PasswordRequestMode eRequestMode = PasswordRequestMode_PASSWORD_ENTER;
603 rxInteractHandler->handle( pRequest );
604 if( pRequest->isPassword() )
606 if( !pRequest->getPassword().isEmpty() )
607 eResult = rVerifier.
verifyPassword( pRequest->getPassword(), aEncData );
609 aPassword = pRequest->getPassword();
615 eRequestMode = PasswordRequestMode_PASSWORD_REENTER;
624 if (std::none_of(std::cbegin(aEncData), std::cend(aEncData),
625 [](
const css::beans::NamedValue& val) {
644 aEncData, std::initializer_list<beans::NamedValue>{
645 {
"STD97EncryptionKey", css::uno::Any(aEnc97Key) },
646 {
"STD97UniqueID", css::uno::Any(aUniqueID) },
647 {
"OOXPassword", css::uno::Any(aPassword) },
655 uno::Sequence< css::beans::NamedValue >
657 const uno::Sequence< uno::Sequence< beans::NamedValue > >& rGpgProperties )
659#if HAVE_FEATURE_GPGME
660 if ( !rGpgProperties.hasElements() )
661 return uno::Sequence< beans::NamedValue >();
663 uno::Sequence< beans::NamedValue > aEncryptionData;
664 std::unique_ptr<GpgME::Context>
ctx;
665 GpgME::initializeLibrary();
666 GpgME::Error
err = GpgME::checkEngine(GpgME::OpenPGP);
668 throw uno::RuntimeException(
"The GpgME library failed to initialize for the OpenPGP protocol.");
670 ctx.reset( GpgME::Context::createForProtocol(GpgME::OpenPGP) );
672 throw uno::RuntimeException(
"The GpgME library failed to initialize for the OpenPGP protocol.");
673 ctx->setArmor(
false);
675 const uno::Sequence < beans::NamedValue > *pSequence = rGpgProperties.getConstArray();
676 const sal_Int32
nLength = rGpgProperties.getLength();
677 for ( sal_Int32
i = 0;
i <
nLength ;
i++, pSequence++ )
679 const beans::NamedValue *
pValues = pSequence->getConstArray();
680 if ( pSequence->getLength() == 3 )
686 uno::Sequence < sal_Int8 > aVector;
690 reinterpret_cast<const char*
>(aVector.getConstArray()),
691 size_t(aVector.getLength()),
false);
694 GpgME::DecryptionResult crypt_res =
ctx->decrypt(
700 off_t
result = plain.seek(0,SEEK_SET);
703 int len=0, curr=0;
char buf;
704 while( (curr=plain.read(&buf, 1)) )
707 if(crypt_res.error() || !len)
710 uno::Sequence < sal_Int8 > aKeyValue(len);
711 result = plain.seek(0,SEEK_SET);
713 if( plain.read(aKeyValue.getArray(), len) != len )
714 throw uno::RuntimeException(
"The GpgME library failed to read the encrypted value.");
716 SAL_INFO(
"comphelper.crypto",
"Extracted gpg session key of length: " << len);
723 if ( aEncryptionData.hasElements() )
725 uno::Sequence< beans::NamedValue > aContainer{
726 {
"GpgInfos",
uno::Any(rGpgProperties) }, {
"EncryptionKey",
uno::Any(aEncryptionData) }
732 (void)rGpgProperties;
734 return uno::Sequence< beans::NamedValue >();
const PropertyValue * pValues
static void encode(OUStringBuffer &aStrBuffer, const css::uno::Sequence< sal_Int8 > &aPass)
encodes the given byte sequence into Base64
static void decode(css::uno::Sequence< sal_Int8 > &aPass, std::u16string_view sBuffer)
static css::uno::Sequence< css::beans::NamedValue > decryptGpgSession(const css::uno::Sequence< css::uno::Sequence< css::beans::NamedValue > > &rGpgProperties)
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 ...
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 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.
static css::uno::Sequence< sal_Int8 > GenerateRandomByteSequence(sal_Int32 nLength)
This helper function generates a random sequence of bytes of requested length.
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...
static css::uno::Sequence< css::beans::PropertyValue > ConvertPasswordInfo(const css::uno::Sequence< css::beans::PropertyValue > &aInfo)
This helper function converts a grab-bagged password, e.g.
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....
static OUString GetOoxHashAsBase64(const OUString &rPassword, std::u16string_view 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....
static css::uno::Sequence< css::beans::PropertyValue > GenerateNewModifyPasswordInfoOOXML(std::u16string_view aPassword)
static sal_uInt32 GetWordHashAsUINT32(std::u16string_view aString)
This helper function generates the hash code based on the algorithm specified by MS for "Password to ...
static css::uno::Sequence< sal_Int8 > GetOoxHashAsSequence(const OUString &rPassword, std::u16string_view 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....
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 > GenerateStd97Key(std::u16string_view aPassword, const css::uno::Sequence< sal_Int8 > &aDocId)
This helper function generates a byte sequence representing the key digest value used by MSCodec_Std9...
Implements the task.XInteractionRequest interface for requesting a password string for a document.
static std::vector< unsigned char > calculateHash(const unsigned char *pInput, size_t length, HashType eType)
@ APPEND
Iteration count prepended to hash iterations.
Base class for a password verifier used by the DocPasswordHelper class below.
virtual ~IDocPasswordVerifier()
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.
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.
static css::uno::Sequence< css::beans::NamedValue > CreatePackageEncryptionData(std::u16string_view aPassword)
Sequence< sal_Int8 > aSeq
#define SAL_INFO(area, stream)
css::uno::Sequence< T > concatSequences(const css::uno::Sequence< T > &rS1, const Ss &... rSn)
concat several sequences
DocPasswordRequestType
Selects which UNO document password request type to use.
DocPasswordVerifierResult
static uno::Sequence< sal_Int8 > GeneratePBKDF2Hash(std::u16string_view aPassword, const uno::Sequence< sal_Int8 > &aSalt, sal_Int32 nCount, sal_Int32 nHashLength)
css::beans::PropertyValue makePropertyValue(const OUString &rName, T &&rValue)
Creates a beans::PropertyValue easily, i.e.
OString OUStringToOString(std::u16string_view str, ConnectionSettings const *settings)
constexpr OUStringLiteral PACKAGE_ENCRYPTIONDATA_SHA256UTF8
std::unique_ptr< char[]> aBuffer