Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 3 additions & 9 deletions src/Bydlo.App/ViewModels/SettingsViewModel.Backup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,19 +133,13 @@ private async Task OpenBackup()
if (files.Count == 0) { return; }
using var file = files[0];
await using var stream = await file.OpenReadAsync();
using var buffer = new MemoryStream();
var chunk = new byte[8192];
int count;
while ((count = await stream.ReadAsync(chunk)) > 0)
{
if (buffer.Length + count > BackupArchive.MaximumFileSize) { throw new InvalidDataException(); }
buffer.Write(chunk, 0, count);
}
// One bounded buffer, handed to the session without another copy (issue #394).
var archive = await BackupArchive.ReadFileAsync(stream);
var password = BackupPassword;
var lifetime = Services.ShutdownToken;
var opened = await Task.Run(() =>
{
var session = BackupArchive.OpenImport(buffer.ToArray(), password);
var session = BackupArchive.OpenImportOwned(archive, password);
// Register on the worker too: shutdown can stop the UI dispatcher before
// this await resumes and transfers ownership to the ViewModel.
try { return (Session: session, Shutdown: lifetime.Register(session.Dispose)); }
Expand Down
130 changes: 113 additions & 17 deletions src/Bydlo.Core/Backup/BackupArchive.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Buffers;
using System.Security.Cryptography;
using System.Text.Json;
using Bydlo.Core.Models;
Expand Down Expand Up @@ -32,52 +33,147 @@ public static class BackupArchive
public const int MaximumFileSize = 32 * 1024 * 1024;
internal const int Overhead = 8 + 16 + 12 + 16;

public static BackupImportSession OpenImport(byte[] file, string password) => BackupImportSession.Open(file, password);
public static BackupImportSession OpenImport(byte[] file, string password) => BackupImportSession.Open(file, password, copy: true);

/// <summary>
/// Opens an archive read with <see cref="ReadFileAsync"/>. Ownership of <paramref name="file"/>
/// moves to the session: it is not copied again and is cleared when the session is disposed (issue #394).
/// </summary>
public static BackupImportSession OpenImportOwned(byte[] file, string password) => BackupImportSession.Open(file, password, copy: false);

/// <summary>
/// Reads an archive with a hard size limit (issue #394). A stream with a known length gets one
/// exactly sized buffer after the limit check; an unknown length grows geometrically but never
/// past <see cref="MaximumFileSize"/> + 1 bytes.
/// </summary>
public static async Task<byte[]> ReadFileAsync(Stream stream, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
long? known = null;
try { if (stream.CanSeek) { known = stream.Length - stream.Position; } }
catch (NotSupportedException) { }
if (known is { } length)
{
if (length > MaximumFileSize) { throw new InvalidDataException("Backup is too large."); }
var exact = new byte[length];
try { await stream.ReadExactlyAsync(exact, ct).ConfigureAwait(false); }
catch (EndOfStreamException ex) { throw new InvalidDataException("Backup changed while reading.", ex); }
var probe = new byte[1];
if (await stream.ReadAsync(probe, ct).ConfigureAwait(false) != 0)
{ throw new InvalidDataException("Backup changed while reading."); }
return exact;
}
var buffer = new byte[Math.Min(64 * 1024, MaximumFileSize + 1)];
var count = 0;
while (true)
{
if (count == buffer.Length)
{
if (buffer.Length > MaximumFileSize) { throw new InvalidDataException("Backup is too large."); }
Array.Resize(ref buffer, (int)Math.Min((long)buffer.Length * 2, MaximumFileSize + 1L));
}
var read = await stream.ReadAsync(buffer.AsMemory(count), ct).ConfigureAwait(false);
if (read == 0) { break; }
count += read;
if (count > MaximumFileSize) { throw new InvalidDataException("Backup is too large."); }
}
return count == buffer.Length ? buffer : buffer.AsSpan(0, count).ToArray();
}

public static byte[] Encrypt(BackupData data, string password)
{
ArgumentException.ThrowIfNullOrWhiteSpace(password);
Validate(data);
var plaintext = JsonSerializer.SerializeToUtf8Bytes(data, JsonDefaults.Options.Info<BackupData>());
// Cheap lower bound first: large raw configs fail before any buffer is allocated.
if (MinimumPayloadSize(data) > MaximumFileSize - Overhead) { throw new InvalidDataException("Backup is too large."); }
// Serialize straight after the header into one pooled buffer, enforcing the limit while
// writing, then encrypt in place (issue #394). The buffer holds plaintext until encrypted,
// so it is always cleared before it returns to the pool.
using var buffer = new BoundedBuffer(Overhead, MaximumFileSize);
byte[]? key = null;
try
{
if (plaintext.Length > MaximumFileSize - Overhead) { throw new InvalidDataException("Backup is too large."); }
var output = new byte[Overhead + plaintext.Length];
using (var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { Encoder = JsonDefaults.Options.Encoder, Indented = JsonDefaults.Options.WriteIndented }))
{
JsonSerializer.Serialize(writer, data, JsonDefaults.Options.Info<BackupData>());
}
var total = buffer.WrittenCount;
var output = buffer.Array.AsSpan(0, total);
Header.CopyTo(output);
RandomNumberGenerator.Fill(output.AsSpan(8, 16));
RandomNumberGenerator.Fill(output.AsSpan(24, 12));
key = Rfc2898DeriveBytes.Pbkdf2(password, output.AsSpan(8, 16), Iterations, HashAlgorithmName.SHA256, 32);
RandomNumberGenerator.Fill(output.Slice(8, 16));
RandomNumberGenerator.Fill(output.Slice(24, 12));
key = Rfc2898DeriveBytes.Pbkdf2(password, output.Slice(8, 16), Iterations, HashAlgorithmName.SHA256, 32);
using var aes = new AesGcm(key, 16);
aes.Encrypt(output.AsSpan(24, 12), plaintext, output.AsSpan(Overhead), output.AsSpan(36, 16), output.AsSpan(0, 24));
return output;
var body = output[Overhead..];
aes.Encrypt(output.Slice(24, 12), body, body, output.Slice(36, 16), output[..24]);
return output.ToArray();
}
finally
{
CryptographicOperations.ZeroMemory(plaintext);
if (key is not null) { CryptographicOperations.ZeroMemory(key); }
}
}

/// <summary>
/// Lower bound of the serialized size: every string value appears at least once in UTF-8.
/// Escaping and property names only add bytes, so exceeding the limit here is conclusive.
/// </summary>
internal static long MinimumPayloadSize(BackupData data)
{
long total = 0;
static long Bytes(string? value) => value is null ? 0 : System.Text.Encoding.UTF8.GetByteCount(value);
static long Dictionary(Dictionary<string, string>? values) =>
values?.Sum(entry => Bytes(entry.Key) + Bytes(entry.Value)) ?? 0;
foreach (var item in data.Profiles)
{
total += Dictionary(item.Secrets.Values) + Dictionary(item.Profile.Options)
+ Bytes(item.Profile.Name) + Bytes(item.Profile.Host);
}
foreach (var sub in data.Subscriptions)
{
total += Bytes(sub.Url) + Bytes(sub.Subscription.Name)
+ (sub.Subscription.SourceOptions?.Values.Sum(Dictionary) ?? 0);
}
return total + Dictionary(data.ToolSecrets.Values);
}

public static BackupData Decrypt(byte[] file, string password)
{
ArgumentException.ThrowIfNullOrWhiteSpace(password);
if (file.Length < Overhead || file.Length > MaximumFileSize || !file.AsSpan(0, 8).SequenceEqual(Header))
{ throw new InvalidDataException("Unsupported backup."); }
var key = Rfc2898DeriveBytes.Pbkdf2(password, file.AsSpan(8, 16), Iterations, HashAlgorithmName.SHA256, 32);
var plaintext = new byte[file.Length - Overhead];
try
{
return DecryptWith(key, file, plaintext =>
{
var data = JsonSerializer.Deserialize(plaintext.Span, JsonDefaults.Options.Info<BackupData>()) ?? throw new InvalidDataException("Invalid backup.");
Validate(data);
return data;
});
}
finally { CryptographicOperations.ZeroMemory(key); }
}

/// <summary>
/// Authenticates and decrypts into a pooled buffer that is cleared on every path. The reader only
/// sees plaintext after the tag has been verified and must not retain the span.
/// </summary>
internal static T DecryptWith<T>(byte[] key, byte[] archive, Func<ReadOnlyMemory<byte>, T> read)
{
var length = archive.Length - Overhead;
var rented = ArrayPool<byte>.Shared.Rent(Math.Max(length, 1));
var plaintext = rented.AsMemory(0, length);
try
{
using var aes = new AesGcm(key, 16);
aes.Decrypt(file.AsSpan(24, 12), file.AsSpan(Overhead), file.AsSpan(36, 16), plaintext, file.AsSpan(0, 24));
var data = JsonSerializer.Deserialize(plaintext, JsonDefaults.Options.Info<BackupData>()) ?? throw new InvalidDataException("Invalid backup.");
Validate(data);
return data;
aes.Decrypt(archive.AsSpan(24, 12), archive.AsSpan(Overhead), archive.AsSpan(36, 16), plaintext.Span, archive.AsSpan(0, 24));
return read(plaintext);
}
finally
{
CryptographicOperations.ZeroMemory(key);
CryptographicOperations.ZeroMemory(plaintext);
CryptographicOperations.ZeroMemory(plaintext.Span);
ArrayPool<byte>.Shared.Return(rented);
}
}

Expand Down
26 changes: 8 additions & 18 deletions src/Bydlo.Core/Backup/BackupImportSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,15 @@ public sealed class BackupImportSession : IDisposable

private BackupImportSession(byte[] archive, byte[] key) { _archive = archive; _key = key; }

internal static BackupImportSession Open(byte[] file, string password)
internal static BackupImportSession Open(byte[] file, string password, bool copy)
{
ArgumentException.ThrowIfNullOrWhiteSpace(password);
if (file.Length < BackupArchive.Overhead || file.Length > BackupArchive.MaximumFileSize ||
!file.AsSpan(0, 8).SequenceEqual(BackupArchive.Header))
{ throw new InvalidDataException("Unsupported backup."); }
// Never retain a caller-owned array that can change after authentication.
var archive = file.ToArray();
// Never retain a caller-owned array that can change after authentication; an owned
// array (OpenImportOwned) is already exclusive to the session.
var archive = copy ? file.ToArray() : file;
var key = Rfc2898DeriveBytes.Pbkdf2(password, archive.AsSpan(8, 16), BackupArchive.Iterations, HashAlgorithmName.SHA256, 32);
var session = new BackupImportSession(archive, key);
try
Expand Down Expand Up @@ -78,33 +79,22 @@ public BackupData Materialize()
ObjectDisposedException.ThrowIf(_disposed, this);
return ReadPlaintext(plaintext =>
{
var data = JsonSerializer.Deserialize(plaintext, JsonDefaults.Options.Info<BackupData>())
var data = JsonSerializer.Deserialize(plaintext.Span, JsonDefaults.Options.Info<BackupData>())
?? throw new InvalidDataException("Invalid backup.");
BackupArchive.Validate(data);
return data;
});
}
}

