File: DecryptingInputStream_impl.h

package info (click to toggle)
firefox 143.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,617,328 kB
  • sloc: cpp: 7,478,492; javascript: 6,417,157; ansic: 3,720,058; python: 1,396,372; xml: 627,523; asm: 438,677; java: 186,156; sh: 63,477; makefile: 19,171; objc: 13,059; perl: 12,983; yacc: 4,583; cs: 3,846; pascal: 3,405; lex: 1,720; ruby: 1,003; exp: 762; php: 436; lisp: 258; awk: 247; sql: 66; sed: 53; csh: 10
file content (569 lines) | stat: -rw-r--r-- 15,981 bytes parent folder | download | duplicates (4)
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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/. */

#ifndef mozilla_dom_quota_DecryptingInputStream_impl_h
#define mozilla_dom_quota_DecryptingInputStream_impl_h

#include <algorithm>
#include <cstdio>
#include <type_traits>
#include <utility>

#include "CipherStrategy.h"
#include "DecryptingInputStream.h"
#include "mozilla/Assertions.h"
#include "mozilla/RefPtr.h"
#include "mozilla/Result.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/Span.h"
#include "mozilla/fallible.h"
#include "mozilla/ipc/InputStreamUtils.h"
#include "nsDebug.h"
#include "nsError.h"
#include "nsFileStreams.h"
#include "nsID.h"
#include "nsIFileStreams.h"

