summaryrefslogtreecommitdiff
path: root/oox/source/crypto/IRMEngine.cxx
blob: 6f531b2a1c140772babfc73ef747e2f716180b03 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

#include <oox/crypto/IRMEngine.hxx>

#include <oox/helper/binaryinputstream.hxx>
#include <oox/helper/binaryoutputstream.hxx>

#include <sax/tools/converter.hxx>

#include <comphelper/hash.hxx>
#include <comphelper/docpasswordhelper.hxx>
#include <comphelper/random.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/base64.hxx>
#include <comphelper/sequence.hxx>
#include <comphelper/sequenceashashmap.hxx>

#include <filter/msfilter/mscodec.hxx>
#include <tools/stream.hxx>
#include <tools/XmlWriter.hxx>

#include <com/sun/star/io/XSeekable.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/xml/sax/XFastParser.hpp>
#include <com/sun/star/xml/sax/XFastTokenHandler.hpp>
#include <com/sun/star/xml/sax/FastParser.hpp>
#include <com/sun/star/xml/sax/FastToken.hpp>

#include <msipc.h>

using namespace css;
using namespace css::beans;
using namespace css::io;
using namespace css::lang;
using namespace css::uno;
using namespace css::xml::sax;
using namespace css::xml;

namespace oox
{
namespace core
{
IRMEngine::IRMEngine() {}

bool IRMEngine::checkDataIntegrity() { return true; }

bool IRMEngine::decrypt(BinaryXInputStream& aInputStream, BinaryXOutputStream& aOutputStream)
{
    aInputStream.readInt64(); // Skip stream size

    HRESULT hr = IpcInitialize();
    if (FAILED(hr) && hr != HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED))
    {
        // ERROR_ALREADY_INITIALIZED not an error
        // TODO: some reaction?
    }

    // Get decryption key
    IPC_BUFFER licenseBuffer;
    IPC_KEY_HANDLE key;
    licenseBuffer.pvBuffer = (void*)mInfo.license.getStr();
    licenseBuffer.cbBuffer = mInfo.license.getLength();
    hr = IpcGetKey(&licenseBuffer, 0, NULL, NULL, &key);
    if (FAILED(hr))
    {
        // TODO: some reaction?
    }

    // Read rights
    BOOL value;
    hr = IpcAccessCheck(key, IPC_GENERIC_READ, &value);
    if (FAILED(hr))
    {
        // TODO: some reaction?
    }
    mInfo.bCanRead = value;

    // Get size of decrypt block
    DWORD* blockSize;
    hr = IpcGetKeyProperty(key, IPC_KI_BLOCK_SIZE, nullptr, (LPVOID*)&blockSize);
    if (FAILED(hr))
    {
        // TODO: some reaction?
    }

    char* pEncryptedBuffer = new char[*blockSize];
    char* pDecryptedBuffer = new char[*blockSize];
    int blockNo = 0;
    bool lastBlock = false;

    do
    {
        sal_uInt32 readBytes = aInputStream.readArray(pEncryptedBuffer, *blockSize);
        lastBlock = readBytes != *blockSize;
        DWORD bytes = 0;
        hr = IpcDecrypt(key, blockNo, lastBlock, (PBYTE)pEncryptedBuffer, *blockSize,
                        (PBYTE)pDecryptedBuffer, *blockSize, &bytes);

        if (FAILED(hr))
        {
            // TODO: some reaction?
        }

        aOutputStream.writeArray(pDecryptedBuffer, bytes);

        blockNo++;
    } while (!lastBlock);

    delete[] pEncryptedBuffer;
    delete[] pDecryptedBuffer;

