Skip to content

Commit 556fc72

Browse files
Add validation and better error handling for length prefixes
- Added validation to prevent excessive memory allocation from corrupted length values - Improved exception handling in full scan to distinguish EOF from corruption - Added bounds checking for record lengths Co-authored-by: MPCoreDeveloper <37024522+MPCoreDeveloper@users.noreply.github.com>
1 parent 4e3738b commit 556fc72

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

SharpCoreDB/DataStructures/Table.cs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,12 @@ private List<Dictionary<string, object>> SelectInternal(string? where, string? o
198198
// Read the length prefix that was written by AppendBytes
199199
int recordLength = reader.ReadInt32();
200200

201+
// Validate length to prevent issues with corrupted data
202+
if (recordLength < 0 || recordLength > data.Length)
203+
{
204+
break; // Corrupted record, stop scanning
205+
}
206+
201207
// Read the record data
202208
var recordData = reader.ReadBytes(recordLength);
203209

@@ -215,9 +221,14 @@ private List<Dictionary<string, object>> SelectInternal(string? where, string? o
215221
if (valid && (string.IsNullOrEmpty(where) || EvaluateWhere(row, where)))
216222
results.Add(row);
217223
}
218-
catch
224+
catch (EndOfStreamException)
225+
{
226+
// Reached end of file
227+
break;
228+
}
229+
catch (Exception)
219230
{
220-
// End of file or corrupted record
231+
// Corrupted record, skip and continue
221232
break;
222233
}
223234
}

SharpCoreDB/Services/Storage.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,13 @@ public long AppendBytes(string path, byte[] data)
204204
// Read the length prefix that was written by AppendBytes
205205
int length = reader.ReadInt32();
206206

207-
// Read the actual data
207+
// Validate length to prevent excessive memory allocation
208+
if (length < 0 || length > maxLength * 10) // Allow some buffer but prevent abuse
209+
{
210+
throw new InvalidDataException($"Invalid record length: {length}");
211+
}
212+
213+
// Read the actual data (maxLength is for the data portion, not including prefix)
208214
int bytesToRead = Math.Min(length, maxLength);
209215
var buffer = reader.ReadBytes(bytesToRead);
210216

0 commit comments

Comments
 (0)