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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ once we reach 1.0.
a crash mid-write can no longer leave a corrupt `trust.json` behind. Joining another device's
incident no longer has an "accept any certificate" fallback — a trust store is required, so a
join is always TLS-pinned. (#286)
- Android: the `FileProvider` now grants access to only its `shared/` and `lagebuch/`
subdirectories, not the whole cache directory — `import.json`, picked attachments and the
synced-attachment cache are no longer reachable through a shared or opened URI. A malicious
content provider's `DISPLAY_NAME` for a picked attachment can no longer escape the app's cache
directory via `../` path traversal; it is now sanitised to a bare file name with a safe fallback. (#303)

## [0.4.1] - 2026-09-07

Expand Down
16 changes: 15 additions & 1 deletion src/LageBuch.App.Android/Resources/xml/file_paths.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
The FileProvider (AndroidManifest.xml) grants access to exactly the two subtrees named here,
never the whole cache dir: a granted content:// URI can only ever address a file under one of
these, not import.json, picked attachments, or the joined-client attachment cache, all of which
also live under the cache dir but are intentionally left out.
-->
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path name="shared_cache" path="." />
<!-- <cache>/shared: everything this app itself hands out a URI for, namely ShareFileAsync's
and OpenFileAsync's targets, and the PDF/JSON export temp files that feed them
(AndroidAppPaths.SharedDir). -->
<cache-path name="shared" path="shared/" />
<!-- <cache>/lagebuch: on Android, Path.GetTempPath() resolves to the app cache dir, so
FilesViewModel.OpenFileAsync's Path.Combine(Path.GetTempPath(), "lagebuch", GUID,
safeName) lands here. That path is exercised on every attachment open, so this entry
must stay even though nothing in this project writes into it directly. -->
<cache-path name="attachments" path="lagebuch/" />
</paths>
30 changes: 30 additions & 0 deletions src/LageBuch.App.Android/Services/AndroidAppPaths.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,36 @@ public static string RecentFilesJsonPath(Context context) =>
public static string AttachmentCacheDir(Context context) =>
System.IO.Path.Combine(CacheDir(context), "attachment-cache");

/// <summary>
/// One of the two subtrees the <c>FileProvider</c> grants a URI into (see
/// <c>file_paths.xml</c>'s "shared" entry; the other is the attachments root a sibling PR
/// writes into). PDF/JSON export write straight here. <see cref="AndroidFileDialogService"/>'s
/// private <c>EnsureShareable</c> is the structural guarantee behind that: it is the sole
/// path <see cref="AndroidFileDialogService.ShareFileAsync"/> and
/// <see cref="AndroidFileDialogService.OpenFileAsync"/> hand a file to the provider through,
/// and it copies anything not already under this directory (or the attachments root) into a
/// fresh subfolder here before ever calling <c>FileProvider.GetUriForFile</c> — so a caller
/// handing either method a path outside both exposed roots cannot crash the provider.
/// </summary>
public static string SharedDir(Context context)
{
var dir = System.IO.Path.Combine(CacheDir(context), "shared");
System.IO.Directory.CreateDirectory(dir);
return dir;
}

/// <summary>
/// Where picked attachments and imported master-data JSON land before this process reads
/// them off disk. Deliberately not exposed through the <c>FileProvider</c> (it never appears
/// in <c>file_paths.xml</c>) — nothing outside this app needs a URI into it.
/// </summary>
public static string PickedDir(Context context)
{
var dir = System.IO.Path.Combine(CacheDir(context), "picked");
System.IO.Directory.CreateDirectory(dir);
return dir;
}

public static string TrustJsonPath(Context context) =>
System.IO.Path.Combine(context.FilesDir!.AbsolutePath, "trust.json");
}
77 changes: 64 additions & 13 deletions src/LageBuch.App.Android/Services/AndroidFileDialogService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ public sealed class AndroidFileDialogService : IFileDialogService
public Task<string?> PickOpenAsync() => Task.FromResult<string?>(null);

public Task<string?> PickExportPdfAsync(string suggestedFileName) =>
Task.FromResult<string?>(System.IO.Path.Combine(AndroidAppPaths.CacheDir(_activity), suggestedFileName));
Task.FromResult<string?>(System.IO.Path.Combine(AndroidAppPaths.SharedDir(_activity), suggestedFileName));

public Task<string?> PickExportJsonAsync(string suggestedFileName) =>
Task.FromResult<string?>(System.IO.Path.Combine(AndroidAppPaths.CacheDir(_activity), suggestedFileName));
Task.FromResult<string?>(System.IO.Path.Combine(AndroidAppPaths.SharedDir(_activity), suggestedFileName));