namespace mozilla::dom::quota {

template <typename CipherStrategy>
DecryptingInputStream<CipherStrategy>::DecryptingInputStream(
    MovingNotNull<nsCOMPtr<nsIInputStream>> aBaseStream, size_t aBlockSize,
    typename CipherStrategy::KeyType aKey)
    : DecryptingInputStreamBase(std::move(aBaseStream), aBlockSize),
      mKey(aKey) {
  // XXX Move this to a fallible init function.
  MOZ_ALWAYS_SUCCEEDS(mCipherStrategy.Init(CipherMode::Decrypt,
                                           CipherStrategy::SerializeKey(aKey)));

  // We used to assert the underlying stream was blocking in DEBUG builds as a
  // proxy for providing synchronous read access (we can't handle AsyncWait),
  // but IsNonBlocking is a bad proxy for this since classes like
  // nsStringInputStream provide sync read access, it just is known to never
  // block because the data is always available.
}

template <typename CipherStrategy>
DecryptingInputStream<CipherStrategy>::~DecryptingInputStream() {
  Close();
}

template <typename CipherStrategy>
DecryptingInputStream<CipherStrategy>::DecryptingInputStream()
    : DecryptingInputStreamBase{} {}

template <typename CipherStrategy>
NS_IMETHODIMP DecryptingInputStream<CipherStrategy>::Close() {
  if (!mBaseStream) {
    return NS_OK;
  }

  (*mBaseStream)->Close();
  mBaseStream.destroy();

  mPlainBuffer.Clear();
  mEncryptedBlock.reset();

  return NS_OK;
}

template <typename CipherStrategy>
NS_IMETHODIMP DecryptingInputStream<CipherStrategy>::Available(
    uint64_t* aLengthOut) {
  if (!mBaseStream) {
    return NS_BASE_STREAM_CLOSED;
  }

  int64_t oldPos, endPos;
  nsresult rv = Tell(&oldPos);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = Seek(SEEK_END, 0);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = Tell(&endPos);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = Seek(SEEK_SET, oldPos);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  *aLengthOut = endPos - oldPos;
  return NS_OK;
}

template <typename CipherStrategy>
NS_IMETHODIMP DecryptingInputStream<CipherStrategy>::StreamStatus() {
  return mBaseStream ? NS_OK : NS_BASE_STREAM_CLOSED;
}

template <typename CipherStrategy>
nsresult DecryptingInputStream<CipherStrategy>::BaseStreamStatus() {
  return mBaseStream ? (*mBaseStream)->StreamStatus() : NS_BASE_STREAM_CLOSED;
}

template <typename CipherStrategy>
NS_IMETHODIMP DecryptingInputStream<CipherStrategy>::ReadSegments(
    nsWriteSegmentFun aWriter, void* aClosure, uint32_t aCount,
    uint32_t* aBytesReadOut) {
  *aBytesReadOut = 0;

  if (!mBaseStream) {
    return NS_BASE_STREAM_CLOSED;
  }

  nsresult rv;

  // Do not try to use the base stream's ReadSegments here.  Its very
  // unlikely we will get a single buffer that contains all of the encrypted
  // data and therefore would have to copy into our own buffer anyways.
  // Instead, focus on making efficient use of the Read() interface.

  while (aCount > 0) {
    // We have some decrypted data in our buffer.  Provide it to the callers
    // writer function.
    if (mNextByte < mPlainBytes) {
      MOZ_ASSERT(!mPlainBuffer.IsEmpty());
      uint32_t remaining = PlainLength();
      uint32_t numToWrite = std::min(aCount, remaining);
      uint32_t numWritten;
      rv = aWriter(this, aClosure,
                   reinterpret_cast<const char*>(&mPlainBuffer[mNextByte]),
                   *aBytesReadOut, numToWrite, &numWritten);

      // As defined in nsIInputputStream.idl, do not pass writer func errors.
      if (NS_FAILED(rv)) {
        return NS_OK;
      }

      // End-of-file
      if (numWritten == 0) {
        return NS_OK;
      }

      *aBytesReadOut += numWritten;
      mNextByte += numWritten;
      MOZ_ASSERT(mNextByte <= mPlainBytes);

      aCount -= numWritten;

      continue;
    }

    // Otherwise decrypt the next chunk and loop.  Any resulting data will set
    // mPlainBytes and mNextByte which we check at the top of the loop.
    uint32_t bytesRead;
    rv = ParseNextChunk(false /* aCheckAvailableBytes */, &bytesRead);
    if (NS_FAILED(rv)) {
      return rv;
    }

    // If we couldn't read anything, then this is eof.
    if (bytesRead == 0) {
      return NS_OK;
    }

    mPlainBytes = bytesRead;
    mNextByte = 0;
  }

  return NS_OK;
}

template <typename CipherStrategy>
nsresult DecryptingInputStream<CipherStrategy>::ParseNextChunk(
    bool aCheckAvailableBytes, uint32_t* const aBytesReadOut) {
  *aBytesReadOut = 0;

  if (!EnsureBuffers()) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  // Read the data to our internal encrypted buffer.
  auto wholeBlock = mEncryptedBlock->MutableWholeBlock();
  nsresult rv =
      ReadAll(AsWritableChars(wholeBlock).Elements(), wholeBlock.Length(),
              wholeBlock.Length(), aCheckAvailableBytes, aBytesReadOut);
  if (NS_WARN_IF(NS_FAILED(rv)) || *aBytesReadOut == 0) {
    return rv;
  }

  // XXX Do we need to know the actual decrypted size?
  rv = mCipherStrategy.Cipher(mEncryptedBlock->MutableCipherPrefix(),
                              mEncryptedBlock->Payload(),
                              AsWritableBytes(Span{mPlainBuffer}));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  *aBytesReadOut = mEncryptedBlock->ActualPayloadLength();

  return NS_OK;
}

template <typename CipherStrategy>
nsresult DecryptingInputStream<CipherStrategy>::ReadAll(
    char* aBuf, uint32_t aCount, uint32_t aMinValidCount,
    bool aCheckAvailableBytes, uint32_t* aBytesReadOut) {
  MOZ_ASSERT(aCount >= aMinValidCount);
  MOZ_ASSERT(mBaseStream);

  nsresult rv = NS_OK;
  *aBytesReadOut = 0;

  uint32_t offset = 0;
  while (aCount > 0) {
    Maybe<uint64_t> availableBytes;
    if (aCheckAvailableBytes) {
      uint64_t available;
      rv = (*mBaseStream)->Available(&available);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        if (rv == NS_BASE_STREAM_CLOSED) {
          rv = NS_OK;
        }
        break;
      }

      if (available == 0) {
        break;
      }

      availableBytes = Some(available);
    }

    uint32_t bytesRead = 0;
    rv = (*mBaseStream)->Read(aBuf + offset, aCount, &bytesRead);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      break;
    }

    // EOF, but don't immediately return.  We need to validate min read bytes
    // below.
    if (bytesRead == 0) {
      break;
    }

    MOZ_DIAGNOSTIC_ASSERT(!availableBytes || bytesRead <= *availableBytes);

    *aBytesReadOut += bytesRead;
    offset += bytesRead;
    aCount -= bytesRead;
  }

  // Reading zero bytes is not an error.  Its the expected EOF condition.
  // Only compare to the minimum valid count if we read at least one byte.
  if (*aBytesReadOut != 0 && *aBytesReadOut < aMinValidCount) {
    return NS_ERROR_CORRUPTED_CONTENT;
  }

  return rv;
}