    return true;
}

void IRMEngine::createEncryptionData(comphelper::SequenceAsHashMap& aEncryptionData,
                                     const OUString rPassword)
{
    aEncryptionData["OOXPassword"] <<= rPassword;

    css::uno::Sequence<sal_uInt8> seq;
    seq.realloc(mInfo.license.getLength());
    memcpy(seq.getArray(), mInfo.license.getStr(), mInfo.license.getLength());

    aEncryptionData["license"] <<= seq;
}

bool IRMEngine::readEncryptionInfo(oox::ole::OleStorage& rOleStorage)
{
    // Read TransformInfo storage for IRM ECMA documents (MS-OFFCRYPTO 2.2.4)
    uno::Reference<io::XInputStream> xTransformInfoStream = rOleStorage.openInputStream(
        "\006DataSpaces/TransformInfo/DRMEncryptedTransform/\006Primary");
    SAL_WARN_IF(!xTransformInfoStream.is(), "oox", "TransormInfo stream is missing!");
    BinaryXInputStream aBinaryStream(xTransformInfoStream, true);

    // MS-OFFCRYPTO 2.1.8: TransformInfoHeader
    aBinaryStream.readuInt32(); // TransformLength
    aBinaryStream.readuInt32(); // TransformType
    // TransformId
    sal_uInt32 aStringLength = aBinaryStream.readuInt32();
    OUString sTransformId = aBinaryStream.readUnicodeArray(aStringLength / 2);
    aBinaryStream.skip((4 - (aStringLength & 3)) & 3); // Skip padding

    // TransformName
    aStringLength = aBinaryStream.readuInt32();
    OUString sTransformName = aBinaryStream.readUnicodeArray(aStringLength / 2);
    aBinaryStream.skip((4 - (aStringLength & 3)) & 3); // Skip padding

    aBinaryStream.readuInt32(); // ReaderVersion
    aBinaryStream.readuInt32(); // UpdaterVersion
    aBinaryStream.readuInt32(); // WriterVersion

    // MS-OFFCRYPTO 2.2.5: ExtensibilityHeader
    aBinaryStream.readuInt32(); // ExtensibilityHeader

    // MS-OFFCRYPTO 2.2.6: XrMLLicense
    aStringLength = aBinaryStream.readuInt32();
    mInfo.license = aBinaryStream.readCharArray(aStringLength);

    if (mInfo.license.getLength()
        && static_cast<sal_uChar>(mInfo.license[0]) != 0x0ef) // BOM is missing?
    {
        mInfo.license = "\x0ef\x0bb\x0bf" + mInfo.license;
    }

    // TODO: CHECK info data

    return true;
}

bool IRMEngine::setupEncryption(css::uno::Sequence<css::beans::NamedValue>& rMediaEncData)
{
    for (int i = 0; i < rMediaEncData.getLength(); i++)
    {
        if (rMediaEncData[i].Name == "license")
        {
            css::uno::Sequence<sal_uInt8> seq;
            rMediaEncData[i].Value >>= seq;
            mInfo.license = OString(reinterpret_cast<sal_Char*>(seq.getArray()), seq.getLength());
        }
    }

    return true;
}

void IRMEngine::writeEncryptionInfo(oox::ole::OleStorage& rOleStorage)
{
    // Write 0x6DataSpaces/DataSpaceMap
    Reference<XOutputStream> xDataSpaceMap(
        rOleStorage.openOutputStream("\006DataSpaces/DataSpaceMap"), UNO_SET_THROW);
    BinaryXOutputStream aDataSpaceMapStream(xDataSpaceMap, false);

    aDataSpaceMapStream.WriteInt32(8); // Header length
    aDataSpaceMapStream.WriteInt32(1); // Entries count

    // DataSpaceMapEntry (MS-OFFCRYPTO 2.1.6.1)
    OUString sDataSpaceName("DRMEncryptedDataSpace");
    OUString sReferenceComponent("EncryptedPackage");

    aDataSpaceMapStream.WriteInt32(0x58); // Length
    aDataSpaceMapStream.WriteInt32(1); // References count
    aDataSpaceMapStream.WriteInt32(0); // References component type

    aDataSpaceMapStream.WriteInt32(sReferenceComponent.getLength() * 2);
    aDataSpaceMapStream.writeUnicodeArray(sReferenceComponent);
    while (aDataSpaceMapStream.tell() % 4) // Padding
    {
        aDataSpaceMapStream.writeValue<sal_Char>(0);
    }

    aDataSpaceMapStream.WriteInt32(sDataSpaceName.getLength() * 2);
    aDataSpaceMapStream.writeUnicodeArray(sDataSpaceName);
    while (aDataSpaceMapStream.tell() % 4) // Padding
    {
        aDataSpaceMapStream.writeValue<sal_Char>(0);
    }

    // Write length
    sal_uInt32 nLength = aDataSpaceMapStream.tell() - 8;
    aDataSpaceMapStream.seek(8);
    aDataSpaceMapStream.WriteInt32(nLength);

    aDataSpaceMapStream.close();
    xDataSpaceMap->flush();
    xDataSpaceMap->closeOutput();

    // Write 0x6DataSpaces/Version
    Reference<XOutputStream> xVersion(rOleStorage.openOutputStream("\006DataSpaces/Version"),
                                      UNO_SET_THROW);
    BinaryXOutputStream aVersionStream(xVersion, false);

    OUString sFeatureIdentifier("Microsoft.Container.DataSpaces");
    aVersionStream.WriteInt32(sFeatureIdentifier.getLength() * 2);
    aVersionStream.writeUnicodeArray(sFeatureIdentifier);
    while (aVersionStream.tell() % 4) // Padding
    {
        aVersionStream.writeValue<sal_Char>(0);
    }

    aVersionStream.WriteInt32(1); // Reader version
    aVersionStream.WriteInt32(1); // Updater version
    aVersionStream.WriteInt32(1); // Writer version

    aVersionStream.close();
    xVersion->flush();
    xVersion->closeOutput();

    // Write 0x6DataSpaces/DataSpaceInfo/[dataspacename]
    OUString sStreamName = "\006DataSpaces/DataSpaceInfo/" + sDataSpaceName;
    Reference<XOutputStream> xDataSpaceInfo(rOleStorage.openOutputStream(sStreamName),
                                            UNO_SET_THROW);
    BinaryXOutputStream aDataSpaceInfoStream(xDataSpaceInfo, false);

    aDataSpaceInfoStream.WriteInt32(8); // Header length
    aDataSpaceInfoStream.WriteInt32(1); // Entries count

    OUString sTransformName("DRMEncryptedTransform");
    aDataSpaceInfoStream.WriteInt32(sTransformName.getLength() * 2);
    aDataSpaceInfoStream.writeUnicodeArray(sTransformName);
    while (aDataSpaceInfoStream.tell() % 4) // Padding
    {
        aDataSpaceInfoStream.writeValue<sal_Char>(0);
    }

    aDataSpaceInfoStream.close();
    xDataSpaceInfo->flush();
    xDataSpaceInfo->closeOutput();

    // Write 0x6DataSpaces/TransformInfo/[transformname]
    sStreamName = "\006DataSpaces/TransformInfo/" + sTransformName + "/\006Primary";
    Reference<XOutputStream> xTransformInfo(rOleStorage.openOutputStream(sStreamName),
                                            UNO_SET_THROW);
    BinaryXOutputStream aTransformInfoStream(xTransformInfo, false);

    // MS-OFFCRYPTO 2.1.8: TransformInfoHeader
    aTransformInfoStream.WriteInt32(0); // TransformLength, will be written later
    aTransformInfoStream.WriteInt32(1); // TransformType

    // TransformId
    OUString sTransformId("{C73DFACD-061F-43B0-8B64-0C620D2A8B50}");
    aTransformInfoStream.WriteInt32(sTransformId.getLength() * 2);
    aTransformInfoStream.writeUnicodeArray(sTransformId);
    while (aTransformInfoStream.tell() % 4) // Padding
    {
        aTransformInfoStream.writeValue<sal_Char>(0);
    }

    // Calculate length and write it into beginning
    nLength = aTransformInfoStream.tell();
    aTransformInfoStream.seek(0);
    aTransformInfoStream.WriteInt32(nLength);
    aTransformInfoStream.seek(nLength);

    // TransformName
    OUString sTransformInfoName("Microsoft.Metadata.DRMTransform");
    aTransformInfoStream.WriteInt32(sTransformInfoName.getLength() * 2);
    aTransformInfoStream.writeUnicodeArray(sTransformInfoName);
    while (aTransformInfoStream.tell() % 4) // Padding
    {
        aTransformInfoStream.writeValue<sal_Char>(0);
    }

    aTransformInfoStream.WriteInt32(1); // ReaderVersion
    aTransformInfoStream.WriteInt32(1); // UpdateVersion
    aTransformInfoStream.WriteInt32(1); // WriterVersion

    aTransformInfoStream.WriteInt32(4); // Extensibility Header

    aTransformInfoStream.WriteInt32(mInfo.license.getLength() - 3); // LicenseLength
    aTransformInfoStream.writeArray<sal_Char>(mInfo.license.getStr() + 3,
                                              mInfo.license.getLength() - 3);
    aTransformInfoStream.writeValue<sal_Char>(0);

    aTransformInfoStream.close();
    xTransformInfo->flush();
    xTransformInfo->closeOutput();
}

void IRMEngine::encrypt(css::uno::Reference<css::io::XInputStream>& rxInputStream,
                        css::uno::Reference<css::io::XOutputStream>& rxOutputStream,
                        sal_uInt32 /*nSize*/)
{
    HRESULT hr = IpcInitialize();

    if (FAILED(hr) && hr != HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED))
    {
        // ERROR_ALREADY_INITIALIZED not an error
        // TODO: some reaction?
    }

