diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f0827939c0..c6428aa58b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog + +## Unreleased + +### Fixes + +- Crash when reading corrupted envelope (#4297) + ## 8.35.0 ### Features diff --git a/Sources/Sentry/SentrySerialization.m b/Sources/Sentry/SentrySerialization.m index 521992499e1..507490bf0d0 100644 --- a/Sources/Sentry/SentrySerialization.m +++ b/Sources/Sentry/SentrySerialization.m @@ -208,6 +208,14 @@ + (SentryEnvelope *_Nullable)envelopeWithData:(NSData *)data if (endOfEnvelope == i) { i++; // 0 byte attachment } + + if (bodyLength > 0 && data.length < (i + 1 + bodyLength)) { + SENTRY_LOG_ERROR(@"Envelope is corrupted or has invalid data. Trying to read %li " + @"bytes by skiping %li from a buffer of %li bytes.", + (unsigned long)data.length, (unsigned long)bodyLength, (long)(i + 1)); + return nil; + } + NSData *itemBody = [data subdataWithRange:NSMakeRange(i + 1, bodyLength)]; SentryEnvelopeItem *envelopeItem = [[SentryEnvelopeItem alloc] initWithHeader:itemHeader data:itemBody]; diff --git a/Tests/SentryTests/Helper/SentrySerializationTests.swift b/Tests/SentryTests/Helper/SentrySerializationTests.swift index b3d5fb5fec7..4105c9540bd 100644 --- a/Tests/SentryTests/Helper/SentrySerializationTests.swift +++ b/Tests/SentryTests/Helper/SentrySerializationTests.swift @@ -267,6 +267,17 @@ class SentrySerializationTests: XCTestCase { XCTAssertNil(actual) } + func testReturnNilForCorruptedEnvelope() throws { + let envelope = SentryEnvelope(event: Event(error: NSError(domain: "test", code: -1, userInfo: nil))) + let data = try XCTUnwrap(SentrySerialization.data(with: envelope)) + + let corruptedData = data[0.. Data { var serializedEnvelope: Data = Data() do {