private T ReadPlaintext<T>(Func<byte[], T> read)
{
var plaintext = new byte[_archive.Length - BackupArchive.Overhead];
try
{
using var aes = new AesGcm(_key, 16);
aes.Decrypt(_archive.AsSpan(24, 12), _archive.AsSpan(BackupArchive.Overhead),
_archive.AsSpan(36, 16), plaintext, _archive.AsSpan(0, 24));
return read(plaintext);
}
finally { CryptographicOperations.ZeroMemory(plaintext); }
}
private T ReadPlaintext<T>(Func<ReadOnlyMemory<byte>, T> read) => BackupArchive.DecryptWith(_key, _archive, read);

private static BackupData ReadMetadata(byte[] plaintext)
private static BackupData ReadMetadata(ReadOnlyMemory<byte> plaintext)
{
using var sanitized = new MemoryStream();
using (var writer = new Utf8JsonWriter(sanitized))
{
var reader = new Utf8JsonReader(plaintext);
var reader = new Utf8JsonReader(plaintext.Span);
if (!reader.Read()) { throw new InvalidDataException("Invalid backup."); }
CopyValue(ref reader, writer, false, false);
if (reader.Read()) { throw new InvalidDataException("Invalid backup."); }
Expand Down
69 changes: 69 additions & 0 deletions src/Bydlo.Core/Backup/BoundedBuffer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
using System.Buffers;
using System.Security.Cryptography;

namespace Bydlo.Core.Backup;

/// <summary>
/// Pooled <see cref="IBufferWriter{T}"/> with a reserved prefix and a hard size limit (issue #394).
/// The limit is enforced while writing, so an oversized export fails before the result grows
/// without bound. Every buffer is cleared before it returns to the pool because it may hold plaintext.
/// </summary>
internal sealed class BoundedBuffer : IBufferWriter<byte>, IDisposable
{
private readonly int _limit;
private byte[] _buffer;
private int _written;

public BoundedBuffer(int prefix, int limit)
{
ArgumentOutOfRangeException.ThrowIfNegative(prefix);
ArgumentOutOfRangeException.ThrowIfLessThan(limit, prefix);
_limit = limit;
_buffer = ArrayPool<byte>.Shared.Rent(Math.Min(Math.Max(prefix + 4096, 64 * 1024), limit));
_written = prefix;
}

/// <summary>Prefix plus everything written so far.</summary>
public int WrittenCount => _written;

/// <summary>Backing array; only the first <see cref="WrittenCount"/> bytes are meaningful.</summary>
public byte[] Array => _buffer;

public void Advance(int count)
{
ArgumentOutOfRangeException.ThrowIfNegative(count);
if ((long)_written + count > _buffer.Length) { throw new InvalidOperationException("Advanced past the buffer."); }
if ((long)_written + count > _limit) { throw new InvalidDataException("Backup is too large."); }
_written += count;
}

public Memory<byte> GetMemory(int sizeHint = 0) { Ensure(sizeHint); return _buffer.AsMemory(_written); }

public Span<byte> GetSpan(int sizeHint = 0) { Ensure(sizeHint); return _buffer.AsSpan(_written); }

private void Ensure(int sizeHint)
{
if (_written >= _limit) { throw new InvalidDataException("Backup is too large."); }
var needed = (long)_written + Math.Max(sizeHint, 1);
if (needed <= _buffer.Length) { return; }
// Writers over-request for worst-case escaping, so the buffer may exceed the limit by one
// hint; Advance still rejects any data past the limit. The hint itself stays bounded.
if (needed > (long)_limit * 8) { throw new InvalidDataException("Backup is too large."); }
var size = (int)Math.Min(Math.Max(needed, (long)_buffer.Length * 2), Math.Max(needed, _limit));
var next = ArrayPool<byte>.Shared.Rent(size);
_buffer.AsSpan(0, _written).CopyTo(next);
CryptographicOperations.ZeroMemory(_buffer);
ArrayPool<byte>.Shared.Return(_buffer);
_buffer = next;
}

public void Dispose()
{
if (_buffer.Length == 0) { return; }
// Clear the whole array: a writer may have produced bytes it never advanced over.
CryptographicOperations.ZeroMemory(_buffer);
ArrayPool<byte>.Shared.Return(_buffer);
_buffer = [];
_written = 0;
}
}
Loading
Loading