template <typename CipherStrategy>
bool DecryptingInputStream<CipherStrategy>::EnsureBuffers() {
  // Lazily create our two buffers so we can report OOM during stream
  // operation.  These allocations only happens once.  The buffers are reused
  // until the stream is closed.
  if (!mEncryptedBlock) {
    // XXX Do we need to do this fallible (as the comment above suggests)?
    mEncryptedBlock.emplace(*mBlockSize);

    MOZ_ASSERT(mPlainBuffer.IsEmpty());
    if (NS_WARN_IF(!mPlainBuffer.SetLength(mEncryptedBlock->MaxPayloadLength(),
                                           fallible))) {
      return false;
    }

    // Make sure we seek our stream to its start before we do anything.  This is
    // primarily intended to deal with the case of IPC serialization, but this
    // is reasonable in all cases.
    (*mBaseSeekableStream)->Seek(NS_SEEK_SET, 0);
  }

  return true;
}

template <typename CipherStrategy>
nsresult DecryptingInputStream<CipherStrategy>::EnsureDecryptedStreamSize() {
  if (mDecryptedStreamSize) {
    return NS_OK;
  }

  auto decryptedStreamSizeOrErr = [this]() -> Result<int64_t, nsresult> {
    nsresult rv = (*mBaseSeekableStream)->Seek(NS_SEEK_SET, 0);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return Err(rv);
    }

    uint64_t baseStreamSize;
    rv = (*mBaseStream)->Available(&baseStreamSize);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return Err(rv);
    }

    if (!baseStreamSize) {
      return 0;
    }

    rv = (*mBaseSeekableStream)
             ->Seek(NS_SEEK_END, -static_cast<int64_t>(*mBlockSize));
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return Err(rv);
    }

    uint32_t bytesRead;
    rv = ParseNextChunk(true /* aCheckAvailableBytes */, &bytesRead);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return Err(rv);
    }
    MOZ_ASSERT(bytesRead);

    mPlainBytes = bytesRead;

    mNextByte = bytesRead;

    int64_t current;
    rv = Tell(&current);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return Err(rv);
    }

    return current;
  }();

  if (decryptedStreamSizeOrErr.isErr()) {
    return decryptedStreamSizeOrErr.unwrapErr();
  }

  mDecryptedStreamSize.init(decryptedStreamSizeOrErr.inspect());

  return NS_OK;
}

template <typename CipherStrategy>
NS_IMETHODIMP DecryptingInputStream<CipherStrategy>::Tell(
    int64_t* const aRetval) {
  MOZ_ASSERT(aRetval);

  if (!mBaseStream) {
    return NS_BASE_STREAM_CLOSED;
  }

  if (!EnsureBuffers()) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  int64_t basePosition;
  nsresult rv = (*mBaseSeekableStream)->Tell(&basePosition);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  if (basePosition == 0) {
    *aRetval = 0;
    return NS_OK;
  }

  MOZ_ASSERT(0 == basePosition % *mBlockSize);

  const auto fullBlocks = basePosition / *mBlockSize;
  MOZ_ASSERT(fullBlocks);

  *aRetval = (fullBlocks - 1) * mEncryptedBlock->MaxPayloadLength() + mNextByte;
  return NS_OK;
}

template <typename CipherStrategy>
NS_IMETHODIMP DecryptingInputStream<CipherStrategy>::Seek(const int32_t aWhence,
                                                          int64_t aOffset) {
  if (!mBaseStream) {
    return NS_BASE_STREAM_CLOSED;
  }

  if (!EnsureBuffers()) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  int64_t baseCurrent;
  nsresult rv = (*mBaseSeekableStream)->Tell(&baseCurrent);
  if (rv == NS_BASE_STREAM_CLOSED) {
    // In the case our underlying stream is CLOSE_ON_EOF and REOPEN_ON_REWIND,
    // as is the case for IDB Files/Blobs in the parent process, then this call
    // to Tell can fail with NS_BASE_STREAM_CLOSED.
    //
    // Requesting any seek in this condition will re-open the file if the flags
    // are set, so try that (but will fail if they are not set).
    rv = (*mBaseSeekableStream)->Seek(NS_SEEK_CUR, 0);
    // If that succeeded, perform the tell call again.
    if (NS_SUCCEEDED(rv)) {
      rv = (*mBaseSeekableStream)->Tell(&baseCurrent);
    }
  }
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return Err(rv);
  }

  // Can't call this just in NS_SEEK_CUR case, because ensuring the decrypted
  // size below may change the current position.
  int64_t current;
  rv = Tell(&current);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  // If there's a failure we need to restore any previous state.
  auto autoRestorePreviousState =
      MakeScopeExit([baseSeekableStream = *mBaseSeekableStream,
                     savedBaseCurrent = baseCurrent,
                     savedPlainBytes = mPlainBytes, savedNextByte = mNextByte,
                     &plainBytes = mPlainBytes, &nextByte = mNextByte] {
        nsresult rv = baseSeekableStream->Seek(NS_SEEK_SET, savedBaseCurrent);
        Unused << NS_WARN_IF(NS_FAILED(rv));
        plainBytes = savedPlainBytes;
        nextByte = savedNextByte;
      });

  rv = EnsureDecryptedStreamSize();
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  int64_t baseBlocksOffset;
  int64_t nextByteOffset;
  switch (aWhence) {
    case NS_SEEK_CUR:
      // XXX Simplify this without using Tell.
      aOffset += current;
      break;

    case NS_SEEK_SET:
      break;

    case NS_SEEK_END:
      // XXX Simplify this without using Seek/Tell.
      aOffset += *mDecryptedStreamSize;
      break;

    default:
      return NS_ERROR_ILLEGAL_VALUE;
  }

  if (aOffset < 0 || aOffset > *mDecryptedStreamSize) {
    return NS_ERROR_ILLEGAL_VALUE;
  }

  baseBlocksOffset = aOffset / mEncryptedBlock->MaxPayloadLength();
  nextByteOffset = aOffset % mEncryptedBlock->MaxPayloadLength();

  // XXX If we remain in the same block as before, we can skip this.
  rv =
      (*mBaseSeekableStream)->Seek(NS_SEEK_SET, baseBlocksOffset * *mBlockSize);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  uint32_t readBytes;
  rv = ParseNextChunk(true /* aCheckAvailableBytes */, &readBytes);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  if (readBytes == 0 && baseBlocksOffset != 0) {
    mPlainBytes = mEncryptedBlock->MaxPayloadLength();
    mNextByte = mEncryptedBlock->MaxPayloadLength();
  } else {
    mPlainBytes = readBytes;
    mNextByte = nextByteOffset;
  }

  autoRestorePreviousState.release();

  return NS_OK;
}

template <typename CipherStrategy>
NS_IMETHODIMP DecryptingInputStream<CipherStrategy>::Clone(
    nsIInputStream** _retval) {
  if (!mBaseStream) {
    return NS_BASE_STREAM_CLOSED;
  }

  if (!(*mBaseCloneableInputStream)->GetCloneable()) {
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIInputStream> clonedStream;
  nsresult rv =
      (*mBaseCloneableInputStream)->Clone(getter_AddRefs(clonedStream));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  *_retval = MakeAndAddRef<DecryptingInputStream>(
                 WrapNotNull(std::move(clonedStream)), *mBlockSize, *mKey)
                 .take();

  return NS_OK;
}

template <typename CipherStrategy>
void DecryptingInputStream<CipherStrategy>::Serialize(
    mozilla::ipc::InputStreamParams& aParams, uint32_t aMaxSize,
    uint32_t* aSizeUsed) {
  MOZ_ASSERT(mBaseStream);
  MOZ_ASSERT(mBaseIPCSerializableInputStream);

  mozilla::ipc::EncryptedFileInputStreamParams encryptedFileInputStreamParams;
  mozilla::ipc::InputStreamHelper::SerializeInputStream(
      *mBaseStream, encryptedFileInputStreamParams.inputStreamParams(),
      aMaxSize, aSizeUsed);

  encryptedFileInputStreamParams.key().AppendElements(
      mCipherStrategy.SerializeKey(*mKey));
  encryptedFileInputStreamParams.blockSize() = *mBlockSize;

  aParams = std::move(encryptedFileInputStreamParams);
}

template <typename CipherStrategy>
bool DecryptingInputStream<CipherStrategy>::Deserialize(
    const mozilla::ipc::InputStreamParams& aParams) {
  const auto& params = aParams.get_EncryptedFileInputStreamParams();

  nsCOMPtr<nsIInputStream> stream =
      mozilla::ipc::InputStreamHelper::DeserializeInputStream(
          params.inputStreamParams());
  if (NS_WARN_IF(!stream)) {
    return false;
  }

  Init(WrapNotNull<nsCOMPtr<nsIInputStream>>(std::move(stream)),
       params.blockSize());

  auto key = mCipherStrategy.DeserializeKey(params.key());
  if (NS_WARN_IF(!key)) {
    return false;
  }

  mKey.init(*key);
  if (NS_WARN_IF(
          NS_FAILED(mCipherStrategy.Init(CipherMode::Decrypt, params.key())))) {
    return false;
  }

  return true;
}

}  // namespace mozilla::dom::quota

#endif