private TaskCompletionSource<string?>? _pendingImport;

Expand Down Expand Up @@ -77,7 +77,7 @@ public void CompleteImport(global::Android.Net.Uri? uri)
return;
}

var destPath = System.IO.Path.Combine(AndroidAppPaths.CacheDir(_activity), "import.json");
var destPath = System.IO.Path.Combine(AndroidAppPaths.PickedDir(_activity), "import.json");
using (var input = _activity.ContentResolver!.OpenInputStream(uri)!)
using (var output = System.IO.File.Create(destPath))
{
Expand Down Expand Up @@ -121,7 +121,7 @@ public void CompleteAttachment(global::Android.Net.Uri? uri)
return;
}

var destPath = System.IO.Path.Combine(AndroidAppPaths.CacheDir(_activity), DisplayNameOf(uri));
var destPath = System.IO.Path.Combine(AndroidAppPaths.PickedDir(_activity), DisplayNameOf(uri));
using (var input = _activity.ContentResolver!.OpenInputStream(uri)!)
using (var output = System.IO.File.Create(destPath))
{
Expand All @@ -131,6 +131,9 @@ public void CompleteAttachment(global::Android.Net.Uri? uri)
pending.SetResult(destPath);
}

// A content provider fully controls DISPLAY_NAME -- a hostile one can return "../../evil" to
// escape PickedDir, so SafeFileName.Sanitize reduces it to a bare, harmless file name before
// it ever reaches Path.Combine.
private string DisplayNameOf(global::Android.Net.Uri uri)
{
using var cursor = _activity.ContentResolver!.Query(uri, null, null, null, null);
Expand All @@ -139,21 +142,23 @@ private string DisplayNameOf(global::Android.Net.Uri uri)
var index = cursor.GetColumnIndex(global::Android.Provider.IOpenableColumns.DisplayName);
if (index >= 0)
{
var name = cursor.GetString(index);
if (!string.IsNullOrWhiteSpace(name))
{
return name;
}
return SafeFileName.Sanitize(cursor.GetString(index));
}
}

return "anhang";
return SafeFileName.DefaultFallback;
}

public Task ShareFileAsync(string path, string mimeType)
{
var shareablePath = EnsureShareable(path);
if (shareablePath is null)
{
return Task.CompletedTask;
}

var authority = $"{_activity.PackageName}.fileprovider";
var uri = FileProvider.GetUriForFile(_activity, authority, new Java.IO.File(path));
var uri = FileProvider.GetUriForFile(_activity, authority, new Java.IO.File(shareablePath));
var intent = new Intent(Intent.ActionSend);
intent.SetType(mimeType);
intent.PutExtra(Intent.ExtraStream, uri);
Expand All @@ -166,15 +171,61 @@ public Task ShareFileAsync(string path, string mimeType)
// type, exactly like a desktop double-click.
public Task OpenFileAsync(string path)
{
var shareablePath = EnsureShareable(path);
if (shareablePath is null)
{
return Task.CompletedTask;
}

var authority = $"{_activity.PackageName}.fileprovider";
var uri = FileProvider.GetUriForFile(_activity, authority, new Java.IO.File(path));
var uri = FileProvider.GetUriForFile(_activity, authority, new Java.IO.File(shareablePath));
var intent = new Intent(Intent.ActionView);
intent.SetDataAndType(uri, MimeTypeOf(path));
intent.SetDataAndType(uri, MimeTypeOf(shareablePath));
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
_activity.StartActivity(intent);
return Task.CompletedTask;
}

// The sole choke point between a filesystem path and the FileProvider: this is a structural
// guarantee, not caller convention. Neither ShareFileAsync nor OpenFileAsync ever calls
// FileProvider.GetUriForFile directly on a caller-supplied path -- both route through here
// first. A path already under SharedDir (every export writes straight there) or under the
// "lagebuch" attachments root a sibling PR writes into (see file_paths.xml's "attachments"
// entry) passes through untouched -- no second copy. Anything else (e.g. today,
// FilesViewModel.OpenFileAsync's tempPath under the bare cache root, until that sibling PR
// relocates it) is copied into a fresh SharedDir subfolder first, so
// FileProvider.GetUriForFile can never throw IllegalArgumentException for an unconfigured
// root no matter what a caller passes in. Returns null (callers then no-op rather than
// launch anything) when the source is not an existing regular file.
private string? EnsureShareable(string path)
{
if (!System.IO.File.Exists(path))
{
return null;
}

var fullPath = System.IO.Path.GetFullPath(path);
var sharedDir = AndroidAppPaths.SharedDir(_activity);
var attachmentsDir = System.IO.Path.Combine(AndroidAppPaths.CacheDir(_activity), "lagebuch");

if (IsUnder(fullPath, sharedDir) || IsUnder(fullPath, attachmentsDir))
{
return fullPath;
}

var destDir = System.IO.Path.Combine(sharedDir, Guid.NewGuid().ToString("N"));
System.IO.Directory.CreateDirectory(destDir);
var destPath = System.IO.Path.Combine(destDir, System.IO.Path.GetFileName(fullPath));
System.IO.File.Copy(fullPath, destPath, overwrite: true);
return destPath;
}

private static bool IsUnder(string fullPath, string dir)
{
var normalizedDir = System.IO.Path.GetFullPath(dir) + System.IO.Path.DirectorySeparatorChar;
return fullPath.StartsWith(normalizedDir, StringComparison.Ordinal);
}

// Unlike OpenFileAsync, this is a remote http(s) URL, not a local file -- no FileProvider
// involved, just hand it straight to whatever app the device has registered for the scheme.
// The http(s)-only check is enforced independently here too (not only by LinksViewModel, the
Expand Down
25 changes: 25 additions & 0 deletions src/LageBuch.AppLogic/Services/SafeFileName.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
namespace LageBuch.AppLogic.Services;

/// <summary>
/// Reduces an untrusted display name (e.g. a content provider's <c>DISPLAY_NAME</c>, which a
/// malicious provider fully controls) to a bare file name safe to <see cref="Path.Combine(string, string)"/>
/// into a fixed directory. Backslash-style traversal is normalised to forward slashes first so
/// <see cref="Path.GetFileName(string)"/> — which only recognises the current platform's own
/// separators — also strips a Windows-style <c>..\..\evil.dll</c> payload on Unix, not just
/// <c>../../evil.dll</c>.
/// </summary>
public static class SafeFileName
{
/// <summary>The fallback name used when sanitising leaves nothing usable behind.</summary>
public const string DefaultFallback = "anhang";

public static string Sanitize(string? name, string fallback = DefaultFallback)
{
var normalized = (name ?? string.Empty).Replace('\\', '/');
var fileName = Path.GetFileName(normalized);
var invalidChars = Path.GetInvalidFileNameChars();
var candidate = new string(fileName.Where(c => Array.IndexOf(invalidChars, c) < 0).ToArray());

return candidate is "" or "." or ".." ? fallback : candidate;
}
}
54 changes: 54 additions & 0 deletions tests/LageBuch.AppLogic.Tests/SafeFileNameTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System.Diagnostics.CodeAnalysis;
using LageBuch.AppLogic.Services;

namespace LageBuch.AppLogic.Tests;

[SuppressMessage("Design", "CA1054", Justification = "Tests exercise the sanitiser with free-form (even hostile) strings — that is the point of these tests.")]
public class SafeFileNameTests
{
[Theory]
[InlineData("photo.jpg")]
[InlineData("Kfz-Kennzeichen (1).png")]
[InlineData("bericht_final.pdf")]
public void Sanitize_passes_through_an_ordinary_display_name(string name)
{
Assert.Equal(name, SafeFileName.Sanitize(name));
}

[Theory]
[InlineData("../../etc/passwd", "passwd")]
[InlineData("..\\..\\Windows\\System32\\evil.dll", "evil.dll")]
[InlineData("/etc/shadow", "shadow")]
[InlineData("a/b/c.txt", "c.txt")]
public void Sanitize_reduces_a_path_traversal_attempt_to_its_final_segment(string input, string expected)
{
Assert.Equal(expected, SafeFileName.Sanitize(input));
}

[Fact]
public void Sanitize_strips_the_platform_invalid_filename_characters()
{
// NUL is invalid on every platform .NET runs on (Windows and Unix both reject it via
// Path.GetInvalidFileNameChars()), so this assertion holds regardless of CI OS — unlike
// e.g. ':', which is only invalid on Windows.
Assert.Equal("foobar.txt", SafeFileName.Sanitize("foo\0bar.txt"));
}

[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(".")]
[InlineData("..")]
[InlineData("../..")]
[InlineData("/")]
public void Sanitize_falls_back_to_anhang_for_empty_or_dot_only_input(string? input)
{
Assert.Equal("anhang", SafeFileName.Sanitize(input));
}

[Fact]
public void Sanitize_falls_back_to_a_caller_supplied_default()
{
Assert.Equal("import.json", SafeFileName.Sanitize(null, fallback: "import.json"));
}
}
Loading