    BinaryXInputStream aInputStream(rxInputStream, false);
    BinaryXOutputStream aOutputStream(rxOutputStream, false);
    aOutputStream.WriteInt64(aInputStream.size()); // Stream size

    // Get decryption key
    IPC_BUFFER licenseBuffer;
    IPC_KEY_HANDLE key;
    licenseBuffer.pvBuffer = (void*)mInfo.license.getStr();
    licenseBuffer.cbBuffer = mInfo.license.getLength();
    hr = IpcGetKey(&licenseBuffer, 0, NULL, NULL, &key);
    if (FAILED(hr))
    {
        // TODO: some reaction?
    }

    // Get size of encrypt block
    DWORD* blockSize;
    hr = IpcGetKeyProperty(key, IPC_KI_BLOCK_SIZE, nullptr, (LPVOID*)&blockSize);
    if (FAILED(hr))
    {
        // TODO: some reaction?
    }

    char* pEncryptedBuffer = new char[*blockSize];
    char* pDecryptedBuffer = new char[*blockSize];
    int blockNo = 0;
    bool lastBlock = false;

    do
    {
        sal_uInt32 readBytes = aInputStream.readArray(pDecryptedBuffer, *blockSize);
        lastBlock = readBytes != *blockSize;
        DWORD bytes = 0;
        hr = IpcEncrypt(key, blockNo, lastBlock, (PBYTE)pDecryptedBuffer, *blockSize,
                        (PBYTE)pEncryptedBuffer, *blockSize, &bytes);

        if (FAILED(hr))
        {
            // TODO: some reaction?
        }

        aOutputStream.writeArray(pEncryptedBuffer, bytes);

        blockNo++;
    } while (!lastBlock);

    delete[] pEncryptedBuffer;
    delete[] pDecryptedBuffer;
}

bool IRMEngine::generateEncryptionKey(const OUString& /*password*/) { return true; }

} // namespace core
} // namespace oox

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */