diff --git a/docs/client-security-architecture.md b/docs/client-security-architecture.md index abb3fb399..aa3931cad 100644 --- a/docs/client-security-architecture.md +++ b/docs/client-security-architecture.md @@ -1,5 +1,7 @@ # ByteSync Client Security Architecture +> Historical overview. For the current relay identity protocol, authorization boundary, local filesystem permissions, migration and validation status, see [Security boundary changes](security-boundaries.md). The short legacy ClientId described below is a display/trust alias and is not an authenticated identity. + **Last Updated:** November 6, 2025 **Analyzed Codebase:** ByteSync.Client (.NET 8.0) @@ -52,14 +54,14 @@ public void InitializeRsa() ### Client Identifier -The `ClientId` is cryptographically derived from the RSA public key: +The legacy display `ClientId` is derived from the RSA public key: ``` ClientId = Base26(SHA256(InstallationId + SHA256(PublicKeyRSA))) Format: XXXX-XXX-XXX (e.g., "ABCD-EFG-HIJ") ``` -This creates a stable, human-readable identifier that is unique to each client's cryptographic identity. +This creates a human-readable alias. Its numeric reduction does not provide a collision-resistant security identity; the current protocol uses the full SHA-256 fingerprint described in the security boundary document. ### Local Key Storage diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md new file mode 100644 index 000000000..8036cd3ed --- /dev/null +++ b/docs/security-boundaries.md @@ -0,0 +1,249 @@ +# Security boundary changes + +Date: 2026-11-13. Local implementation on `fix/security-boundaries`, based on `397a1d1d781ae9eaa979d3cfe48b9ac7256f99d4`. A read-only check of `origin/master` returned the same commit before changes. The checkout was initially clean. The actual solution targets .NET 10; validation used SDK 10.0.204 on Windows. + +This is an implementation and local validation report, not evidence of a deployed fix or of a compromise. No hosted service was tested. Security-word design, AEAD migration and update signing remain separate work. + +## Implemented relay boundary + +### Possession, identity and authentication epoch + +`AuthenticationProtocol` derives the identity from SHA-256 of canonical DER SubjectPublicKeyInfo after fully importing the existing PKCS#1 RSA public key. The full uppercase 64-character fingerprint is the security identity. Keys must be 2048–8192 bits; trailing key data is rejected. Instance identifiers consist of that fingerprint, an underscore and a canonical GUID. Multiple instances can prove possession of the same durable key independently. + +The client retains its existing RSA private key. Login first obtains a random 256-bit server nonce with a two-minute lifetime, then signs a length-prefixed canonical binary message with RSA-PSS/SHA-256. The message binds the domain, authentication epoch, relay audience, protocol version, challenge ID, nonce, expiry, fingerprint, readable ClientId, instance, software version and platform. The relay stores the exact binding, consumes the Redis challenge using a single atomic Lua script (`GET` followed by `DEL` inside the script), then verifies the signature. Failed verification does not issue tokens or adopt an existing instance. The script uses commands available in Azure Cache for Redis 6.0; GETDEL is not required. Scripting must be permitted, and script errors fail closed without a non-atomic fallback. + +The current authentication epoch is 1 and protocol is V3. Software version remains a separate compatibility check and cannot substitute for proof of possession. The legacy short `ApplicationSettings.ClientId` remains a display/trust alias; it cannot claim a server identity or an old instance. There is no first-key-wins migration of old aliases. Existing mismatched or legacy instance records are rejected. + +JWTs carry fingerprint and epoch claims. Both JWT validation paths check signature, HS256, issuer, audience, lifetime and the live record/claim association. Refresh records also carry the epoch; an old refresh token cannot mint a verified JWT. No weak login fallback was added. Public challenge/login/refresh endpoints are POST; announcements remain public. The local key and trusted-key lists are not regenerated or silently cleared. + +### Session authorization and joining + +The registered MediatR `SessionAuthorizationBehavior` protects session, inventory, member, synchronization, trust and transfer requests before their handlers run. It checks verified identity, session existence/removal, session epoch/protocol, current membership or an eligible expiring prejoin attempt, allowed state, and operation-specific resource ownership. A reflection test enumerates all session request types and detects missing authorization markers. Profile/lobby operations have their own ownership checks because their authorization context differs from a session. + +Members can still read other members' inventories/sources within their session. Source/node mutations must address the caller's resources, including collision checks inside the repository update. Action acknowledgements must reference the real source/target node. Route/body identifiers are compared for session, member, profile and lobby endpoints. All referenced actions are preflighted before batch handlers run. + +`beginJoin` creates a controlled five-minute prejoin attempt before the legitimate trust exchange and returns only instance IDs. Detailed membership remains restricted to current members. The attempt binds the verified requester, public key and chosen current validator. Repeated password-exchange setup preserves an eligible existing attempt and its trust checks. The validator must equal the authenticated caller. Finalization requires the authenticated joiner, matching validator, session, identity, nonempty unique proof and expiry. Finalization consumes the proof while holding the session Redis lock across transaction commit; notifications follow successful commit. The old short-ID prefix shortcut was removed. Same-key shortcuts require the full verified fingerprint and instance namespace. + +Profile slots identify their original instance in addition to the durable fingerprint, preserving distinct slots for multiple instances of one identity. New profiles and lobbies carry the current epoch. Legacy remote relationships cannot silently become verified relationships. Local profile files are preserved. + +### SignalR + +Negotiation binds the SignalR user to `epoch:instance`; connection callbacks refuse legacy users and unverified records. Client/session/lobby group names include the authentication epoch. Reconnection rechecks saved session/lobby subscriptions against current membership and epoch, rather than trusting persisted group names. Joining/quitting applies group changes to all known distinct connections of the instance. Token-bearing negotiation responses and session credential payloads are no longer logged. + +There are no client-invocable synchronization mutations over SignalR in this serverless design; mutations enter authenticated HTTP/MediatR handlers. SignalR connection callbacks still depend on the deployment's trusted Azure upstream configuration. A live Azure test has not been performed. + +### Storage object authority + +A transfer must match its authorized route/session, verified upload owner, type, action ownership and allowed part range. The relay creates or loads an immutable file record, chooses a random storage object ID, snapshots recipients and provider, and replaces the request's free-form object selection with the stored definition. Synchronization downloads require the recipient to be a target of every action in the transferred archive, as well as a current session member. Other transfer types snapshot the other current members. Downloads require an uploaded registered part. Totals cannot contradict recorded parts. + +Azure/R2 object keys are formed only from the server-generated ID and validated part number. URLs are scoped to one part and one operation: Azure blob write/read SAS or R2 PUT/GET, with five-minute expiry. The record's provider is used even if the default provider configuration later changes. Part bytes may be deleted after acknowledgement, but the authorization record is retained until session cleanup or its existing two-day cache expiry so the final acknowledgement remains authorized. A caller cannot substitute another session's object by changing body path fields. + +Signed URLs remain bearer capabilities until expiry. Membership revocation prevents new URLs; it does not revoke a previously issued URL. Upload owners can overwrite their own part while a write URL is valid. Provider-level immutability, signed content hashes and AEAD are separate decisions. + +## Implemented client filesystem boundary + +### Local permissions and replicated representations + +`LocalSourceAuthorizationService` owns local permissions independently of replicated sources, inventories and profile contents. Local application settings persist exact `(key fingerprint, canonical root, file/directory type)` permissions. A runtime grant additionally binds the current session object, session ID, source ID, real node, local instance and root/type snapshot. A reused short session ID cannot inherit a previous session object's grants. + +Only explicit local source selection creates a new permission. Network sources are checked against the authenticated DTO owner and actual node owner. A network echo of a local source must match an existing grant; it cannot change its root or type. Initial source/node loading after join has the same checks. Profile restoration can attach a new runtime source ID only to an already persisted exact local permission. Therefore unattended profiles remain possible after local enrollment, without prompting on every sync. Old profiles need their sources selected locally once; paths from profile contents do not grant themselves authority. Explicit local removal revokes the permission. + +Inventory parts and action parts now carry `SourceId`; action parts also carry a strict source-relative path. Remote inventory ownership, source identifiers and logical relative paths are validated, and parent inventory references are rebuilt from the authoritative top-level inventory. This prevents a malicious inventory from acquiring local authority when an honest creator computes and forwards the plan. + +### Plan validation and execution + +The complete received/generated plan is checked before installation, organization or execution. Structural validation includes unique safe action IDs, valid operators/types, required timestamps/synchronization mode, complete part bindings and valid relative paths. Local parts are resolved from the local grant, never from a peer's root. Resolver callbacks are excluded from JSON and installed only after every action passes. A file grant accepts only the empty relative path, so it cannot authorize siblings. Directory checks use a separator boundary and the platform's casing rules. + +Execution resolves again and rechecks permission. The boundary covers content reads/fingerprints/uploads, full copy staging and replacement, delta basis/output/replacement, deletes, directory creation, file timestamps, downloaded archives and finalization. Upload slicing and download merging/finalization repeat access checks. Multi-file archives are completely checked for unexpected IDs, duplicate entries and path forms before extraction. + +Internal cache/profile/session components are validated separately; a peer machine name is no longer used to select a cache path. Temporary replacements use random sibling names and exclusive creation. An invalid complete plan performs no synchronization mutation. This is validation atomicity, not a transactional filesystem: a valid batch that later loses permission or encounters I/O failure may have completed earlier authorized actions. + +### Native access and deliberate restrictions + +`LocalPathSafety` combines strict path syntax, reparse/link rejection and native operations. It does not treat two textual checks as a filesystem race solution. + +* Windows traverses directories with no-delete/no-write sharing leases, opens leaves with OPEN_REPARSE_POINT, checks the opened handle and rejects hard-linked files. Replacement pins the source and parent handles and uses handle-relative NT rename within the same parent. Parent directory pinning and a nonempty parent protect that replacement against directory substitution. Real full-copy/delta, junction, hard-link and directory-substitution tests ran on this Windows host. +* Linux/macOS use component-wise openat with O_NOFOLLOW and directory descriptors, fstat of the opened leaf, mkdirat/unlinkat, and relative native rename with exclusive no-overwrite flags when requested. File streams use the opened descriptor. Linux x64/arm64 and macOS x64/arm64 ABI layouts were inspected against platform headers; they have not been executed here. Unsupported Linux architectures fail closed. +* Symlinks, junctions/reparse points and hard-linked file content are refused, including links beneath an authorized directory. UNC/device sources are refused. Backslash, colon, absolute paths, empty/dot/dot-dot components and controls are refused in the portable relative representation. Windows additionally rejects device names, invalid characters and trailing dots/spaces. This excludes some valid Unix filenames and network-drive/link workflows; there is no automatic fallback. +* Directory deletion is nonrecursive. Empty directories can be removed, but a nonempty tree must be represented by individual authorized child operations before its directory is removed. Timestamp operations apply to regular files; unsupported special files fail closed. + +Microsoft documents that a directory must be empty to establish a reparse point: [Reparse points](https://learn.microsoft.com/en-us/windows/win32/fileio/reparse-points). Native declarations were checked against [Apple stat.h](https://github.com/apple-oss-distributions/xnu/blob/main/bsd/sys/stat.h), [Apple stdio.h](https://github.com/apple-oss-distributions/xnu/blob/main/bsd/sys/stdio.h) and [glibc Linux stat layout](https://github.com/bminor/glibc/blob/master/sysdeps/unix/sysv/linux/x86/bits/struct_stat.h). These checks are static evidence, not cross-platform runtime validation. + +## Architecture choices and rejected alternatives + +| Choice | Alternative rejected | Reason | +| --- | --- | --- | +| Durable RSA possession and full canonical fingerprint | Trust a supplied instance/short alias, or JWT validation alone | Validation of a token cannot repair an unproved initial identity. | +| Atomic expiring Redis challenge | Process-local nonce or read-then-delete | Multiple workers must agree on single consumption. | +| Explicit epoch/protocol break | Keep the old login beside the new one | A weak reachable login would retain the vulnerability. | +| Recreate legacy remote relationships | Let the first key claim a legacy alias/profile | There is no authenticated legacy binding to migrate automatically. | +| Local grants plus SourceId resolution | Import permissions from a profile/source echo or sanitize peer roots | Replicated data cannot be the authority for local access. | +| Persist locally enrolled permissions | Ask for confirmation at every sync | Local permissions preserve unattended operation without substituting prompts for enforcement. | +| Native no-follow access and initial link refusal | GetFullPath/StartsWith or repeated path checks alone | Text does not pin the filesystem object accessed. Supporting links safely needs additional design. | + +## Initial security-boundary validation + +The final non-incremental build and each test command were run separately. Final commands and result counts are recorded below. TRX and coverage artifacts are retained locally under `artifacts/security-boundaries/`; build/test logs are local ignored files. They contain no intentionally logged tokens, private keys or session secrets. Test keys and sentinels are synthetic. + +| Final suite | Passed | Failed | Not executed (TRX, including OS exclusions) | +| --- | ---: | ---: | ---: | +| server | 364 | 0 | 0 | +| client | 1232 | 0 | 12 | +| functions | 66 | 0 | 0 | +| common | 53 | 0 | 0 | +| local-integration | 40 | 0 | 6 | + +**1755 passed, zero failures; 186 security cases are included in these totals. 18 cases did not execute.** NUnit console totals exclude some OS-filtered cases; the table counts every NotExecuted TRX result. Build: zero errors, 670 warnings (including existing nullable, obsolete API and dependency vulnerability warnings). `git diff --check` passed. + +Reproduction (build and tests are separate commands): + +```powershell +rtk proxy dotnet build ByteSync.sln --no-incremental --no-restore --verbosity quiet +rtk proxy dotnet test tests/ByteSync.ServerCommon.Tests/ByteSync.ServerCommon.Tests.csproj --no-build --no-restore --filter 'FullyQualifiedName!~.Repositories.' --collect 'XPlat Code Coverage' +rtk proxy dotnet test tests/ByteSync.Client.UnitTests/ByteSync.Client.UnitTests.csproj --no-build --no-restore --collect 'XPlat Code Coverage' +rtk proxy dotnet test tests/ByteSync.Functions.UnitTests/ByteSync.Functions.UnitTests.csproj --no-build --no-restore +rtk proxy dotnet test tests/ByteSync.Common.Tests/ByteSync.Common.Tests.csproj --no-build --no-restore +rtk proxy dotnet test tests/ByteSync.Client.IntegrationTests/ByteSync.Client.IntegrationTests.csproj --no-build --no-restore --filter 'FullyQualifiedName~TestSynchronizationActionHandler|FullyQualifiedName~EnvironmentService_Tests|FullyQualifiedName~FullInventoryRunner_IntegrationTests|FullyQualifiedName~InventoryBuilderAccessHandling_IntegrationTests' +``` + +Do not run a coverage collector and another test process against the same output assembly concurrently. Final collection used one process per test output. Superseded trial output is under the separate `history-*` directory; only `final/validation.json` and its referenced reports are authoritative. + +Line coverage of selected boundary source files, merging duplicate/state-machine sequence points within each report (not whole-project or Sonar new-code coverage): + +| Source | Covered / executable lines | Coverage | +| --- | ---: | ---: | +| `AuthenticationProtocol.cs` | 28 / 29 | 96.6% | +| `AuthenticationChallengeService.cs` | 41 / 41 | 100.0% | +| `CloudSessionProfileService.cs` | 79 / 84 | 94.0% | +| `TransferAuthorizationService.cs` | 51 / 59 | 86.4% | +| `ClientAuthentication.cs` | 8 / 8 | 100.0% | +| `SessionAuthorizationBehavior.cs` | 114 / 127 | 89.8% | +| `LocalPathSafety.cs` | 153 / 243 | 63.0% | +| `LocalSourceAuthorizationService.cs` | 104 / 110 | 94.5% | + +The 85% target is **not met for LocalPathSafety** on this Windows host, in particular because native POSIX branches did not execute. No exclusions were added to hide those branches. The PR-wide 80% Sonar gate has **not been demonstrated**. Cross-platform runtime tests and the actual new-code analysis remain release gates. + +Machine-readable evidence: [final validation summary](../artifacts/security-boundaries/final/validation.json). + +Security tests cover real RSA proofs, expiry/replay, concurrent consumption (30 attempts, one winner using an atomic Redis fake), instance binding, old token/refresh rejection, real registered JWT bearer authentication, creation, join proof binding/replay, profile ownership/multiple-instance slots, current SignalR subscriptions, every session request's outsider rejection, transfer ownership/parts/lifecycle and offline Azure SAS scope. Client cases exercise exact file grants, hostile paths and source/node impersonation, forged inventory propagation, XML permission persistence, revocation, complete-plan rejection, links/junctions/hardlinks, real copy/delta and locally enrolled automated restore. Existing local integration tests now explicitly grant their fixture sources through the real registry. + +### Validation not performed + +* No tests against production, staging or hosted ByteSync, Redis, Azure SignalR, Blob Storage or R2. Server repository and Functions integration suites require configured services and were excluded. R2 upload/download and resume integration classes were excluded explicitly. +* Challenge consumption uses an atomic Lua script compatible with Redis 6.0. Distributed Redis/RedLock transaction failures and failover behavior still require isolated integration validation. +* Docker is installed but its engine was unavailable; no ready Linux/macOS runner was available. POSIX native syscall/ABI behavior, filesystem-specific edge cases and packaged applications need runtime tests on each supported OS/architecture. +* Windows ACL-denial integration cases self-skipped because this host did not enforce their synthetic permission changes. POSIX-only tests cannot run on Windows. +* No Sonar PR analysis, production-scale/load/rate-limit evaluation, complete UI/manual trust exchange, or live multi-machine automatic synchronization was run. Local tests do not establish a production security certification. + +## Redis 6.0 compatibility follow-up + +Azure resource metadata confirmed that the ByteSync development/staging and production caches use Azure Cache for Redis 6.0 (Basic and Standard respectively). GETDEL requires Redis 6.2 and is unavailable on those engines. Authentication now consumes a challenge by executing one short Lua script with one explicitly declared key: GET the value, DEL that same key if present, and return the value. Redis executes the script atomically; there is no separate client-side GET/DEL or weak authentication fallback. Missing/expired values reject authentication, invalid signatures still burn their challenge, and script/server errors propagate without issuing tokens. The RSA binding, two-minute challenge expiry and authentication epoch are preserved. No infrastructure upgrade is required for this change. See [Redis scripting atomicity](https://redis.io/docs/latest/develop/programmability/eval-intro/) and [Azure Cache versions](https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-how-to-upgrade#current-versions). + +The unit fake now rejects GETDEL as Redis 6.0 does. Added cases enforce one ScriptEvaluateAsync call with exactly the challenge key, verify that an invalid signature consumes only its own challenge, and verify that a script failure never falls back to non-atomic commands. Existing concurrent-consumer, replay, expiry, key/instance and signature checks remain active. + +Follow-up validation: solution build succeeded with zero errors (142 warnings); **367 server unit tests and 66 Functions unit tests passed, zero failures**. Coverage of the C# AuthenticationChallengeService is 100.0% (42/42 executable lines). This does not measure execution of the Lua body. Local TRX/Cobertura evidence is indexed by [Redis 6.0 validation](../artifacts/security-boundaries/redis60/validation.json). The initial validation counts above belong to the earlier commit. + +Four explicit integration cases were added in `AuthenticationChallengeRedis60Tests` for a real disposable Redis 6.0: valid proof/replay and TTL, 30 concurrent consumers across independent connections, invalid-signature consumption and isolation, and Redis-side expiry/nil handling. They only connect to 127.0.0.1, require an explicit Redis60Port parameter, check the server is version 6.0, and remove only the randomly generated challenge keys they created. They do not load hosted connection settings. **These four cases were not executed:** Docker failed during startup and Paul stopped it. Docker was not restarted and no test was run against Azure Redis. Run them later with an isolated local Redis 6.0 and an explicit port, for example: + +```powershell +rtk proxy dotnet test tests/ByteSync.ServerCommon.Tests/ByteSync.ServerCommon.Tests.csproj --no-build --no-restore --filter 'FullyQualifiedName~AuthenticationChallengeRedis60Tests' -- 'TestRunParameters.Parameter(name="Redis60Port", value="16379")' +``` + +The server regression run excluded `.Repositories.` and `.Integration.` to avoid running service-dependent suites. This follow-up changed no Azure settings and requires no production or staging data access. + +## Offline Redis 6.0 regression guard + +`Redis60CompatibilityTests` runs in the ordinary server unit suite without a Redis process, Azure access, configuration secrets, Docker or network access. It inspects compiled production IL, including async state machines and generic repository methods, and allows only the reviewed Redis API overloads. Unreviewed command APIs and raw command dispatch fail the test. The audit covers StackExchange.Redis 2.10.1 and RedLock.net 2.3.2; the resolved dependency versions must match that baseline so SDK command-mapping changes require review. + +Lua bodies are restricted to the audited constant script, and RedLock's actual embedded Extend/Unlock resources are checked against audited SHA-256 digests. Line endings are normalized for cross-platform checkouts. Changing Lua commands, options, dynamic dispatch or these dependency versions requires an explicit compatibility review and baseline update. This is a conservative audit allowlist; a new compatible operation also requires review. Reflection-based or dynamically generated production command dispatch is outside this static guard and must not be used to bypass it. + +The guard's negative cases cover GETDEL, GETEX, SET GET/EXAT, read-only scripting APIs, raw dispatch, absolute-expiry/value-condition overloads, and a real GETDEL call in compiled test code that is inspected but never executed. Repository saves now explicitly select the TimeSpan/When overload for their two-day TTL. The former three-argument call selected the modern Expiration/ValueCondition overload; its existing relative-TTL/default-condition usage was compatible, but that broader overload is deliberately refused by the guard. Fake-backed tests exercise both immediate and transactional saves and assert the relative TTL and audited overload. + +Validation: solution build succeeded with zero errors (17 warnings). **1,742 tests passed with zero failures**: 386 server, 1,236 client, 54 Common, 66 Functions. These include 19 Redis guard cases and four new client authentication cases. Twelve existing POSIX-only client cases did not execute on Windows. Evidence: [guard validation](../artifacts/security-boundaries/redis-guard/final/validation.json). Redis runtime/ACL/failover behavior remains outside this run; no Azure endpoint was contacted and Docker was not started. + +### Older relay and client compatibility + +The supplied client log shows a 404 for `auth/challenge` while targeting the remote development API, before SignalR negotiation or any peer exchange. The source before this branch has no challenge endpoint. An old relay or a deployment missing that route therefore cannot authenticate this client. The deployed server version was not probed; this diagnosis uses the supplied log and local source only. + +An HTTP 404 from `auth/challenge` now stops automatic reconnection after the first request. The client shows "Incompatible relay server" ("Serveur relais incompatible" in French), with details asking the user to check the relay address or update the relay server. The diagnostic log names the missing route and HTTP status. This applies to empty, HTML and JSON error responses, without attempting login, storing tokens or opening SignalR. Other HTTP and network errors retain their existing retry behavior; a 404 from `auth/login` is not classified as a missing challenge route. An explicit new connection attempt remains possible after correcting the relay. This message concerns the relay; an older V2 peer separately requires a client update. + +Offline validation of this error handling: solution build succeeded with zero errors; all 1,272 client unit tests passed, including 36 added cases. Twelve existing POSIX-only cases did not execute on Windows. Line coverage was 93.75% for `ApiInvoker`, 96.25% for `ConnectionStatusViewModel`, and 100% for `AuthApiClient` and `RelayIncompatibleException`. HTTP responses were supplied by in-process handlers; no Azure endpoint was contacted and Docker was not started. Evidence is under `artifacts/security-boundaries/relay-error/client/`. + +V3 clients require the matching relay and V3 peers. An older V2 peer is explicitly incompatible, and an older relay cannot provide the required possession proof. Regression tests assert that a missing challenge endpoint fails without calling the legacy login; a supported relay receives a valid RSA-PSS proof with the current epoch/protocol; refresh has no login fallback; and V2 remains rejected. The secure protocol is not downgraded to restore legacy connectivity. + +For local Rider testing, run the Functions project built from this branch and launch the client in Debug with `--use-local-api`. Check the client's `LocalDebugUrl` matches the Functions host's actual port and `/api/` base path, then confirm the client log selects that local URL. Debug defaults to the remote DevelopmentUrl when no API-selection argument is supplied. The local-API switch applies to Debug execution; Release uses ProductionUrl (or its existing staging override). Run all session peers from the same V3 branch and create a fresh session. Coordinated remote deployment remains a separate, unexecuted operation. + +## PR review corrections (2026-11-21) + +Join validation now resends the existing finalization proof after a failed or lost SignalR notification. Retries preserve both the proof and its original expiry, still require the bound current validator and an eligible pending member, and cannot recreate a proof after finalization. Regression tests cover successful and failed first notifications, ineligible retries, and exactly one finalization after resending. + +Functions integration fixtures and the HTTP end-to-end scenario now use a shared real RSA identity, request and sign an authentication challenge, bind refresh records to the current identity/epoch, and use server-generated storage object IDs instead of client metadata in object paths. The end-to-end join validation is authenticated as the validator rather than the joining client. Offline regressions exercise the shared identity with the real challenge, login, token and refresh services, reject challenge/refresh replay, and check SAS object/part/operation scope without making storage requests. + +Validation: solution build succeeded with zero errors; 402 server unit tests (excluding service-dependent repository and integration suites), 66 Functions unit tests and 54 Common unit tests passed, zero failures. These include 16 new regression cases; the shared RSA fixture helper has 100% line coverage. The migrated integration fixtures and E2E compile but were not executed because this correction was explicitly required to avoid Azure access and Docker. Restore used the local NuGet package cache. Evidence is under `artifacts/pr351-fixes/`. + +The correction commit uses `[skip ci]` to prevent the PR workflows from contacting configured Azure services or starting container-based tests after the requested push. Those workflows and the actual integration/E2E suites must be run later when external-service testing is authorized; no production checks were weakened to accommodate legacy fixtures. + +## ClientId and Identity clarification (2026-11-21) + +`ClientId` remains the stored readable installation code, in the existing `ABCD-EFG-HIJ` format. Environment initialization, About/display consumers, public-key information, login requests, server records, endpoints and the JWT ClientId claim all retain that alias. No migration rewrites `ApplicationSettings.ClientId`, regenerates the RSA key pair or clears existing trusted keys. Trust continues to require the previously accepted public key; an identical readable alias with a different key is not trusted. + +`Identity` separately holds the full canonical RSA fingerprint. It owns authentication, instance binding and authorization. `ClientInstanceId` remains `_`; reverting its prefix to the short code would restore an unsafe identity shortcut. The readable alias is now included in both the signed login message and the stored challenge binding. Two different keys can share an alias without merging server records or claiming an existing instance. Legacy records without a verified identity/epoch remain rejected. + +Dormant profile/lobby ownership checks now use an explicit slot `Identity`, while slot `ClientId` retains the readable code. Missing identities fail closed. This is an authorization correction, with no profile migration or new profile behavior. + +This does not restore the legacy network protocol: clients, relay and peers still need matched V3 builds. The revised canonical login message is part of this unreleased PR; intermediate builds of the PR must also be rebuilt together. + +Offline validation: solution build succeeded with zero errors. **1,816 tests passed, zero failures**: 1,284 client, 412 server (excluding service-dependent repository/integration suites), 66 Functions and 54 Common. Twelve existing POSIX-only client cases did not execute on Windows. The 22 added regression cases cover retained aliases/keys/trust, identity-based instance filtering, alias collisions, signed challenge binding and profile/lobby authorization. The Functions adapter initially failed to load; cleaning and rebuilding its local test outputs resolved this, and all 66 tests then passed. Integration/E2E fixtures compile but were not run. + +Combined client/server coverage covers 20 of the 22 changed executable production lines (90.9%); the two bootstrap wiring lines were not executed. `AuthApiClient`, `AuthenticationChallengeService`, `CloudSessionProfileService` and the shared RSA fixture helper have 100% line coverage in these runs. This local change metric does not establish the PR-wide Sonar coverage gate. Evidence is under `artifacts/clientid-identity/`, including `validation.json`, TRX and coverage files. No Azure endpoint was contacted and Docker was not started. The same PR branch receives the correction with `[skip ci]` to avoid Azure/container workflows. + +## Authenticated trust confirmations (2026-11-22) + +Trust completion notifications no longer select a pending exchange by readable ClientId. The relay derives the issuer instance, full fingerprint and display alias from the authenticated client, replacing caller-supplied issuer metadata. It checks the current session epoch/protocol/state, sender membership or an unexpired join attempt, recipient eligibility, the recipient public key and a bounded nonempty exchange identifier before forwarding. + +Both client roles register the expected peer instance, canonical RSA fingerprint and the salt already shared by their public-key check exchange. A received confirmation must match all three values within the current session and target the local instance. Identical readable aliases, including distinct instances of one key, remain independent. The first confirmation consumes the pending response; duplicate registration of the same exchange preserves that state, while a new salt replaces the expected exchange and rejects older confirmations. The readable ClientId and existing saved peer trust remain unchanged. + +This update addresses P1 only. It does not change manual key renewal. The extended notification requires matched builds of this unreleased V3 PR; missing identity/exchange fields cannot use an alias fallback. + +Validation: the solution, including integration fixtures, builds with zero errors. **1,850 offline tests pass, zero failures**: 1,299 client, 431 server (excluding service-dependent repository/integration suites), 66 Functions and 54 Common. These are 34 additional cases compared with the preceding PR head. Twelve existing POSIX-only client cases did not execute on Windows. Coverage reaches 56 of 57 changed executable production lines (98.2%); the trust-confirmation handler has 100% line coverage. This does not establish the PR-wide Sonar gate. Integration/E2E services were not exercised. Restore used the local package cache; no Azure endpoint was contacted and Docker was not started. + +Evidence is retained locally under `artifacts/pr351-p1/` in the original checkout, including TRX, coverage and `validation.json`. The correction uses `[skip ci]` to avoid Azure/container workflows after pushing to the same PR. + +## Coherent manual key renewal (2026-11-22) + +Explicit manual renewal now updates the stored RSA pair, readable ClientId, runtime Identity and fingerprint-prefixed ClientInstanceId together. The existing manual-renewal behavior still regenerates the readable code and clears trusted keys after user confirmation; normal startup/login does neither. The readable code keeps its historical format. + +Renewal is serialized and refused while a session exists, while creating/joining a session, or while an authentication attempt/retry is pending. These checks run before stopping the connection and session state is checked again afterwards. The UI disables renewal during sessions/connection setup and supplies English/French guidance. A failed hub stop leaves the keys unchanged. + +Before key replacement, the client cancels token refresh, waits for any in-flight refresh request to finish, stops the old hub, clears its endpoint and removes the old JWT/refresh tokens. The settings update installs the matching environment identity and a fresh instance. A previously connected client starts an observed fresh-login reconnection in the background, allowing the new identity to appear immediately even if the relay is unavailable. Reconnection failure preserves coherent new key/identity state for another attempt. No legacy login fallback is introduced. + +Automatic restarts and explicit stops share a lifecycle gate; canceled refresh work cannot restart the old connection. Ordinary same-key reconnections keep the existing instance identity so local source grants and current sessions are not invalidated by transient connectivity. Only explicit key renewal clears/replaces the endpoint and key identity. Existing session membership and local permissions are not promoted to the new key. + +Validation: the solution and integration fixtures compile with zero errors. The full client unit suite passes **1,317 tests**, zero failures, including 18 additional cases for renewal, real RSA-PSS login after renewal, token removal, refusal/failure paths, refresh draining, automatic restart, recipient/session UI guards and nonblocking reconnection. Twelve existing POSIX-only cases do not execute on Windows. Coverage reaches 88 of 93 changed executable/instrumented lines (94.6%), including the XAML tooltip sequence point; this does not establish the PR-wide Sonar gate. Backend production code is unchanged; the server/Functions/Common suites were not rerun for this client-only follow-up. The previous P1 validation remains recorded above. Integration/E2E services were not exercised. No Azure endpoint was contacted and Docker was not started. Evidence is under `artifacts/p2/validated/`; the correction uses `[skip ci]` when pushed to the same PR. + +## Future rollout proposal (not executed) + +1. Review this patch and approve the breaking protocol, restrictions and enrollment experience. Complete native multi-platform CI, isolated Redis/SignalR/storage end-to-end tests, load/abuse checks and the coverage gate. Confirm the Redis version before rollout. Back up local RSA/settings/trust/profile data through the existing supported process; do not collect private keys centrally. +2. Prepare matched V3 clients and relay together in an isolated environment. Verify manual join, multiple instances, reconnection, profile automation, full/delta transfers and expiration/revocation. Distribute the compatible clients before the cutover window if desired, accepting that they will refuse the old relay protocol until cutover. A separate explicitly selected legacy client can remain outside the new service only under a separately approved risk decision; coexistence does not close the old login flaw. +3. During an announced maintenance window, stop/drain the old relay writers and synchronization jobs. Disable the old login path on every reachable relay instance. Do not run mixed old/new relay workers against a shared authorization namespace. Invalidate old refresh/JWT assurance through the epoch checks; rotate signing secrets as an additional operational measure if approved. Terminate old SignalR connections or provision a fresh hub and switch upstream endpoints; epoch groups isolate new delivery but do not sanitize an old reachable relay. Wait for previously issued legacy SAS/R2 URLs to expire or revoke them operationally before declaring cutover complete. +4. Deploy the matched relay/client V3 pair. Create fresh sessions; epoch-0 sessions cannot continue. Reauthenticate with the existing private key, recreate cloud profile/lobby relationships, and perform the normal peer trust exchange using retained local trusted keys. Do not map a legacy alias to whichever key appears first. Old profile files remain available for manual reconstruction; migration of remote relationships would require a separately designed proof-based process. +5. Enroll each local source through local selection once. Subsequent profile restore must match the stored permission exactly and can run unattended. Explain rejected link/UNC/special-name workflows before enabling automated jobs. Verify fresh full and delta syncs, reconnection and all instances before enabling scheduled work. +6. Observe proof/epoch/authorization failures using identifiers and status codes only. Monitor retry behavior, Redis consumption, transfer metadata retention and grant failures. Never add request-body, JWT, private-key, credential or signed-URL logging for diagnostics. + +Old clients fail the challenge/epoch/protocol boundary; claiming a newer software version does not help. Existing sessions, transfers, remote profiles/lobbies and SignalR subscriptions are not silently promoted. The constants are code-level epoch controls; a later epoch requires a coordinated code release and the same operational invalidation steps. + +### Safe rollback + +Keep the strong authentication/authorization boundary active. Roll back to a previously tested V3 build or disable the affected operation/service while correcting it. Preserve keys, trust lists, settings, local grants and profile files; do not downgrade their meaning or auto-import profile paths. Quarantine or expire failed-epoch server state and issue fresh tokens/sessions after recovery. Do not restore an old vulnerable login, lower the minimum protocol/epoch, remove membership checks, or fall back to raw peer paths. If no compatible build exists, fail closed and keep synchronization unavailable until repaired. A deployment/database rollback to the old relay is not a safe security rollback. + +## Residual risks and decisions for Paul + +Approval is still needed for the coordinated downtime and client/relay release; recreation of existing sessions and remote profiles; the initial local source enrollment UX and user communication; rejecting links, UNC sources, hard links, special names and recursive empty-tree deletion; five-minute URL expiry and retained transfer metadata; and the supported native OS/filesystem/architecture matrix. No such rollout decision was executed here. + +The local settings and durable private key remain trusted local state. Malware running as the user, a privileged local filesystem/mount adversary, or a compromised client can alter that state. Native handle/descriptor access prevents following substituted links, but does not promise rollback of already opened I/O or protection against every concurrent directory relocation/mount change. On Unix a directory pinned by descriptor can itself be renamed by another process; operations then refer to the pinned object. Hard links created after the opened-file check, and arbitrary privileged local renames, require a stronger OS isolation policy if they are included in the threat model. Inventory metadata enumeration still uses existing scanner APIs; content reads are constrained, but concurrent Unix metadata enumeration has not been proven race-free. Local revocation blocks subsequent resolutions and transfer slices, not bytes already read or written. + +Relay authorization checks use current repository state before dispatch; they do not make every handler, notification and concurrent membership change one serializable transaction. Final join-proof consumption is locked/transactional. Already issued URLs and in-flight requests retain their bounded capabilities. Distributed state, failover and departure/reconnect races require isolated integration validation. + +HTTP bodies/archives still need a broader resource-abuse budget/rate-limit review. Peer possession proves control of a key, not that the key owner is honest. A session member may still request destructive actions within sources the local user authorized. The relay cannot inspect encrypted file contents. Cryptographic content integrity/AEAD, security-word entropy and update authenticity remain separate tracked work. Existing dependency vulnerability warnings were observed during build; this patch does not update those packages. + +No deployment or production configuration change was performed. The PR and its follow-up commits are hosted on GitHub; no Azure service was tested. Executed validation used local files, synthetic credentials, fakes or offline signing, subject to the OS exclusions and unexecuted integration cases recorded above. diff --git a/src/ByteSync.Client/Assets/Resources/Resources.en.resx b/src/ByteSync.Client/Assets/Resources/Resources.en.resx index 722f831f8..e2e25b058 100644 --- a/src/ByteSync.Client/Assets/Resources/Resources.en.resx +++ b/src/ByteSync.Client/Assets/Resources/Resources.en.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -38,5 +38,14 @@ You must select at least 2 data nodes. Local Inventory not launched + + + Incompatible relay server + + + The relay server does not provide the secure authentication required by this client. Check the relay address or update the relay server. Automatic reconnection has stopped. + + + Renew your key outside a session, after connection attempts have finished. diff --git a/src/ByteSync.Client/Assets/Resources/Resources.fr.resx b/src/ByteSync.Client/Assets/Resources/Resources.fr.resx index bb2186922..87822c752 100644 --- a/src/ByteSync.Client/Assets/Resources/Resources.fr.resx +++ b/src/ByteSync.Client/Assets/Resources/Resources.fr.resx @@ -1831,5 +1831,14 @@ Voulez-vous enregistrer ce nouveau Profil de Session avec ce nom ? ANNULER + + Serveur relais incompatible + + + Le serveur relais ne fournit pas l’authentification sécurisée requise par ce client. Vérifiez l’adresse du relais ou mettez à jour le serveur. La reconnexion automatique est arrêtée. + + + Renouvelez votre clé hors session, une fois les tentatives de connexion terminées. + diff --git a/src/ByteSync.Client/Assets/Resources/Resources.resx b/src/ByteSync.Client/Assets/Resources/Resources.resx index 69dc16029..9f0d76f5f 100644 --- a/src/ByteSync.Client/Assets/Resources/Resources.resx +++ b/src/ByteSync.Client/Assets/Resources/Resources.resx @@ -1856,4 +1856,13 @@ Do you want to save this new Session Profile with this name? CANCEL + + Incompatible relay server + + + The relay server does not provide the secure authentication required by this client. Check the relay address or update the relay server. Automatic reconnection has stopped. + + + Renew your key outside a session, after connection attempts have finished. + diff --git a/src/ByteSync.Client/Business/Actions/Shared/SharedActionsGroup.cs b/src/ByteSync.Client/Business/Actions/Shared/SharedActionsGroup.cs index 6245dee73..f25c7f423 100644 --- a/src/ByteSync.Client/Business/Actions/Shared/SharedActionsGroup.cs +++ b/src/ByteSync.Client/Business/Actions/Shared/SharedActionsGroup.cs @@ -76,17 +76,8 @@ public HashSet GetTargetsFullNames(ByteSyncEndpoint endpoint) public string GetFullName(SharedDataPart sharedDataPart) { - string sourceFileName; - if (sharedDataPart.InventoryPartType == FileSystemTypes.Directory) - { - sourceFileName = IOUtils.Combine(sharedDataPart.RootPath, sharedDataPart.RelativePath!); - } - else - { - sourceFileName = sharedDataPart.RootPath; - } - - return sourceFileName; + return sharedDataPart.LocalPathResolver?.Invoke() + ?? throw new UnauthorizedAccessException("Action has no local source authorization"); } private bool Equals(SharedActionsGroup other) diff --git a/src/ByteSync.Client/Business/Actions/Shared/SharedDataPart.cs b/src/ByteSync.Client/Business/Actions/Shared/SharedDataPart.cs index 4295399be..ba09efba0 100644 --- a/src/ByteSync.Client/Business/Actions/Shared/SharedDataPart.cs +++ b/src/ByteSync.Client/Business/Actions/Shared/SharedDataPart.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.Inventories; +using ByteSync.Common.Business.Inventories; using ByteSync.Models.Inventories; namespace ByteSync.Business.Actions.Shared; @@ -20,6 +20,9 @@ public SharedDataPart(string name, Inventory inventory, InventoryPart inventoryP InventoryCodeAndId = inventory.CodeAndId; NodeId = inventory.NodeId; RootPath = inventoryPart.RootPath; + SourceId = inventoryPart.SourceId; + SourceRelativePath = inventoryPart.InventoryPartType == FileSystemTypes.File ? "" : + (relativePath?.StartsWith('/') == true ? relativePath[1..] : relativePath); RelativePath = relativePath; SignatureGuid = signatureGuid; SignatureHash = signatureHash; @@ -37,6 +40,10 @@ public SharedDataPart(string name, Inventory inventory, InventoryPart inventoryP public string? NodeId { get; set; } public string RootPath { get; set; } = null!; + public string? SourceId { get; set; } + public string? SourceRelativePath { get; set; } + [System.Text.Json.Serialization.JsonIgnore] + public Func? LocalPathResolver { get; set; } public string? RelativePath { get; set; } @@ -48,7 +55,9 @@ public SharedDataPart(string name, Inventory inventory, InventoryPart inventoryP protected bool Equals(SharedDataPart other) { - return Equals(ClientInstanceId, other.ClientInstanceId) && + return Equals(SourceId, other.SourceId) && Equals(NodeId, other.NodeId) && + Equals(SourceRelativePath, other.SourceRelativePath) && + Equals(ClientInstanceId, other.ClientInstanceId) && RootPath.Equals(other.RootPath, StringComparison.InvariantCultureIgnoreCase) && Equals (RelativePath, other.RelativePath); } diff --git a/src/ByteSync.Client/Business/Communications/ConnectionStatuses.cs b/src/ByteSync.Client/Business/Communications/ConnectionStatuses.cs index d914b9a4c..8bc059aee 100644 --- a/src/ByteSync.Client/Business/Communications/ConnectionStatuses.cs +++ b/src/ByteSync.Client/Business/Communications/ConnectionStatuses.cs @@ -7,4 +7,5 @@ public enum ConnectionStatuses Connected = 2, RetryConnectingSoon = 3, ConnectionFailed = 4, -} \ No newline at end of file + RelayIncompatible = 5, +} diff --git a/src/ByteSync.Client/Business/Communications/Downloading/DownloadTarget.cs b/src/ByteSync.Client/Business/Communications/Downloading/DownloadTarget.cs index de207bb3e..f4da8c7b1 100644 --- a/src/ByteSync.Client/Business/Communications/Downloading/DownloadTarget.cs +++ b/src/ByteSync.Client/Business/Communications/Downloading/DownloadTarget.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using ByteSync.Common.Business.SharedFiles; using ByteSync.Interfaces.Controls.Synchronizations; @@ -16,6 +16,14 @@ public DownloadTarget(SharedFileDefinition sharedFileDefinition, LocalSharedFile MemoryStreams = new Dictionary(); } + public Action? ValidateAccess { get; set; } + + public void CheckAccess() + { + if (SharedFileDefinition.IsSynchronization && ValidateAccess == null) throw new UnauthorizedAccessException("Missing download authorization"); + ValidateAccess?.Invoke(); + } + public SharedFileDefinition SharedFileDefinition { get; set; } public LocalSharedFile? LocalSharedFile { get; } diff --git a/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/PeerTrustProcessData.cs b/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/PeerTrustProcessData.cs index 7af6fe332..de2e77bdd 100644 --- a/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/PeerTrustProcessData.cs +++ b/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/PeerTrustProcessData.cs @@ -1,4 +1,4 @@ -using System.Threading; +using System.Threading; namespace ByteSync.Business.Communications.PublicKeysTrusting; @@ -19,6 +19,19 @@ public PeerTrustProcessData(string otherPartyClientId) SyncRoot = new object(); } + public PeerTrustProcessData(ByteSync.Common.Business.EndPoints.PublicKeyCheckData peer) : this(peer.IssuerPublicKeyInfo.ClientId) + { + OtherPartyIdentity = ByteSync.Common.Business.Auth.AuthenticationProtocol.GetIdentity(peer.IssuerPublicKeyInfo.PublicKey); + OtherPartyClientInstanceId = peer.IssuerClientInstanceId; + ExchangeId = peer.Salt; + if (!ByteSync.Common.Business.Auth.AuthenticationProtocol.IsInstanceOf(OtherPartyClientInstanceId, OtherPartyIdentity) || + string.IsNullOrWhiteSpace(ExchangeId) || ExchangeId.Length > 128) + throw new ArgumentException("Invalid peer trust exchange", nameof(peer)); + } + + public string? OtherPartyClientInstanceId { get; } + public string? OtherPartyIdentity { get; } + public string? ExchangeId { get; } public string OtherPartyClientId { get; } public bool HasOtherPartyValidatedPublicKey diff --git a/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/TrustProcessPublicKeysData.cs b/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/TrustProcessPublicKeysData.cs index 901903bef..2725f3f80 100644 --- a/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/TrustProcessPublicKeysData.cs +++ b/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/TrustProcessPublicKeysData.cs @@ -1,6 +1,4 @@ -using Serilog; - -namespace ByteSync.Business.Communications.PublicKeysTrusting; +namespace ByteSync.Business.Communications.PublicKeysTrusting; public class TrustProcessPublicKeysData { @@ -23,26 +21,22 @@ public TrustProcessPublicKeysData(string sessionId) public SessionMemberTrustProcessData SessionMemberTrustProcessData { get; } - public void AddPeerTrustProcessData(PeerTrustProcessData peerTrustProcessData) + public PeerTrustProcessData AddPeerTrustProcessData(PeerTrustProcessData peer) { - if (PeerTrustProcessDatas.ContainsKey(peerTrustProcessData.OtherPartyClientId)) - { - PeerTrustProcessDatas.Remove(peerTrustProcessData.OtherPartyClientId); - } - - PeerTrustProcessDatas.Add(peerTrustProcessData.OtherPartyClientId, peerTrustProcessData); + var instance = peer.OtherPartyClientInstanceId!; + if (PeerTrustProcessDatas.TryGetValue(instance, out var existing) && + existing.OtherPartyIdentity == peer.OtherPartyIdentity && existing.ExchangeId == peer.ExchangeId) + return existing; + PeerTrustProcessDatas[instance] = peer; + return peer; } - public void SetOtherPartyChecked(string issuerClientId, bool isValidated) + public void SetOtherPartyChecked(ByteSync.Common.Business.Sessions.Cloud.Connections.PublicKeyValidationParameters parameters) { - PeerTrustProcessData? peerTrustProcessData; - if (PeerTrustProcessDatas.TryGetValue(issuerClientId, out peerTrustProcessData)) - { - peerTrustProcessData.SetOtherPartyChecked(isValidated); - } - else - { - Log.Warning("Can not find PeerTrustProcessData with ClientId {issuerClientId}", issuerClientId); - } + if (parameters.IssuerClientInstanceId != null && + PeerTrustProcessDatas.TryGetValue(parameters.IssuerClientInstanceId, out var peer) && + peer.OtherPartyIdentity == parameters.IssuerIdentity && peer.ExchangeId == parameters.ExchangeId && + !peer.OtherPartyHasFinished()) + peer.SetOtherPartyChecked(parameters.IsValidated); } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/Business/Configurations/ApplicationSettings.cs b/src/ByteSync.Client/Business/Configurations/ApplicationSettings.cs index 6672358f9..c3d950927 100644 --- a/src/ByteSync.Client/Business/Configurations/ApplicationSettings.cs +++ b/src/ByteSync.Client/Business/Configurations/ApplicationSettings.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.ObjectModel; using System.Security.Cryptography; using System.Text.RegularExpressions; @@ -11,6 +11,8 @@ namespace ByteSync.Business.Configurations; public class ApplicationSettings : ICloneable { + public List LocalSourcePermissions { get; set; } = new(); + private string? _rsaPrivateKey; public ApplicationSettings() @@ -229,7 +231,9 @@ public List DecodedAcknowledgedAnnouncementIds public object Clone() { - return this.MemberwiseClone(); + var clone = (ApplicationSettings)MemberwiseClone(); + clone.LocalSourcePermissions = LocalSourcePermissions.Select(p => p with { }).ToList(); + return clone; } public void SetEncryptionPassword(string encryptionPassword) diff --git a/src/ByteSync.Client/Business/DataSources/LocalSourcePermission.cs b/src/ByteSync.Client/Business/DataSources/LocalSourcePermission.cs new file mode 100644 index 000000000..6185339cb --- /dev/null +++ b/src/ByteSync.Client/Business/DataSources/LocalSourcePermission.cs @@ -0,0 +1,12 @@ +using ByteSync.Common.Business.Inventories; + +namespace ByteSync.Business.DataSources; + +public record LocalSourcePermission +{ + public LocalSourcePermission() { } + public LocalSourcePermission(string identity, string path, FileSystemTypes type) { Identity = identity; Path = path; Type = type; } + public string Identity { get; set; } = ""; + public string Path { get; set; } = ""; + public FileSystemTypes Type { get; set; } +} diff --git a/src/ByteSync.Client/Business/Synchronizations/MultiUploadZip.cs b/src/ByteSync.Client/Business/Synchronizations/MultiUploadZip.cs index 09af56f16..665408991 100644 --- a/src/ByteSync.Client/Business/Synchronizations/MultiUploadZip.cs +++ b/src/ByteSync.Client/Business/Synchronizations/MultiUploadZip.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.IO.Compression; using ByteSync.Common.Business.Misc; using ByteSync.Common.Business.SharedFiles; @@ -28,6 +28,7 @@ public MultiUploadZip(string key, SharedFileDefinition sharedFileDefinition) ActionsGroupIdsConcatenationLength = 0; } + public List AccessValidators { get; } = new(); public string Key { get; } public SharedFileDefinition SharedFileDefinition { get; } @@ -57,7 +58,8 @@ public bool CanAdd(FileInfo fileInfo, string actionsGroupId) public void AddEntry(FileInfo fileInfo, string actionsGroupId) { // https://stackoverflow.com/questions/22339260/how-do-i-add-files-to-an-existing-zip-archive - ZipArchive.CreateEntryFromFile(fileInfo.FullName, actionsGroupId, CompressionLevel.Fastest); + using (var input = ByteSync.Services.Synchronizations.LocalPathSafety.OpenRead(fileInfo.FullName)) + using (var output = ZipArchive.CreateEntry(actionsGroupId, CompressionLevel.Fastest).Open()) input.CopyTo(output); ActionGroupsIds.Add(actionsGroupId); FilesFullNames.Add(fileInfo.FullName); diff --git a/src/ByteSync.Client/DependencyInjection/ServiceRegistrar.cs b/src/ByteSync.Client/DependencyInjection/ServiceRegistrar.cs index d7712b31e..6685b7ca7 100644 --- a/src/ByteSync.Client/DependencyInjection/ServiceRegistrar.cs +++ b/src/ByteSync.Client/DependencyInjection/ServiceRegistrar.cs @@ -1,4 +1,4 @@ -using Autofac; +using Autofac; using Avalonia.ReactiveUI; using ByteSync.Business.Arguments; using ByteSync.DependencyInjection.Modules; @@ -86,7 +86,8 @@ private static void FeedClientId(this IContainer container) var environmentService = scope.Resolve(); var applicationSettings = applicationSettingsRepository.GetCurrentApplicationSettings(); - environmentService.SetClientId(applicationSettings.ClientId); + environmentService.SetClientIdentity(applicationSettings.ClientId, + ByteSync.Common.Business.Auth.AuthenticationProtocol.GetIdentity(applicationSettings.DecodedRsaPublicKey!)); } private static void LogBootstrapHeader(this IContainer container) @@ -104,4 +105,4 @@ private static void LogBootstrap(this IContainer container) var logger = scope.Resolve(); logger.LogBootstrapContent(); } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/Exceptions/RelayIncompatibleException.cs b/src/ByteSync.Client/Exceptions/RelayIncompatibleException.cs new file mode 100644 index 000000000..3b2afc7c6 --- /dev/null +++ b/src/ByteSync.Client/Exceptions/RelayIncompatibleException.cs @@ -0,0 +1,10 @@ +namespace ByteSync.Exceptions; + +public sealed class RelayIncompatibleException : BuildConnectionException +{ + public RelayIncompatibleException(Exception innerException) + : base("The relay returned HTTP 404 for auth/challenge, which is required for this client's secure authentication. " + + "Check the relay address or update the relay server. Automatic reconnection has stopped.", innerException) + { + } +} diff --git a/src/ByteSync.Client/Factories/InventoryBuilderFactory.cs b/src/ByteSync.Client/Factories/InventoryBuilderFactory.cs index daa517ac8..90d5706e4 100644 --- a/src/ByteSync.Client/Factories/InventoryBuilderFactory.cs +++ b/src/ByteSync.Client/Factories/InventoryBuilderFactory.cs @@ -1,4 +1,4 @@ -using Autofac; +using Autofac; using ByteSync.Business; using ByteSync.Business.DataNodes; using ByteSync.Business.Inventories; @@ -59,6 +59,7 @@ public IInventoryBuilder CreateInventoryBuilder(DataNode dataNode) { try { + _context.Resolve().CheckNetworkSource(dataSource, dataSource.ClientInstanceId); inventoryBuilder.AddInventoryPart(dataSource); } catch (Exception ex) diff --git a/src/ByteSync.Client/Interfaces/Controls/Applications/IEnvironmentService.cs b/src/ByteSync.Client/Interfaces/Controls/Applications/IEnvironmentService.cs index 5ef88fe5c..44b025001 100644 --- a/src/ByteSync.Client/Interfaces/Controls/Applications/IEnvironmentService.cs +++ b/src/ByteSync.Client/Interfaces/Controls/Applications/IEnvironmentService.cs @@ -19,7 +19,7 @@ public interface IEnvironmentService public bool IsAutoRunProfile(); - public void SetClientId(string clientId); + public void SetClientIdentity(string clientId, string identity); string AssemblyFullName { get; } @@ -35,5 +35,7 @@ public interface IEnvironmentService string ClientId { get; } + string Identity { get; } + string ClientInstanceId { get; } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/Interfaces/Controls/Communications/Http/ICloudSessionApiClient.cs b/src/ByteSync.Client/Interfaces/Controls/Communications/Http/ICloudSessionApiClient.cs index 5e25ac095..403455edc 100644 --- a/src/ByteSync.Client/Interfaces/Controls/Communications/Http/ICloudSessionApiClient.cs +++ b/src/ByteSync.Client/Interfaces/Controls/Communications/Http/ICloudSessionApiClient.cs @@ -1,4 +1,4 @@ -using System.Threading; +using System.Threading; using System.Threading.Tasks; using ByteSync.Common.Business.Sessions; using ByteSync.Common.Business.Sessions.Cloud; @@ -14,6 +14,8 @@ public interface ICloudSessionApiClient Task ResetCloudSession(string sessionId); + Task> BeginJoin(AskCloudSessionPasswordExchangeKeyParameters parameters, CancellationToken cancellationToken = default); + Task AskPasswordExchangeKey(AskCloudSessionPasswordExchangeKeyParameters parameters, CancellationToken cancellationToken = default); diff --git a/src/ByteSync.Client/Interfaces/Controls/Communications/IFileUploader.cs b/src/ByteSync.Client/Interfaces/Controls/Communications/IFileUploader.cs index 7ee7e4d84..3d36f02bc 100644 --- a/src/ByteSync.Client/Interfaces/Controls/Communications/IFileUploader.cs +++ b/src/ByteSync.Client/Interfaces/Controls/Communications/IFileUploader.cs @@ -1,8 +1,9 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; namespace ByteSync.Interfaces.Controls.Communications; public interface IFileUploader { + Action? ValidateAccess { get; set; } Task Upload(); } \ No newline at end of file diff --git a/src/ByteSync.Client/Interfaces/Controls/Communications/IPublicKeysManager.cs b/src/ByteSync.Client/Interfaces/Controls/Communications/IPublicKeysManager.cs index df3abbee8..48e205e7b 100644 --- a/src/ByteSync.Client/Interfaces/Controls/Communications/IPublicKeysManager.cs +++ b/src/ByteSync.Client/Interfaces/Controls/Communications/IPublicKeysManager.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using ByteSync.Business.Communications; using ByteSync.Common.Business.EndPoints; @@ -24,7 +24,7 @@ public interface IPublicKeysManager void Delete(TrustedPublicKey trustedPublicKey); - void InitializeRsaAndTrustedPublicKeys(); + Task InitializeRsaAndTrustedPublicKeys(); byte[] DecryptBytes(byte[] messageToEncrypt); diff --git a/src/ByteSync.Client/Interfaces/Controls/Communications/ITrustProcessPublicKeysRepository.cs b/src/ByteSync.Client/Interfaces/Controls/Communications/ITrustProcessPublicKeysRepository.cs index 1e18a3992..9dcd4756a 100644 --- a/src/ByteSync.Client/Interfaces/Controls/Communications/ITrustProcessPublicKeysRepository.cs +++ b/src/ByteSync.Client/Interfaces/Controls/Communications/ITrustProcessPublicKeysRepository.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.Threading.Tasks; using ByteSync.Business.Communications.PublicKeysTrusting; using ByteSync.Common.Business.EndPoints; @@ -17,7 +17,7 @@ public interface ITrustProcessPublicKeysRepository : IRepository IsFullyTrusted(string sessionId, string memberInstanceId); - Task ResetPeerTrustProcessData(string sessionId, string otherPartyClientId); + Task ResetPeerTrustProcessData(string sessionId, PublicKeyCheckData peer); Task ResetJoinerTrustProcessData(string sessionId); diff --git a/src/ByteSync.Client/Interfaces/Controls/Encryptions/ISlicerEncrypter.cs b/src/ByteSync.Client/Interfaces/Controls/Encryptions/ISlicerEncrypter.cs index ece38f935..1a55ffa35 100644 --- a/src/ByteSync.Client/Interfaces/Controls/Encryptions/ISlicerEncrypter.cs +++ b/src/ByteSync.Client/Interfaces/Controls/Encryptions/ISlicerEncrypter.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Threading.Tasks; using ByteSync.Business.Communications.Transfers; using ByteSync.Common.Business.SharedFiles; @@ -7,6 +7,8 @@ namespace ByteSync.Interfaces.Controls.Encryptions; public interface ISlicerEncrypter : IDisposable { + Action? ValidateAccess { get; set; } + void Initialize(FileInfo fileToEncrypt, SharedFileDefinition sharedFileDefinition); void Initialize(MemoryStream fileToEncrypt, SharedFileDefinition sharedFileDefinition); diff --git a/src/ByteSync.Client/Interfaces/Controls/Inventories/IDataSourceService.cs b/src/ByteSync.Client/Interfaces/Controls/Inventories/IDataSourceService.cs index 08690548a..fd4266cbc 100644 --- a/src/ByteSync.Client/Interfaces/Controls/Inventories/IDataSourceService.cs +++ b/src/ByteSync.Client/Interfaces/Controls/Inventories/IDataSourceService.cs @@ -1,4 +1,4 @@ -using ByteSync.Business.DataNodes; +using ByteSync.Business.DataNodes; using ByteSync.Business.DataSources; using ByteSync.Common.Business.Inventories; @@ -7,6 +7,7 @@ namespace ByteSync.Interfaces.Controls.Inventories; public interface IDataSourceService { Task TryAddDataSource(DataSource dataSource); + Task RestoreDataSource(string path, FileSystemTypes type, DataNode node); Task CreateAndTryAddDataSource(string path, FileSystemTypes fileSystemType, DataNode dataNode); diff --git a/src/ByteSync.Client/Interfaces/Controls/Inventories/ILocalSourceAuthorizationService.cs b/src/ByteSync.Client/Interfaces/Controls/Inventories/ILocalSourceAuthorizationService.cs new file mode 100644 index 000000000..24413bd6d --- /dev/null +++ b/src/ByteSync.Client/Interfaces/Controls/Inventories/ILocalSourceAuthorizationService.cs @@ -0,0 +1,15 @@ +using ByteSync.Business.Actions.Shared; +using ByteSync.Business.DataSources; + +namespace ByteSync.Interfaces.Controls.Inventories; + +public interface ILocalSourceAuthorizationService +{ + void Grant(DataSource source, bool restoreOnly = false); + void Revoke(DataSource source); + void CheckNetworkSource(DataSource source, string sender); + string Resolve(SharedDataPart part); + void ValidatePlan(IEnumerable groups); + void ValidatePath(string path); + void ValidateDestination(SharedActionsGroup group, string destination); +} diff --git a/src/ByteSync.Client/Interfaces/Services/Communications/IAuthenticationTokensRepository.cs b/src/ByteSync.Client/Interfaces/Services/Communications/IAuthenticationTokensRepository.cs index daac9eff4..01fc31d25 100644 --- a/src/ByteSync.Client/Interfaces/Services/Communications/IAuthenticationTokensRepository.cs +++ b/src/ByteSync.Client/Interfaces/Services/Communications/IAuthenticationTokensRepository.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using ByteSync.Common.Business.Auth; namespace ByteSync.Interfaces.Services.Communications; @@ -8,4 +8,6 @@ public interface IAuthenticationTokensRepository Task GetTokens(); Task Store(AuthenticationTokens authenticationTokens); + + Task Clear(); } \ No newline at end of file diff --git a/src/ByteSync.Client/Interfaces/Services/Communications/IConnectionService.cs b/src/ByteSync.Client/Interfaces/Services/Communications/IConnectionService.cs index 6b54b17d0..e1ee40a5d 100644 --- a/src/ByteSync.Client/Interfaces/Services/Communications/IConnectionService.cs +++ b/src/ByteSync.Client/Interfaces/Services/Communications/IConnectionService.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using ByteSync.Business.Communications; using ByteSync.Common.Business.EndPoints; using Microsoft.AspNetCore.SignalR.Client; @@ -17,6 +17,8 @@ public interface IConnectionService string? ClientInstanceId { get; } + bool IsStarting { get; } + Task StartConnectionAsync(); Task StopConnection(); diff --git a/src/ByteSync.Client/Models/Inventories/InventoryPart.cs b/src/ByteSync.Client/Models/Inventories/InventoryPart.cs index c2ebbe6bd..360082b85 100644 --- a/src/ByteSync.Client/Models/Inventories/InventoryPart.cs +++ b/src/ByteSync.Client/Models/Inventories/InventoryPart.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.Inventories; +using ByteSync.Common.Business.Inventories; using ByteSync.Common.Business.Misc; using ByteSync.Models.FileSystems; @@ -23,6 +23,8 @@ public InventoryPart(Inventory inventory, string rootPath, FileSystemTypes inven public Inventory Inventory { get; set; } public string RootPath { get; set; } + + public string? SourceId { get; set; } public FileSystemTypes InventoryPartType { get; set; } diff --git a/src/ByteSync.Client/Services/Actions/SynchronizationDataSaver.cs b/src/ByteSync.Client/Services/Actions/SynchronizationDataSaver.cs index 19d582f01..628c19428 100644 --- a/src/ByteSync.Client/Services/Actions/SynchronizationDataSaver.cs +++ b/src/ByteSync.Client/Services/Actions/SynchronizationDataSaver.cs @@ -14,7 +14,7 @@ public SynchronizationDataSaver() public void Save(string localPath, SharedSynchronizationStartData sharedSynchronizationStartData) { - using ZipArchive zipArchive = ZipFile.Open(localPath, ZipArchiveMode.Create); + using ZipArchive zipArchive = new ZipArchive(ByteSync.Services.Synchronizations.LocalPathSafety.OpenWrite(localPath), ZipArchiveMode.Create); string json = JsonHelper.Serialize(sharedSynchronizationStartData); @@ -27,7 +27,7 @@ public void Save(string localPath, SharedSynchronizationStartData sharedSynchron public SharedSynchronizationStartData Load(string localPath) { - using ZipArchive zipArchive = ZipFile.OpenRead(localPath); + using ZipArchive zipArchive = new ZipArchive(ByteSync.Services.Synchronizations.LocalPathSafety.OpenRead(localPath), ZipArchiveMode.Read); var synchronizationActionsFile = zipArchive.GetEntry("synchronization_start_data.json"); diff --git a/src/ByteSync.Client/Services/Applications/EnvironmentService.cs b/src/ByteSync.Client/Services/Applications/EnvironmentService.cs index 16e1450c8..dd9101543 100644 --- a/src/ByteSync.Client/Services/Applications/EnvironmentService.cs +++ b/src/ByteSync.Client/Services/Applications/EnvironmentService.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.InteropServices; using ByteSync.Business.Arguments; using ByteSync.Business.Misc; @@ -29,6 +29,8 @@ public EnvironmentService(IMsixPfnParser msixPfnParser) } public string ClientId { get; private set; } = null!; + + public string Identity { get; private set; } = null!; public string ClientInstanceId { get; private set; } = null!; @@ -227,9 +229,13 @@ public Version ApplicationVersion } } - public void SetClientId(string clientId) + public void SetClientIdentity(string clientId, string identity) { + ArgumentException.ThrowIfNullOrWhiteSpace(clientId); + if (identity == null || !ByteSync.Common.Business.Auth.AuthenticationProtocol.IsInstanceOf($"{identity}_{Guid.Empty:D}", identity)) + throw new ArgumentException("A full RSA key fingerprint is required", nameof(identity)); ClientId = clientId; - ClientInstanceId = $"{ClientId}_{Guid.NewGuid():D}"; + Identity = identity; + ClientInstanceId = $"{Identity}_{Guid.NewGuid():D}"; } } diff --git a/src/ByteSync.Client/Services/Communications/Api/ApiInvoker.cs b/src/ByteSync.Client/Services/Communications/Api/ApiInvoker.cs index e272887b2..0b244e287 100644 --- a/src/ByteSync.Client/Services/Communications/Api/ApiInvoker.cs +++ b/src/ByteSync.Client/Services/Communications/Api/ApiInvoker.cs @@ -58,16 +58,21 @@ private async Task DoInvokeRestAsync(HttpMethod httpMethod, string resourc object? requestObject, bool handleResult, CancellationToken cancellationToken) { using var request = await BuildRequest(httpMethod, resource, additionalHeaders, requestObject); + HttpStatusCode? responseStatusCode = null; try { - var response = await _httpClient.SendAsync(request, cancellationToken); + using var response = await _httpClient.SendAsync(request, cancellationToken); + responseStatusCode = response.StatusCode; return await HandleResponse(handleResult, response); } catch (Exception ex) { _logger.LogError(ex, "Exception occurred while invoking API: {Resource}", resource); - throw new ApiException($"An error occurred while invoking the API on resource {resource}", ex); + throw new ApiException($"An error occurred while invoking the API on resource {resource}", ex) + { + HttpStatusCode = responseStatusCode ?? (ex as ApiException)?.HttpStatusCode + }; } } @@ -124,7 +129,7 @@ private async Task HandleResponse(bool handleResult, HttpResponseMessage r errorMessage += $" Reason: {response.ReasonPhrase}"; } - if (!ApiResponseContentHelper.IsEmptyContent(content) && handleResult) + if (response.StatusCode != HttpStatusCode.NotFound && !ApiResponseContentHelper.IsEmptyContent(content) && handleResult) { return DeserializeContent(content); } @@ -152,4 +157,4 @@ private T DeserializeContent(string content) throw new ApiException("Failed to deserialize the response content.", ex); } } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs b/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs index ed2876265..f8fbb72ab 100644 --- a/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs +++ b/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs @@ -1,6 +1,11 @@ -using System.Runtime.CompilerServices; +using System.Net; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using ByteSync.Interfaces; +using ByteSync.Common.Business.Versions; using System.Threading.Tasks; using ByteSync.Common.Business.Auth; +using ByteSync.Exceptions; using ByteSync.Interfaces.Controls.Communications.Http; using Serilog; @@ -10,15 +15,28 @@ public class AuthApiClient : IAuthApiClient { private readonly IApiInvoker _apiInvoker; - public AuthApiClient(IApiInvoker apiInvoker) + private readonly IApplicationSettingsRepository _settings; + + public AuthApiClient(IApiInvoker apiInvoker, IApplicationSettingsRepository settings) { _apiInvoker = apiInvoker!; + _settings = settings; } public async Task Login(LoginData loginData) { try { + var settings = _settings.GetCurrentApplicationSettings(); + loginData.ClientId = settings.ClientId; + loginData.PublicKey = settings.DecodedRsaPublicKey!; + loginData.Identity = AuthenticationProtocol.GetIdentity(loginData.PublicKey); + loginData.AuthenticationEpoch = AuthenticationProtocol.Epoch; + loginData.ProtocolVersion = ProtocolVersion.CURRENT; + var challenge = await GetChallenge(loginData); + loginData.ChallengeId = challenge.Id; + loginData.Signature = settings.PrivateRsa.SignData(AuthenticationProtocol.GetMessage(loginData, challenge), + HashAlgorithmName.SHA256, RSASignaturePadding.Pss); var result = await _apiInvoker.PostAsync($"auth/login", loginData); return result; @@ -31,6 +49,34 @@ public AuthApiClient(IApiInvoker apiInvoker) } } + private async Task GetChallenge(LoginData loginData) + { + try + { + return await _apiInvoker.PostAsync("auth/challenge", loginData) + ?? throw new CryptographicException("Missing authentication challenge"); + } + catch (ApiException ex) when (IsNotFound(ex)) + { + throw new RelayIncompatibleException(ex); + } + } + + private static bool IsNotFound(Exception? exception) + { + while (exception != null) + { + if (exception is ApiException { HttpStatusCode: HttpStatusCode.NotFound }) + { + return true; + } + + exception = exception.InnerException; + } + + return false; + } + public async Task RefreshAuthenticationTokens(RefreshTokensData refreshTokensData) { try @@ -52,4 +98,4 @@ private void LogError(Exception exception, [CallerMemberName] string caller = "" // ReSharper disable once TemplateIsNotCompileTimeConstantProblem Log.Error(exception, caller); } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/Services/Communications/Api/CloudSessionApiClient.cs b/src/ByteSync.Client/Services/Communications/Api/CloudSessionApiClient.cs index 6bee9df69..174afcbf9 100644 --- a/src/ByteSync.Client/Services/Communications/Api/CloudSessionApiClient.cs +++ b/src/ByteSync.Client/Services/Communications/Api/CloudSessionApiClient.cs @@ -1,4 +1,4 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using ByteSync.Common.Business.Sessions; @@ -62,6 +62,12 @@ public async Task ResetCloudSession(string sessionId) } } + public async Task> BeginJoin(AskCloudSessionPasswordExchangeKeyParameters parameters, CancellationToken cancellationToken = default) + { + return await _apiInvoker.PostAsync>($"session/{parameters.SessionId}/beginJoin", parameters, cancellationToken) + ?? throw new UnauthorizedAccessException("Join attempt could not be created"); + } + public async Task AskPasswordExchangeKey(AskCloudSessionPasswordExchangeKeyParameters parameters, CancellationToken cancellationToken = default) { diff --git a/src/ByteSync.Client/Services/Communications/AuthenticationTokensRepository.cs b/src/ByteSync.Client/Services/Communications/AuthenticationTokensRepository.cs index af2ad67f5..3d51a09fe 100644 --- a/src/ByteSync.Client/Services/Communications/AuthenticationTokensRepository.cs +++ b/src/ByteSync.Client/Services/Communications/AuthenticationTokensRepository.cs @@ -1,4 +1,4 @@ -using System.Threading; +using System.Threading; using System.Threading.Tasks; using ByteSync.Common.Business.Auth; using ByteSync.Interfaces.Services.Communications; @@ -24,6 +24,13 @@ public class AuthenticationTokensRepository : IAuthenticationTokensRepository } } + public async Task Clear() + { + await _semaphore.WaitAsync(); + try { _tokens = null; } + finally { _semaphore.Release(); } + } + public async Task Store(AuthenticationTokens authenticationTokens) { var clone = authenticationTokens.Clone() as AuthenticationTokens; diff --git a/src/ByteSync.Client/Services/Communications/ConnectionService.cs b/src/ByteSync.Client/Services/Communications/ConnectionService.cs index 1979dfc06..ea239f6ff 100644 --- a/src/ByteSync.Client/Services/Communications/ConnectionService.cs +++ b/src/ByteSync.Client/Services/Communications/ConnectionService.cs @@ -21,6 +21,10 @@ public class ConnectionService : IConnectionService, IDisposable private readonly IDisposable? _connectionSubscription; private CancellationTokenSource? _refreshCancellationTokenSource; + private readonly object _refreshGate = new(); + private readonly SemaphoreSlim _lifecycleGate = new(1, 1); + private Task? _refreshOperation; + public bool IsStarting { get; private set; } public ConnectionService(IConnectionFactory connectionFactory, IAuthenticationTokensRepository authenticationTokensRepository, ILogger logger) @@ -68,12 +72,15 @@ public ConnectionService(IConnectionFactory connectionFactory, IAuthenticationTo public Func? RetryDelaySleepDurationProvider { get; set; } - public async Task StartConnectionAsync() + public Task StartConnectionAsync() => StartConnectionCore(false); + + private async Task StartConnectionCore(bool lifecycleHeld) { var retryDelaySleepDurationProvider = RetryDelaySleepDurationProvider; var retryPolicy = Policy - .Handle(ex => !(ex is BuildConnectionException bce && bce.InitialConnectionStatus == InitialConnectionStatus.VersionNotAllowed)) + .Handle(ex => ex is not RelayIncompatibleException && + !(ex is BuildConnectionException bce && bce.InitialConnectionStatus is InitialConnectionStatus.VersionNotAllowed or InitialConnectionStatus.InvalidProof)) .WaitAndRetryForeverAsync( retryAttempt => retryDelaySleepDurationProvider?.Invoke(retryAttempt) ?? TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (exception, _, _) => @@ -83,35 +90,51 @@ public async Task StartConnectionAsync() _logger.LogError(exception, "An error occurred while starting the connection"); }); - - await retryPolicy.ExecuteAsync(async () => + + if (IsStarting) throw new InvalidOperationException("Connection is already starting"); + IsStarting = true; + try { - _logger.LogInformation("Starting connection"); + await retryPolicy.ExecuteAsync(async () => + { + _logger.LogInformation("Starting connection"); - ConnectionStatusSubject.OnNext(ConnectionStatuses.Connecting); + ConnectionStatusSubject.OnNext(ConnectionStatuses.Connecting); - var result = await _connectionFactory.BuildConnection(); - - ConnectionSubject.OnNext(result.HubConnection); - - if (result.HubConnection != null) - { - CurrentEndPoint = result.EndPoint!; - - ConnectionStatusSubject.OnNext(ConnectionStatuses.Connected); - } - else - { - if (result.AuthenticateResponseStatus == InitialConnectionStatus.VersionNotAllowed) + var result = await _connectionFactory.BuildConnection(); + + ConnectionSubject.OnNext(result.HubConnection); + + if (result.HubConnection != null) { - ConnectionStatusSubject.OnNext(ConnectionStatuses.NotConnected); + CurrentEndPoint = result.EndPoint!; + + IsStarting = false; + ConnectionStatusSubject.OnNext(ConnectionStatuses.Connected); } - - throw new BuildConnectionException("Unable to connect", result.AuthenticateResponseStatus); - } - }); + else + { + if (result.AuthenticateResponseStatus is InitialConnectionStatus.VersionNotAllowed or InitialConnectionStatus.InvalidProof) + { + ConnectionStatusSubject.OnNext(ConnectionStatuses.NotConnected); + } + + throw new BuildConnectionException("Unable to connect", result.AuthenticateResponseStatus); + } + }); + } + catch (RelayIncompatibleException ex) + { + if (lifecycleHeld) await StopConnectionCore(); + else await StopConnection(); + CurrentEndPoint = null; + ConnectionStatusSubject.OnNext(ConnectionStatuses.RelayIncompatible); + _logger.LogError(ex, "{RelayCompatibilityError}", ex.Message); + throw; + } + finally { IsStarting = false; } } - + private async Task StartOrRestartJwtTokensRefreshTimer() { await CancelCurrentRefreshCancellationTokenSource(); @@ -133,12 +156,13 @@ private async Task StartOrRestartJwtTokensRefreshTimer() try { - await RefreshJwtTokens(); + await RefreshJwtTokens(cancellationToken); } catch (Exception ex) { + if (cancellationToken.IsCancellationRequested) break; _logger.LogError(ex, "An error occurred while refreshing JWT tokens"); - await RestartConnection(); + await RestartConnection(cancellationToken); } } } @@ -157,10 +181,10 @@ private async Task StartOrRestartJwtTokensRefreshTimer() } } - private async Task RefreshJwtTokens() + private async Task RefreshJwtTokens(CancellationToken cancellationToken) { var retryPolicy = Policy - .Handle(ex => !(ex is HttpRequestException httpRequestException && httpRequestException.Message.Contains("401"))) + .Handle(ex => ex is not OperationCanceledException && !(ex is HttpRequestException httpRequestException && httpRequestException.Message.Contains("401"))) .Or(ex => !ex.Message.Contains("401")) .WaitAndRetryAsync(5, _ => TimeSpan.FromSeconds(10), @@ -169,11 +193,19 @@ private async Task RefreshJwtTokens() _logger.LogError(exception, "Attempt {CurrentAttempt}: An error occurred while refreshing jwt tokens", currentAttempt); }); - await retryPolicy.ExecuteAsync(async () => + await retryPolicy.ExecuteAsync(async _ => { + cancellationToken.ThrowIfCancellationRequested(); _logger.LogInformation("Start refreshing jwt tokens"); - var refreshTokens = await _connectionFactory.RefreshAuthenticationTokens(); + Task operation; + lock (_refreshGate) + { + cancellationToken.ThrowIfCancellationRequested(); + operation = _refreshOperation = _connectionFactory.RefreshAuthenticationTokens(); + } + var refreshTokens = await operation; + cancellationToken.ThrowIfCancellationRequested(); if (refreshTokens) { _logger.LogInformation("successfully refreshed jwt tokens"); @@ -182,12 +214,19 @@ await retryPolicy.ExecuteAsync(async () => { _logger.LogWarning("failed to refresh jwt tokens"); - _ = RestartConnection(); + await RestartConnection(cancellationToken); } - }); + }, cancellationToken); } public async Task StopConnection() + { + await _lifecycleGate.WaitAsync(); + try { await StopConnectionCore(); } + finally { _lifecycleGate.Release(); } + } + + private async Task StopConnectionCore() { await CancelCurrentRefreshCancellationTokenSource(); @@ -201,6 +240,7 @@ public async Task StopConnection() catch (Exception e) { _logger.LogError(e, "An error occurred while stopping the connection"); + throw; } } @@ -214,20 +254,31 @@ public void Dispose() _refreshCancellationTokenSource?.Dispose(); } - private async Task RestartConnection() + private async Task RestartConnection(CancellationToken cancellationToken) { - await StopConnection(); - await StartConnectionAsync(); + await _lifecycleGate.WaitAsync(); + try + { + if (cancellationToken.IsCancellationRequested || CurrentConnectionStatus == ConnectionStatuses.RelayIncompatible) + return; + await StopConnectionCore(); + await StartConnectionCore(true); + } + finally { _lifecycleGate.Release(); } } - - private Task CancelCurrentRefreshCancellationTokenSource() + + private async Task CancelCurrentRefreshCancellationTokenSource() { - var currentRefreshCancellationTokenSource = _refreshCancellationTokenSource; - if (currentRefreshCancellationTokenSource != null) + Task? operation; + lock (_refreshGate) { - _ = currentRefreshCancellationTokenSource.CancelAsync(); + _refreshCancellationTokenSource?.Cancel(); + operation = _refreshOperation; + } + if (operation != null) + { + try { await operation; } + catch (Exception ex) { _logger.LogDebug(ex, "Previous token refresh ended while stopping the connection"); } } - - return Task.CompletedTask; } } diff --git a/src/ByteSync.Client/Services/Communications/PublicKeysManager.cs b/src/ByteSync.Client/Services/Communications/PublicKeysManager.cs index 0875b6d70..1b288722e 100644 --- a/src/ByteSync.Client/Services/Communications/PublicKeysManager.cs +++ b/src/ByteSync.Client/Services/Communications/PublicKeysManager.cs @@ -1,4 +1,10 @@ -using System.Collections.ObjectModel; +using System.Threading; +using ByteSync.Common.Business.Auth; +using ByteSync.Business.Sessions; +using ByteSync.Interfaces.Controls.Applications; +using ByteSync.Interfaces.Repositories; +using ByteSync.Interfaces.Services.Sessions; +using System.Collections.ObjectModel; using System.Security.Cryptography; using System.Text; using ByteSync.Business.Communications; @@ -16,13 +22,23 @@ public class PublicKeysManager : IPublicKeysManager private readonly IApplicationSettingsRepository _applicationSettingsRepository; private readonly IConnectionService _connectionService; private readonly ILogger _logger; + private readonly IEnvironmentService _environment; + private readonly IAuthenticationTokensRepository _tokens; + private readonly Lazy _session; + private readonly ICloudSessionConnectionRepository _sessionConnection; + private readonly SemaphoreSlim _renewalGate = new(1, 1); public PublicKeysManager(IApplicationSettingsRepository applicationSettingsManager, IConnectionService connectionService, - ILogger logger) + ILogger logger, IEnvironmentService environment, + IAuthenticationTokensRepository tokens, Lazy session, ICloudSessionConnectionRepository sessionConnection) { _applicationSettingsRepository = applicationSettingsManager; _connectionService = connectionService; _logger = logger; + _environment = environment; + _tokens = tokens; + _session = session; + _sessionConnection = sessionConnection; } public PublicKeyInfo GetMyPublicKeyInfo() @@ -161,18 +177,39 @@ public void Delete(TrustedPublicKey trustedPublicKey) _logger.LogInformation("Removed Trusted Public Key {@publicKey}", trustedPublicKey); } - public void InitializeRsaAndTrustedPublicKeys() + public async Task InitializeRsaAndTrustedPublicKeys() { - var updatedSettings = _applicationSettingsRepository.UpdateCurrentApplicationSettings(settings => + await _renewalGate.WaitAsync(); + try { - settings.InitializeRsa(); - settings.InitializeTrustedPublicKeys(); - }); - - _logger.LogInformation("Initialized Local RSA Keys and removed all Trusted Public Keys"); - _logger.LogInformation("ClientId is now {@clientId}", updatedSettings.ClientId); + if (_session.Value.CurrentSession != null || _sessionConnection.CurrentConnectionStatus != SessionConnectionStatus.NoSession || + _connectionService.IsStarting || _connectionService.CurrentConnectionStatus == ByteSync.Business.Communications.ConnectionStatuses.Connecting) + throw new InvalidOperationException("Leave the current session and wait for the connection to finish before renewing the key"); + var reconnect = _connectionService.CurrentConnectionStatus == ConnectionStatuses.Connected; + await _connectionService.StopConnection(); + if (_session.Value.CurrentSession != null || _sessionConnection.CurrentConnectionStatus != SessionConnectionStatus.NoSession) + throw new InvalidOperationException("A session started while stopping the connection; the key was not renewed"); + _connectionService.CurrentEndPoint = null; + await _tokens.Clear(); + var updatedSettings = _applicationSettingsRepository.UpdateCurrentApplicationSettings(settings => + { + settings.InitializeRsa(); + settings.InitializeTrustedPublicKeys(); + _environment.SetClientIdentity(settings.ClientId, AuthenticationProtocol.GetIdentity(settings.DecodedRsaPublicKey!)); + }); + _logger.LogInformation("Initialized Local RSA Keys and removed all Trusted Public Keys"); + _logger.LogInformation("ClientId is now {@clientId}", updatedSettings.ClientId); + if (reconnect) _ = ReconnectAfterRenewal(); + } + finally { _renewalGate.Release(); } } - + + private async Task ReconnectAfterRenewal() + { + try { await _connectionService.StartConnectionAsync(); } + catch (Exception ex) { _logger.LogError(ex, "The key was renewed but reconnection failed"); } + } + public byte[] DecryptBytes(byte[] messageToDecrypt) { // On décrypte avec la clé privée diff --git a/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs b/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs index de085ca69..64ccea518 100644 --- a/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs +++ b/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs @@ -1,4 +1,4 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using System.Threading; using ByteSync.Assets.Resources; using ByteSync.Business; @@ -142,7 +142,7 @@ public async Task OnTrustPublicKeyRequestedAsync(RequestTrustProcessParameters r // Reset the peer trust process data var peerTrustProcessData = await _trustProcessPublicKeysRepository.ResetPeerTrustProcessData( - requestTrustProcessParameters.SessionId, myPublicKeyCheckData.OtherPartyPublicKeyInfo!.ClientId); + requestTrustProcessParameters.SessionId, requestTrustProcessParameters.JoinerPublicKeyCheckData); var trustDataParameters = new TrustDataParameters(1, 1, false, requestTrustProcessParameters.SessionId, peerTrustProcessData); var addTrustedClientViewModel = _flyoutElementViewModelFactory.BuilAddTrustedClientViewModel( @@ -152,7 +152,7 @@ public async Task OnTrustPublicKeyRequestedAsync(RequestTrustProcessParameters r public async Task OnPublicKeyValidationIsFinishedAsync(PublicKeyValidationParameters publicKeyValidationParameters) { - if (publicKeyValidationParameters.OtherPartyClientInstanceId.Equals(_environmentService.ClientInstanceId)) + if (publicKeyValidationParameters.OtherPartyClientInstanceId == _environmentService.ClientInstanceId) { await _trustProcessPublicKeysRepository.SetOtherPartyChecked(publicKeyValidationParameters.SessionId, publicKeyValidationParameters); @@ -164,6 +164,7 @@ public async Task OnPublicKeyValidationFinished(PublicKeyCheckData publicKeyChec { var parameters = new PublicKeyValidationParameters(); + parameters.ExchangeId = publicKeyCheckData.Salt; parameters.IsValidated = isValidated; parameters.SessionId = trustDataParameters.SessionId; parameters.IssuerClientId = _publicKeysManager.GetMyPublicKeyInfo().ClientId; @@ -227,7 +228,7 @@ private async Task DoTrustMembersPublicKeys(string sessionId, cpt += 1; var peerTrustProcessData = await _trustProcessPublicKeysRepository - .ResetPeerTrustProcessData(sessionId, publicKeyCheckData.IssuerPublicKeyInfo.ClientId); + .ResetPeerTrustProcessData(sessionId, publicKeyCheckData); var trustDataParameters = new TrustDataParameters(cpt, keysToTrust.Count, true, sessionId, peerTrustProcessData); var addTrustedClientViewModel = _flyoutElementViewModelFactory.BuilAddTrustedClientViewModel( @@ -274,7 +275,7 @@ private async Task InitiateAndWaitForTrustCheck(string sessio return JoinSessionResult.BuildFrom(JoinSessionStatus.SessionNotFound); } - memberIdsToCheck.RemoveAll(id => id.StartsWith(_environmentService.ClientId)); + memberIdsToCheck.RemoveAll(id => ByteSync.Common.Business.Auth.AuthenticationProtocol.IsInstanceOf(id, _environmentService.Identity)); if (memberIdsToCheck.Count == 0) { return JoinSessionResult.BuildProcessingNormally(); @@ -335,4 +336,4 @@ private void LogProblem(string problemDescription, [CallerMemberName] string cal // ReSharper disable once TemplateIsNotCompileTimeConstantProblem _logger.LogWarning($"CloudSessionConnector.{caller}: {problemDescription}"); } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/Services/Communications/PushReceivers/DataNodePushReceiver.cs b/src/ByteSync.Client/Services/Communications/PushReceivers/DataNodePushReceiver.cs index 2ed1258cf..ea95fd4d1 100644 --- a/src/ByteSync.Client/Services/Communications/PushReceivers/DataNodePushReceiver.cs +++ b/src/ByteSync.Client/Services/Communications/PushReceivers/DataNodePushReceiver.cs @@ -27,7 +27,8 @@ public DataNodePushReceiver(ISessionService sessionService, IDataEncrypter dataE .Subscribe(dto => { var dataNode = _dataEncrypter.DecryptDataNode(dto.EncryptedDataNode); - dataNode.ClientInstanceId = dto.ClientInstanceId; + if (dataNode.ClientInstanceId != dto.ClientInstanceId || dataNode.Id != dto.EncryptedDataNode.Id) + throw new UnauthorizedAccessException("Node owner or id mismatch"); _dataNodeService.ApplyAddDataNodeLocally(dataNode); }); @@ -36,7 +37,8 @@ public DataNodePushReceiver(ISessionService sessionService, IDataEncrypter dataE .Subscribe(dto => { var dataNode = _dataEncrypter.DecryptDataNode(dto.EncryptedDataNode); - dataNode.ClientInstanceId = dto.ClientInstanceId; + if (dataNode.ClientInstanceId != dto.ClientInstanceId || dataNode.Id != dto.EncryptedDataNode.Id) + throw new UnauthorizedAccessException("Node owner or id mismatch"); _dataNodeService.ApplyRemoveDataNodeLocally(dataNode); }); } diff --git a/src/ByteSync.Client/Services/Communications/PushReceivers/DataSourcePushReceiver.cs b/src/ByteSync.Client/Services/Communications/PushReceivers/DataSourcePushReceiver.cs index 01a54932f..28d342afb 100644 --- a/src/ByteSync.Client/Services/Communications/PushReceivers/DataSourcePushReceiver.cs +++ b/src/ByteSync.Client/Services/Communications/PushReceivers/DataSourcePushReceiver.cs @@ -1,4 +1,4 @@ -using System.Reactive.Linq; +using System.Reactive.Linq; using ByteSync.Interfaces.Communications; using ByteSync.Interfaces.Controls.Communications.SignalR; using ByteSync.Interfaces.Controls.Encryptions; @@ -9,14 +9,17 @@ namespace ByteSync.Services.Communications.PushReceivers; public class DataSourcePushReceiver : IPushReceiver { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ISessionService _sessionService; private readonly IDataEncrypter _dataEncrypter; private readonly IHubPushHandler2 _hubPushHandler2; private readonly IDataSourceService _dataSourceService; public DataSourcePushReceiver(ISessionService sessionService, IDataEncrypter dataEncrypter, - IHubPushHandler2 hubPushHandler2, IDataSourceService dataSourceService) + IHubPushHandler2 hubPushHandler2, IDataSourceService dataSourceService, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _sessionService = sessionService; _dataEncrypter = dataEncrypter; _hubPushHandler2 = hubPushHandler2; @@ -27,6 +30,8 @@ public DataSourcePushReceiver(ISessionService sessionService, IDataEncrypter dat .Subscribe(dto => { var dataSource = _dataEncrypter.DecryptDataSource(dto.EncryptedDataSource); + if (dataSource.Id != dto.EncryptedDataSource.Id) throw new UnauthorizedAccessException("Source id mismatch"); + _authorization.CheckNetworkSource(dataSource, dto.ClientInstanceId); _dataSourceService.ApplyAddDataSourceLocally(dataSource); }); @@ -35,6 +40,8 @@ public DataSourcePushReceiver(ISessionService sessionService, IDataEncrypter dat .Subscribe(dto => { var dataSource = _dataEncrypter.DecryptDataSource(dto.EncryptedDataSource); + if (dataSource.Id != dto.EncryptedDataSource.Id) throw new UnauthorizedAccessException("Source id mismatch"); + _authorization.CheckNetworkSource(dataSource, dto.ClientInstanceId); _dataSourceService.ApplyRemoveDataSourceLocally(dataSource); }); } diff --git a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadManager.cs b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadManager.cs index 28a1d8146..7e5c15256 100644 --- a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadManager.cs +++ b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadManager.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.SharedFiles; +using ByteSync.Common.Business.SharedFiles; using ByteSync.Interfaces.Controls.Communications; using ByteSync.Interfaces.Controls.Communications.Http; @@ -59,16 +59,19 @@ public async Task OnFileReadyToFinalize(SharedFileDefinition sharedFileDefinitio await fileDownloader.WaitForFileFullyExtracted(); + downloadTarget.CheckAccess(); if (downloadTarget.TemporaryFileManagers != null) { foreach (var tempFileHelper in downloadTarget.TemporaryFileManagers) { + downloadTarget.CheckAccess(); tempFileHelper.ValidateTemporaryFile(); } } } catch (Exception ex) { + downloadTarget.CheckAccess(); if (downloadTarget.TemporaryFileManagers != null) { foreach (var tempFileHelper in downloadTarget.TemporaryFileManagers) diff --git a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadTargetBuilder.cs b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadTargetBuilder.cs index dfa973bfc..9eda39b99 100644 --- a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadTargetBuilder.cs +++ b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadTargetBuilder.cs @@ -1,4 +1,5 @@ -using System.Reactive.Linq; +using ByteSync.Interfaces.Controls.Inventories; +using System.Reactive.Linq; using ByteSync.Business.Communications; using ByteSync.Business.Communications.Downloading; using ByteSync.Business.Sessions; @@ -16,6 +17,8 @@ namespace ByteSync.Services.Communications.Transfers.Downloading; public class DownloadTargetBuilder : IDownloadTargetBuilder, IDisposable { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ICloudSessionLocalDataManager _cloudSessionLocalDataManager; private readonly ISessionProfileLocalDataManager _sessionProfileLocalDataManager; private readonly ISharedActionsGroupRepository _sharedActionsGroupRepository; @@ -34,8 +37,9 @@ public class DownloadTargetBuilder : IDownloadTargetBuilder, IDisposable public DownloadTargetBuilder(ICloudSessionLocalDataManager cloudSessionLocalDataManager, ISessionProfileLocalDataManager sessionProfileLocalDataManager, ISharedActionsGroupRepository sharedActionsGroupRepository, IConnectionService connectionService, - ITemporaryFileManagerFactory temporaryFileManagerFactory, ISessionService sessionService) + ITemporaryFileManagerFactory temporaryFileManagerFactory, ISessionService sessionService, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _cloudSessionLocalDataManager = cloudSessionLocalDataManager; _sessionProfileLocalDataManager = sessionProfileLocalDataManager; _sharedActionsGroupRepository = sharedActionsGroupRepository; @@ -55,9 +59,13 @@ public DownloadTargetBuilder(ICloudSessionLocalDataManager cloudSessionLocalData public DownloadTarget BuildDownloadTarget(SharedFileDefinition sharedFileDefinition) { + if (sharedFileDefinition.SessionId != _sessionService.SessionId) throw new UnauthorizedAccessException("Transfer session mismatch"); // Check cache first if (_downloadTargetCache.TryGetValue(sharedFileDefinition.Id, out var existing)) + { + existing.CheckAccess(); return existing; + } LocalSharedFile? sharedFile = null; var downloadDestinations = new HashSet(); @@ -158,6 +166,22 @@ public DownloadTarget BuildDownloadTarget(SharedFileDefinition sharedFileDefinit downloadTarget.LastWriteTimeUtcPerActionsGroupId = datesPerActionsGroupId; downloadTarget.TemporaryFileManagers = temporaryFileManagers; + if (sharedFileDefinition.IsSynchronization) + { + downloadTarget.ValidateAccess = () => + { + foreach (var id in sharedFileDefinition.ActionsGroupIds!) + { + var group = _sharedActionsGroupRepository.GetSharedActionsGroup(id) ?? throw new UnauthorizedAccessException(); + if (group.Source?.ClientInstanceId != sharedFileDefinition.ClientInstanceId || + !group.NeedsOperatingOnSourceAndTargets) throw new UnauthorizedAccessException("Transfer source mismatch"); + foreach (var destination in downloadTarget.FinalDestinationsPerActionsGroupId![id]) + _authorization.ValidateDestination(group, destination); + } + foreach (var path in downloadTarget.DownloadDestinations) ByteSync.Services.Synchronizations.LocalPathSafety.AssertNoLinks(path); + }; + downloadTarget.CheckAccess(); + } // Store in cache _downloadTargetCache[sharedFileDefinition.Id] = downloadTarget; diff --git a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/FileDownloader.cs b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/FileDownloader.cs index bb3028f75..da3e8a02e 100644 --- a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/FileDownloader.cs +++ b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/FileDownloader.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Threading; using Autofac.Features.Indexed; using ByteSync.Business.Communications.Downloading; @@ -74,6 +74,7 @@ await Task.Run(() => var partToMerge = await _partsCoordinator.MergeChannel.Reader.ReadAsync(); try { + DownloadTarget.CheckAccess(); await _fileMerger.MergeAsync(partToMerge); } finally diff --git a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/SynchronizationDownloadFinalizer.cs b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/SynchronizationDownloadFinalizer.cs index cdce8e2ed..cbe6cbcc9 100644 --- a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/SynchronizationDownloadFinalizer.cs +++ b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/SynchronizationDownloadFinalizer.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.IO.Compression; using ByteSync.Business.Communications.Downloading; using ByteSync.Common.Business.SharedFiles; @@ -23,9 +23,10 @@ public SynchronizationDownloadFinalizer(IDeltaManager deltaManager, ITemporaryFi _fileDatesSetter = fileDatesSetter; _logger = logger; } - + public async Task FinalizeSynchronization(SharedFileDefinition sharedFileDefinition, DownloadTarget downloadTarget) { + downloadTarget.CheckAccess(); if (downloadTarget.IsMultiFileZip) { await HandleSynchronizationZipMultiFile(sharedFileDefinition, downloadTarget); @@ -35,31 +36,35 @@ public async Task FinalizeSynchronization(SharedFileDefinition sharedFileDefinit await HandleSynchronizationMonoFile(sharedFileDefinition, downloadTarget); } } - + private async Task HandleSynchronizationZipMultiFile(SharedFileDefinition sharedFileDefinition, DownloadTarget downloadTarget) { var downloadDestination = downloadTarget.DownloadDestinations.Single(); - using (var zipArchive = ZipFile.Open(downloadDestination, ZipArchiveMode.Read)) + using (var zipArchive = new ZipArchive(ByteSync.Services.Synchronizations.LocalPathSafety.OpenRead(downloadDestination), ZipArchiveMode.Read)) { + if (zipArchive.Entries.Any(e => e.FullName != e.Name || !downloadTarget.FinalDestinationsPerActionsGroupId!.ContainsKey(e.Name)) || + zipArchive.Entries.Select(e => e.Name).Distinct().Count() != zipArchive.Entries.Count) + throw new UnauthorizedAccessException("Unexpected archive entries"); foreach (var entry in zipArchive.Entries) { var finalDestinations = downloadTarget.FinalDestinationsPerActionsGroupId![entry.Name]; var downloadTargetDates = downloadTarget.GetTargetDates(entry.Name); - + if (sharedFileDefinition.IsDeltaSynchronization) { // Synchro delta foreach (var finalDestination in finalDestinations) { - _logger.LogInformation("{SharedFileDefinitionId}: Extracting and applying delta on {FinalDestination}", + downloadTarget.CheckAccess(); + _logger.LogInformation("{SharedFileDefinitionId}: Extracting and applying delta on {FinalDestination}", sharedFileDefinition.Id, finalDestination); - + await using (var stream = entry.Open()) { using (var reader = new MemoryStream()) { await stream.CopyToAsync(reader); - + await _deltaManager.ApplyDelta(finalDestination, reader); } } @@ -71,21 +76,24 @@ private async Task HandleSynchronizationZipMultiFile(SharedFileDefinition shared { foreach (var finalDestination in finalDestinations) { - _logger.LogInformation("{SharedFileDefinitionId}: Extracting to :{FinalDestination}", + downloadTarget.CheckAccess(); + _logger.LogInformation("{SharedFileDefinitionId}: Extracting to :{FinalDestination}", sharedFileDefinition.Id, finalDestination); - + var fileInfo = new FileInfo(finalDestination); if (fileInfo.Directory is { Exists: false }) { - fileInfo.Directory.Create(); + ByteSync.Services.Synchronizations.LocalPathSafety.CreateDirectory(fileInfo.Directory.FullName); } var temporaryFileManager = _temporaryFileManagerFactory.Create(finalDestination); var destinationTemporaryPath = temporaryFileManager.GetDestinationTemporaryPath(); - + try { - entry.ExtractToFile(destinationTemporaryPath); //NOSONAR + using (var input = entry.Open()) + using (var output = ByteSync.Services.Synchronizations.LocalPathSafety.OpenWrite(destinationTemporaryPath, true)) input.CopyTo(output); + downloadTarget.CheckAccess(); temporaryFileManager.ValidateTemporaryFile(); await _fileDatesSetter.SetDates(sharedFileDefinition, finalDestination, downloadTargetDates); } @@ -98,50 +106,51 @@ private async Task HandleSynchronizationZipMultiFile(SharedFileDefinition shared } } } - + DeleteTemporaryDownloadedFile(downloadDestination); } - + private async Task HandleSynchronizationMonoFile(SharedFileDefinition sharedFileDefinition, DownloadTarget downloadTarget) { var actionsGroupId = sharedFileDefinition.ActionsGroupIds!.Single(); - + var downloadTargetDates = downloadTarget.GetTargetDates(actionsGroupId); if (sharedFileDefinition.IsDeltaSynchronization) { var downloadDestination = downloadTarget.DownloadDestinations.Single(); - + var deltaFullName = downloadDestination; var finalDestinations = downloadTarget.FinalDestinationsPerActionsGroupId![actionsGroupId]; foreach (var finalDestination in finalDestinations) { - _logger.LogInformation("{SharedFileDefinitionId}: Applying delta on {FinalDestination}", + downloadTarget.CheckAccess(); + _logger.LogInformation("{SharedFileDefinitionId}: Applying delta on {FinalDestination}", sharedFileDefinition.Id, finalDestination); - + await _deltaManager.ApplyDelta(finalDestination, deltaFullName); await _fileDatesSetter.SetDates(sharedFileDefinition, finalDestination, downloadTargetDates); } - + DeleteTemporaryDownloadedFile(downloadDestination); } else { var tasks = new List(); - + foreach (var downloadDestination in downloadTarget.AllFinalDestinations) { tasks.Add(_fileDatesSetter.SetDates(sharedFileDefinition, downloadDestination, downloadTargetDates)); } - + await Task.WhenAll(tasks); } } - + private void DeleteTemporaryDownloadedFile(string temporaryDownloadedFile) { _logger.LogInformation("Deleting temporary downloaded file {temporaryDownloadedFile}", temporaryDownloadedFile); - File.Delete(temporaryDownloadedFile); + ByteSync.Services.Synchronizations.LocalPathSafety.Delete(temporaryDownloadedFile); } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/Services/Communications/Transfers/Uploading/FileUploader.cs b/src/ByteSync.Client/Services/Communications/Transfers/Uploading/FileUploader.cs index 0b6998e42..ec41979c8 100644 --- a/src/ByteSync.Client/Services/Communications/Transfers/Uploading/FileUploader.cs +++ b/src/ByteSync.Client/Services/Communications/Transfers/Uploading/FileUploader.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using ByteSync.Business.Communications.Transfers; using ByteSync.Common.Business.SharedFiles; using ByteSync.Interfaces.Controls.Communications; @@ -37,6 +37,8 @@ public FileUploader( SharedFileDefinition = sharedFileDefinition ?? throw new NullReferenceException("SharedFileDefinition is null"); } + public Action? ValidateAccess { get; set; } + public int? MaxSliceLength { get; set; } private SharedFileDefinition SharedFileDefinition { get; set; } private string? LocalFileToUpload { get; set; } @@ -49,6 +51,8 @@ public FileUploader( public Task Upload() { + ValidateAccess?.Invoke(); + _slicerEncrypter.ValidateAccess = ValidateAccess; if (LocalFileToUpload != null) { return UploadFile(); diff --git a/src/ByteSync.Client/Services/Communications/TrustProcessPublicKeysRepository.cs b/src/ByteSync.Client/Services/Communications/TrustProcessPublicKeysRepository.cs index 34aa910e9..c2e2ad63a 100644 --- a/src/ByteSync.Client/Services/Communications/TrustProcessPublicKeysRepository.cs +++ b/src/ByteSync.Client/Services/Communications/TrustProcessPublicKeysRepository.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.Threading; using ByteSync.Business.Communications.PublicKeysTrusting; using ByteSync.Common.Business.EndPoints; @@ -39,15 +39,12 @@ public async Task IsFullyTrusted(string sessionId, string memberInstanceId .FullyTrustedPublicKeyCheckDatas.Any(pk => pk.IssuerClientInstanceId.Equals(memberInstanceId))); } - public async Task ResetPeerTrustProcessData(string sessionId, string otherPartyClientId) + public async Task ResetPeerTrustProcessData(string sessionId, PublicKeyCheckData peer) { return await GetAsync(sessionId, data => { - var peerTrustProcessData = new PeerTrustProcessData(otherPartyClientId); - - data.AddPeerTrustProcessData(peerTrustProcessData); - - return peerTrustProcessData; + var peerTrustProcessData = new PeerTrustProcessData(peer); + return data.AddPeerTrustProcessData(peerTrustProcessData); }); } @@ -65,7 +62,7 @@ public async Task SetOtherPartyChecked(string sessionId, PublicKeyValidationPara { await RunAsync(sessionId, data => { - data.SetOtherPartyChecked(publicKeyValidationParameters.IssuerClientId, publicKeyValidationParameters.IsValidated); + data.SetOtherPartyChecked(publicKeyValidationParameters); }); } diff --git a/src/ByteSync.Client/Services/Encryptions/MergerDecrypter.cs b/src/ByteSync.Client/Services/Encryptions/MergerDecrypter.cs index 461c4c1c9..33e8543cc 100644 --- a/src/ByteSync.Client/Services/Encryptions/MergerDecrypter.cs +++ b/src/ByteSync.Client/Services/Encryptions/MergerDecrypter.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; @@ -50,12 +50,13 @@ private void Initialize(string finalFile, DownloadTarget downloadTarget, Cancell CancellationTokenSource = cancellationTokenSource; + DownloadTarget.CheckAccess(); var fileInfo = new FileInfo(FinalFile); if (fileInfo.Directory != null) { - fileInfo.Directory.Create(); + ByteSync.Services.Synchronizations.LocalPathSafety.CreateDirectory(fileInfo.Directory.FullName); } - using (var _ = new FileStream(FinalFile, FileMode.Append)) + using (var _ = ByteSync.Services.Synchronizations.LocalPathSafety.OpenWrite(FinalFile, append: true)) { // Pour créer au moins un fichier vide } @@ -68,7 +69,8 @@ public async Task MergeAndDecrypt() return; } - await using var outStream = new FileStream(FinalFile, FileMode.Append); + DownloadTarget.CheckAccess(); + await using var outStream = ByteSync.Services.Synchronizations.LocalPathSafety.OpenWrite(FinalFile, append: true); var cryptoTransform = Aes.CreateDecryptor(Aes.Key, Aes.IV); await using var cryptoStream = new CryptoStream(outStream, cryptoTransform, CryptoStreamMode.Write); diff --git a/src/ByteSync.Client/Services/Encryptions/SlicerEncrypter.cs b/src/ByteSync.Client/Services/Encryptions/SlicerEncrypter.cs index bb3b10eb2..571be5d4e 100644 --- a/src/ByteSync.Client/Services/Encryptions/SlicerEncrypter.cs +++ b/src/ByteSync.Client/Services/Encryptions/SlicerEncrypter.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Security.Cryptography; using System.Threading; using ByteSync.Business.Communications.Transfers; @@ -13,6 +13,7 @@ public class SlicerEncrypter : ISlicerEncrypter private readonly ICloudSessionConnectionRepository _cloudSessionConnectionRepository; private readonly ILogger _logger; + public Action? ValidateAccess { get; set; } private int _maxSliceLength; public SlicerEncrypter(ICloudSessionConnectionRepository cloudSessionConnectionRepository, @@ -29,7 +30,7 @@ public void Initialize(FileInfo fileToEncrypt, SharedFileDefinition sharedFileDe { SharedFileDefinition = sharedFileDefinition; - InStream = new FileStream(fileToEncrypt.FullName, FileMode.Open, FileAccess.Read); + InStream = ByteSync.Services.Synchronizations.LocalPathSafety.OpenRead(fileToEncrypt.FullName); InReader = new BinaryReader(InStream); EndInitialize(); @@ -85,6 +86,7 @@ public int MaxSliceLength CryptoStream? cryptoStream = null; FileUploaderSlice? fileUploaderSlice = null; + ValidateAccess?.Invoke(); var bytes = InReader.ReadBytes(BufferSize); var readBytes = bytes.Length; var thisSessionReadBytes = readBytes; diff --git a/src/ByteSync.Client/Services/Inventories/DataNodeService.cs b/src/ByteSync.Client/Services/Inventories/DataNodeService.cs index 4d6909271..e40052465 100644 --- a/src/ByteSync.Client/Services/Inventories/DataNodeService.cs +++ b/src/ByteSync.Client/Services/Inventories/DataNodeService.cs @@ -24,6 +24,7 @@ public class DataNodeService : IDataNodeService private readonly IDataSourceRepository _dataSourceRepository; private readonly ILogger _logger; + private readonly ILocalSourceAuthorizationService _authorization; private int _nodeCounter; private readonly SemaphoreSlim _counterSemaphore = new(1, 1); @@ -31,7 +32,7 @@ public DataNodeService(ISessionService sessionService, IConnectionService connec IDataEncrypter dataEncrypter, IInventoryApiClient inventoryApiClient, IDataNodeRepository dataNodeRepository, IDataNodeCodeGenerator codeGenerator, IDataSourceService dataSourceService, - IDataSourceRepository dataSourceRepository, ILogger logger) + IDataSourceRepository dataSourceRepository, ILogger logger, ILocalSourceAuthorizationService authorization) { _sessionService = sessionService; _connectionService = connectionService; @@ -42,6 +43,7 @@ public DataNodeService(ISessionService sessionService, IConnectionService connec _dataSourceService = dataSourceService; _dataSourceRepository = dataSourceRepository; _logger = logger; + _authorization = authorization; // Reset the counter when a session ends or is reset _sessionService.SessionObservable @@ -133,6 +135,7 @@ public async Task TryRemoveDataNode(DataNode dataNode) foreach (var dataSource in associatedDataSources) { + if (dataSource.ClientInstanceId == _connectionService.ClientInstanceId) _authorization.Revoke(dataSource); _dataSourceService.ApplyRemoveDataSourceLocally(dataSource); } } @@ -142,12 +145,16 @@ public async Task TryRemoveDataNode(DataNode dataNode) public void ApplyAddDataNodeLocally(DataNode dataNode) { + var existing = _dataNodeRepository.GetElement(dataNode.Id); + if (existing != null && existing.ClientInstanceId != dataNode.ClientInstanceId) throw new UnauthorizedAccessException("Node id already belongs to another instance"); _dataNodeRepository.AddOrUpdate(dataNode); _codeGenerator.RecomputeCodes(); } public void ApplyRemoveDataNodeLocally(DataNode dataNode) { + var existing = _dataNodeRepository.GetElement(dataNode.Id); + if (existing != null && existing.ClientInstanceId != dataNode.ClientInstanceId) throw new UnauthorizedAccessException("Node owner mismatch"); _dataNodeRepository.Remove(dataNode); _codeGenerator.RecomputeCodes(); } diff --git a/src/ByteSync.Client/Services/Inventories/DataSourceService.cs b/src/ByteSync.Client/Services/Inventories/DataSourceService.cs index 98d460536..2f1b1433a 100644 --- a/src/ByteSync.Client/Services/Inventories/DataSourceService.cs +++ b/src/ByteSync.Client/Services/Inventories/DataSourceService.cs @@ -1,4 +1,4 @@ -using ByteSync.Business.DataNodes; +using ByteSync.Business.DataNodes; using ByteSync.Business.DataSources; using ByteSync.Common.Business.Inventories; using ByteSync.Common.Business.Sessions.Cloud; @@ -14,6 +14,8 @@ namespace ByteSync.Services.Inventories; public class DataSourceService : IDataSourceService { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ISessionService _sessionService; private readonly IDataSourceChecker _dataSourceChecker; private readonly IDataEncrypter _dataEncrypter; @@ -25,8 +27,9 @@ public class DataSourceService : IDataSourceService public DataSourceService(ISessionService sessionService, IDataSourceChecker dataSourceChecker, IDataEncrypter dataEncrypter, IConnectionService connectionService, IInventoryApiClient inventoryApiClient, - IDataSourceRepository dataSourceRepository, IDataSourceCodeGenerator codeGenerator, ILogger logger) + IDataSourceRepository dataSourceRepository, IDataSourceCodeGenerator codeGenerator, ILogger logger, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _sessionService = sessionService; _dataSourceChecker = dataSourceChecker; _dataEncrypter = dataEncrypter; @@ -68,6 +71,7 @@ public async Task TryAddDataSource(DataSource dataSource) public void ApplyAddDataSourceLocally(DataSource dataSource) { + _authorization.CheckNetworkSource(dataSource, dataSource.ClientInstanceId); _dataSourceRepository.AddOrUpdate(dataSource); _codeGenerator.RecomputeCodesForNode(dataSource.DataNodeId); } @@ -83,9 +87,18 @@ public Task CreateAndTryAddDataSource(string path, FileSystemTypes fileSystemTyp dataSource.DataNodeId = dataNode.Id; dataSource.InitialTimestamp = DateTime.UtcNow; + _authorization.Grant(dataSource); return TryAddDataSource(dataSource); } + public async Task RestoreDataSource(string path, FileSystemTypes type, DataNode node) + { + var source = new DataSource { Id = Guid.NewGuid().ToString(), Path = path, Type = type, + DataNodeId = node.Id, ClientInstanceId = _connectionService.ClientInstanceId!, InitialTimestamp = DateTime.UtcNow }; + _authorization.Grant(source, true); + await TryAddDataSource(source); + } + public async Task TryRemoveDataSource(DataSource dataSource) { var encryptedDataSource = _dataEncrypter.EncryptDataSource(dataSource); @@ -99,6 +112,7 @@ public async Task TryRemoveDataSource(DataSource dataSource) if (isRemoveOK) { + _authorization.Revoke(dataSource); ApplyRemoveDataSourceLocally(dataSource); } diff --git a/src/ByteSync.Client/Services/Inventories/InventoryBuilder.cs b/src/ByteSync.Client/Services/Inventories/InventoryBuilder.cs index 0c3d1664f..9b16061f6 100644 --- a/src/ByteSync.Client/Services/Inventories/InventoryBuilder.cs +++ b/src/ByteSync.Client/Services/Inventories/InventoryBuilder.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Threading; using ByteSync.Business; using ByteSync.Business.Arguments; @@ -104,6 +104,7 @@ public InventoryPart AddInventoryPart(DataSource dataSource) var inventoryPart = AddInventoryPart(dataSource.Path); inventoryPart.Code = dataSource.Code; + inventoryPart.SourceId = dataSource.Id; return inventoryPart; } diff --git a/src/ByteSync.Client/Services/Inventories/InventoryFileAnalyzer.cs b/src/ByteSync.Client/Services/Inventories/InventoryFileAnalyzer.cs index 8a980a973..bd1d1f557 100644 --- a/src/ByteSync.Client/Services/Inventories/InventoryFileAnalyzer.cs +++ b/src/ByteSync.Client/Services/Inventories/InventoryFileAnalyzer.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Threading; using ByteSync.Business; using ByteSync.Business.Arguments; @@ -19,15 +19,17 @@ public class InventoryFileAnalyzer : IInventoryFileAnalyzer private readonly IInventorySaver _saver; private readonly ILogger _logger; + private readonly ILocalSourceAuthorizationService _authorization; public InventoryFileAnalyzer(FingerprintModes fingerprintMode, InventoryProcessData processData, IInventorySaver saver, - ILogger logger) + ILogger logger, ILocalSourceAuthorizationService authorization) { _fingerprintMode = fingerprintMode; _processData = processData; _saver = saver; _logger = logger; + _authorization = authorization; ManualResetSyncEvents = new ManualResetSyncEvents(); SyncRoot = new object(); @@ -148,9 +150,10 @@ private void HandleFilesAnalysis() private void ComputeFingerPrint(Tuple tuple) { + _authorization.ValidatePath(tuple.Item2.FullName); if (tuple.Item1.FingerprintMode == FingerprintModes.Sha256) { - using var basisStream = new FileStream(tuple.Item2.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); + using var basisStream = ByteSync.Services.Synchronizations.LocalPathSafety.OpenRead(tuple.Item2.FullName); var sha256 = CryptographyUtils.ComputeSHA256(basisStream); tuple.Item1.Sha256 = sha256; @@ -159,7 +162,7 @@ private void ComputeFingerPrint(Tuple tuple) { _logger.LogInformation("Analyzing file {FullName}", tuple.Item2.FullName); - using var basisStream = new FileStream(tuple.Item2.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); + using var basisStream = ByteSync.Services.Synchronizations.LocalPathSafety.OpenRead(tuple.Item2.FullName); using var memoryStream = new MemoryStream(); var signatureBuilder = new SignatureBuilder(); signatureBuilder.Build(basisStream, new SignatureWriter(memoryStream)); diff --git a/src/ByteSync.Client/Services/Inventories/InventoryLoader.cs b/src/ByteSync.Client/Services/Inventories/InventoryLoader.cs index dd7016b1a..dc8069f4a 100644 --- a/src/ByteSync.Client/Services/Inventories/InventoryLoader.cs +++ b/src/ByteSync.Client/Services/Inventories/InventoryLoader.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.IO.Compression; using ByteSync.Common.Controls.Json; using ByteSync.Models.Inventories; @@ -7,13 +7,25 @@ namespace ByteSync.Services.Inventories; public class InventoryLoader : IDisposable { - public InventoryLoader(string fullName) + private readonly string? _expectedOwner; + + public InventoryLoader(string fullName, string? expectedOwner = null) { FullName = fullName; + _expectedOwner = expectedOwner; - ZipArchive = ZipFile.OpenRead(FullName); - - Inventory = Load(); + var stream = ByteSync.Services.Synchronizations.LocalPathSafety.OpenRead(FullName); + try + { + ZipArchive = new ZipArchive(stream, ZipArchiveMode.Read); + Inventory = Load(); + } + catch + { + ZipArchive?.Dispose(); + stream.Dispose(); + throw; + } } public string FullName { get; } @@ -40,6 +52,22 @@ private Inventory Load() throw new InvalidOperationException("Failed to deserialize inventory.json."); } + if (_expectedOwner != null && inventory.Endpoint.ClientInstanceId != _expectedOwner) throw new UnauthorizedAccessException("Inventory sender mismatch"); + foreach (var part in inventory.InventoryParts) + { + part.Inventory = inventory; + if (_expectedOwner != null && string.IsNullOrEmpty(part.SourceId)) throw new UnauthorizedAccessException("Missing inventory source id"); + foreach (var item in part.FileDescriptions.Cast().Concat(part.DirectoryDescriptions)) + { + item.InventoryPart = part; + if (_expectedOwner != null) + { + if (item.RelativePath == null || !item.RelativePath.StartsWith('/')) throw new UnauthorizedAccessException("Invalid inventory path"); + ByteSync.Services.Synchronizations.LocalPathSafety.ValidateRelativePath(item.RelativePath[1..]); + } + } + } + foreach (var inventoryPart in inventory.InventoryParts .Where(ip => !ip.IsIncompleteDueToAccess && (ip.DirectoryDescriptions.Any(d => !d.IsAccessible) diff --git a/src/ByteSync.Client/Services/Inventories/InventorySaver.cs b/src/ByteSync.Client/Services/Inventories/InventorySaver.cs index b39ae802c..6bff03f8f 100644 --- a/src/ByteSync.Client/Services/Inventories/InventorySaver.cs +++ b/src/ByteSync.Client/Services/Inventories/InventorySaver.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.IO.Compression; using ByteSync.Common.Controls.Json; using ByteSync.Interfaces.Controls.Inventories; @@ -19,12 +19,12 @@ public void Start(string inventoryFullName) if (File.Exists(inventoryFullName)) { Log.Information("Deleting {FileFullName}", inventoryFullName); - File.Delete(inventoryFullName); + ByteSync.Services.Synchronizations.LocalPathSafety.Delete(inventoryFullName); // throw new Exception("file already exists"); } - ZipArchive = ZipFile.Open(inventoryFullName, ZipArchiveMode.Create); + ZipArchive = new ZipArchive(ByteSync.Services.Synchronizations.LocalPathSafety.OpenWrite(inventoryFullName, true), ZipArchiveMode.Create); CountByDirectory.Clear(); } diff --git a/src/ByteSync.Client/Services/Inventories/InventoryService.cs b/src/ByteSync.Client/Services/Inventories/InventoryService.cs index 1e61f34e0..00ffee1ee 100644 --- a/src/ByteSync.Client/Services/Inventories/InventoryService.cs +++ b/src/ByteSync.Client/Services/Inventories/InventoryService.cs @@ -1,4 +1,4 @@ -using System.Reactive.Linq; +using System.Reactive.Linq; using ByteSync.Business; using ByteSync.Business.Communications; using ByteSync.Business.DataNodes; @@ -62,6 +62,11 @@ public async Task OnFileIsFullyDownloaded(LocalSharedFile localSharedFile) { if (localSharedFile.SharedFileDefinition.IsInventory) { + using var loader = new InventoryLoader(localSharedFile.LocalPath, localSharedFile.SharedFileDefinition.ClientInstanceId); + var node = _dataNodeRepository.GetElement(loader.Inventory.NodeId); + if (node == null || node.ClientInstanceId != localSharedFile.SharedFileDefinition.ClientInstanceId || + loader.Inventory.CodeAndId != localSharedFile.SharedFileDefinition.AdditionalName) + throw new UnauthorizedAccessException("Inventory node or id mismatch"); var inventoryFile = new InventoryFile(localSharedFile); _inventoryFileRepository.AddOrUpdate(inventoryFile); diff --git a/src/ByteSync.Client/Services/Inventories/LocalSourceAuthorizationService.cs b/src/ByteSync.Client/Services/Inventories/LocalSourceAuthorizationService.cs new file mode 100644 index 000000000..c9924c0aa --- /dev/null +++ b/src/ByteSync.Client/Services/Inventories/LocalSourceAuthorizationService.cs @@ -0,0 +1,141 @@ +using System.IO; +using ByteSync.Business.Actions.Shared; +using ByteSync.Business.DataSources; +using ByteSync.Common.Business.Inventories; +using ByteSync.Interfaces; +using ByteSync.Interfaces.Controls.Inventories; +using ByteSync.Interfaces.Services.Communications; +using ByteSync.Interfaces.Services.Sessions; +using ByteSync.Services.Synchronizations; + +namespace ByteSync.Services.Inventories; + +public class LocalSourceAuthorizationService(IApplicationSettingsRepository settings, IConnectionService connection, + ISessionService session, ByteSync.Interfaces.Repositories.IDataNodeRepository nodes) : ILocalSourceAuthorizationService +{ + private sealed record GrantData(object? Session, string SessionId, string Id, string NodeId, string InstanceId, string Root, FileSystemTypes Type); + private readonly Dictionary<(string, string), GrantData> _grants = new(); + private readonly object _gate = new(); + + public void Grant(DataSource source, bool restoreOnly = false) + { + if (source.ClientInstanceId != connection.ClientInstanceId || session.SessionId == null || + string.IsNullOrEmpty(source.Id) || string.IsNullOrEmpty(source.DataNodeId)) throw new UnauthorizedAccessException(); + if (source.Type is not (FileSystemTypes.File or FileSystemTypes.Directory)) throw new UnauthorizedAccessException(); + var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(source.Path)); + if (!Path.IsPathFullyQualified(source.Path)) throw new UnauthorizedAccessException(); + LocalPathSafety.AssertNoLinks(root); + var identity = ByteSync.Common.Business.Auth.AuthenticationProtocol.GetIdentity(settings.GetCurrentApplicationSettings().DecodedRsaPublicKey!); + var permission = new LocalSourcePermission(identity, root, source.Type); + lock (_gate) + { + var permissions = settings.GetCurrentApplicationSettings().LocalSourcePermissions; + if (restoreOnly && !permissions.Contains(permission)) + throw new UnauthorizedAccessException("Select the profile source locally before running it automatically"); + if (!restoreOnly && !permissions.Contains(permission)) + settings.UpdateCurrentApplicationSettings(s => s.LocalSourcePermissions.Add(permission)); + _grants[(session.SessionId, source.Id)] = new GrantData(session.CurrentSession, session.SessionId, source.Id, source.DataNodeId, + source.ClientInstanceId, root, source.Type); + } + } + + public void Revoke(DataSource source) + { + lock (_gate) + { + if (session.SessionId != null) _grants.Remove((session.SessionId, source.Id)); + settings.UpdateCurrentApplicationSettings(s => s.LocalSourcePermissions.RemoveAll(p => + p.Path == Path.TrimEndingDirectorySeparator(Path.GetFullPath(source.Path)) && p.Type == source.Type)); + } + } + + public void CheckNetworkSource(DataSource source, string sender) + { + if (source.ClientInstanceId != sender) throw new UnauthorizedAccessException("Source owner mismatch"); + var node = nodes.GetElement(source.DataNodeId); + if (node == null || node.ClientInstanceId != sender) throw new UnauthorizedAccessException("Source node owner mismatch"); + if (sender != connection.ClientInstanceId) return; + var part = new SharedDataPart { SourceId = source.Id, NodeId = source.DataNodeId, ClientInstanceId = sender, + InventoryPartType = source.Type, SourceRelativePath = "" }; + var expected = Resolve(part); + if (!string.Equals(expected, Path.TrimEndingDirectorySeparator(Path.GetFullPath(source.Path)), LocalPathSafety.Comparison)) + throw new UnauthorizedAccessException("Network data cannot change a local source root"); + } + + public string Resolve(SharedDataPart part) + { + lock (_gate) + { + if (session.SessionId == null || part.SourceId == null || + !_grants.TryGetValue((session.SessionId, part.SourceId), out var grant) || + part.ClientInstanceId != connection.ClientInstanceId || grant.InstanceId != part.ClientInstanceId || + !ReferenceEquals(grant.Session, session.CurrentSession) || grant.NodeId != part.NodeId || grant.Type != part.InventoryPartType) throw new UnauthorizedAccessException("Local source is not authorized"); + LocalPathSafety.ValidateRelativePath(part.SourceRelativePath); + if (grant.Type == FileSystemTypes.File && part.SourceRelativePath != "") throw new UnauthorizedAccessException("File source cannot authorize siblings"); + var resolved = Path.GetFullPath(Path.Combine(grant.Root, part.SourceRelativePath!.Replace('/', Path.DirectorySeparatorChar))); + var boundary = Path.EndsInDirectorySeparator(grant.Root) ? grant.Root : grant.Root + Path.DirectorySeparatorChar; + if (!string.Equals(resolved, grant.Root, LocalPathSafety.Comparison) && + !resolved.StartsWith(boundary, LocalPathSafety.Comparison)) + throw new UnauthorizedAccessException("Path escapes source"); + LocalPathSafety.AssertNoLinks(resolved); + return resolved; + } + } + + public void ValidatePlan(IEnumerable groups) + { + var bindings = new List(); + var ids = new HashSet(StringComparer.Ordinal); + foreach (var group in groups) + { + if (group == null || string.IsNullOrEmpty(group.ActionsGroupId) || !ids.Add(group.ActionsGroupId)) + throw new UnauthorizedAccessException("Invalid or duplicate action id"); + LocalPathSafety.ValidateComponent(group.ActionsGroupId); + if (!Enum.IsDefined(group.Operator) || group.Targets == null || group.PathIdentity == null || + (group.NeedsOperatingOnSourceAndTargets && group.Source == null)) throw new UnauthorizedAccessException("Invalid synchronization plan"); + if (group.PathIdentity.FileSystemType is not (FileSystemTypes.File or FileSystemTypes.Directory) || + (group.IsCreate && !group.IsDirectory) || ((group.IsCopyContent || group.IsCopyDates) && !group.IsFile) || + ((group.IsFullCopy || group.IsCopyDates) && (!group.CreationTimeUtc.HasValue || !group.LastWriteTimeUtc.HasValue)) || + (group.IsCopyContent && group.SynchronizationType is not (ByteSync.Common.Business.Actions.SynchronizationTypes.Full or ByteSync.Common.Business.Actions.SynchronizationTypes.Delta))) + throw new UnauthorizedAccessException("Incomplete synchronization operation"); + foreach (var part in group.Targets.Concat(group.Source == null ? Array.Empty() : new[] { group.Source })) + { + if (part == null || string.IsNullOrEmpty(part.SourceId) || string.IsNullOrEmpty(part.NodeId) || string.IsNullOrEmpty(part.ClientInstanceId)) + throw new UnauthorizedAccessException("Missing action source binding"); + LocalPathSafety.ValidateRelativePath(part.SourceRelativePath); + } + if (group.Source != null && group.Source.ClientInstanceId == connection.ClientInstanceId) bindings.Add(group.Source); + bindings.AddRange(group.Targets.Where(p => p.ClientInstanceId == connection.ClientInstanceId)); + } + foreach (var part in bindings) Resolve(part); + foreach (var part in bindings) part.LocalPathResolver = () => Resolve(part); + } + + public void ValidatePath(string path) + { + lock (_gate) + { + var full = Path.GetFullPath(path); + foreach (var grant in _grants.Values.Where(g => g.SessionId == session.SessionId)) + { + var relative = Path.GetRelativePath(grant.Root, full).Replace(Path.DirectorySeparatorChar, '/'); + if (relative == ".") relative = ""; + try + { + var resolved = Resolve(new SharedDataPart { SourceId = grant.Id, NodeId = grant.NodeId, ClientInstanceId = grant.InstanceId, + InventoryPartType = grant.Type, SourceRelativePath = relative }); + if (string.Equals(resolved, full, StringComparison.Ordinal)) return; + } + catch (UnauthorizedAccessException) { } + } + throw new UnauthorizedAccessException("Path has no current local authorization"); + } + } + + public void ValidateDestination(SharedActionsGroup group, string destination) + { + if (!group.Targets.Where(p => p.ClientInstanceId == connection.ClientInstanceId) + .Any(p => string.Equals(Resolve(p), destination, LocalPathSafety.Comparison))) + throw new UnauthorizedAccessException("Destination is not part of the authorized action"); + } +} diff --git a/src/ByteSync.Client/Services/Profiles/SessionProfileLocalDataManager.cs b/src/ByteSync.Client/Services/Profiles/SessionProfileLocalDataManager.cs index 4aba07a6b..a5da97f6d 100644 --- a/src/ByteSync.Client/Services/Profiles/SessionProfileLocalDataManager.cs +++ b/src/ByteSync.Client/Services/Profiles/SessionProfileLocalDataManager.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.IO.Compression; using System.Threading.Tasks; using ByteSync.Business.Profiles; @@ -27,6 +27,7 @@ public SessionProfileLocalDataManager(ILocalApplicationDataManager localApplicat public string GetProfileZipPath(string profileId) { + ByteSync.Services.Synchronizations.LocalPathSafety.ValidateComponent(profileId); var profilesDirectory = IOUtils.Combine(_localApplicationDataManager.ApplicationDataPath, "Profiles", profileId); Directory.CreateDirectory(profilesDirectory); @@ -39,6 +40,7 @@ public string GetProfileZipPath(SharedFileDefinition sharedFileDefinition) { if (sharedFileDefinition.IsProfileDetails) { + ByteSync.Services.Synchronizations.LocalPathSafety.ValidateComponent(sharedFileDefinition.AdditionalName); var profilesDirectory = IOUtils.Combine(_localApplicationDataManager.ApplicationDataPath, "Profiles", sharedFileDefinition.AdditionalName); Directory.CreateDirectory(profilesDirectory); @@ -55,6 +57,7 @@ public string GetProfileZipPath(SharedFileDefinition sharedFileDefinition) public DirectoryInfo GetProfileDirectory(AbstractSessionProfile sessionProfile) { + ByteSync.Services.Synchronizations.LocalPathSafety.ValidateComponent(sessionProfile.ProfileId); var profileDirectory = IOUtils.Combine(_localApplicationDataManager.ApplicationDataPath, "Profiles", sessionProfile.ProfileId); return new DirectoryInfo(profileDirectory); @@ -62,6 +65,7 @@ public DirectoryInfo GetProfileDirectory(AbstractSessionProfile sessionProfile) public DirectoryInfo GetProfileDirectory(AbstrastSessionProfileDetails abstrastSessionProfileDetails) { + ByteSync.Services.Synchronizations.LocalPathSafety.ValidateComponent(abstrastSessionProfileDetails.ProfileId); var profileDirectory = IOUtils.Combine(_localApplicationDataManager.ApplicationDataPath, "Profiles", abstrastSessionProfileDetails.ProfileId); return new DirectoryInfo(profileDirectory); diff --git a/src/ByteSync.Client/Services/Profiles/SessionProfileManager.cs b/src/ByteSync.Client/Services/Profiles/SessionProfileManager.cs index a8e521b96..0867866cb 100644 --- a/src/ByteSync.Client/Services/Profiles/SessionProfileManager.cs +++ b/src/ByteSync.Client/Services/Profiles/SessionProfileManager.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.IO.Compression; using System.Threading.Tasks; using ByteSync.Assets.Resources; @@ -367,7 +367,8 @@ private CloudSessionProfileDetails BuildCloudSessionProfileDetails(CloudSessionP cloudSessionProfileMember.IpAddress = sessionMemberInfo.IpAddress; cloudSessionProfileMember.ProfileClientId = data.Slots - .Single(t => t.ClientId.Equals(sessionMemberInfo.Endpoint.ClientId)).ProfileClientId; + .Single(t => t.ClientId.Equals(sessionMemberInfo.Endpoint.ClientId) && + t.OriginalClientInstanceId == sessionMemberInfo.ClientInstanceId).ProfileClientId; cloudSessionProfileMember.ProfileClientPassword = $"CSPCP_{Guid.NewGuid()}"; cloudSessionProfileMember.DataSources = allDataSources .Where(ds => ds.BelongsTo(sessionMemberInfo)) diff --git a/src/ByteSync.Client/Services/Sessions/CloudSessionLocalDataManager.cs b/src/ByteSync.Client/Services/Sessions/CloudSessionLocalDataManager.cs index fae1f43b5..74c60579b 100644 --- a/src/ByteSync.Client/Services/Sessions/CloudSessionLocalDataManager.cs +++ b/src/ByteSync.Client/Services/Sessions/CloudSessionLocalDataManager.cs @@ -1,4 +1,5 @@ -using System.IO; +using System.IO; +using ByteSync.Services.Synchronizations; using ByteSync.Business; using ByteSync.Business.Actions.Shared; using ByteSync.Common.Business.SharedFiles; @@ -33,11 +34,12 @@ public CloudSessionLocalDataManager(ILocalApplicationDataManager localApplicatio internal string GetSessionLocalPath() { var cloudSession = _sessionService.CurrentSession!; + LocalPathSafety.ValidateComponent(cloudSession.SessionId); var sessionLocalPath = IOUtils.Combine(_localApplicationDataManager.ApplicationDataPath, "Sessions", $"{cloudSession.SessionId}_{cloudSession.Created:yyyyMMddTHHmmss}"); - Directory.CreateDirectory(sessionLocalPath); + LocalPathSafety.CreateDirectory(sessionLocalPath); return sessionLocalPath; } @@ -56,13 +58,14 @@ private string GetMachineFullPath(string clientInstanceId) var sessionMember = _sessionMemberRepository.GetElement(clientInstanceId); machinePath = sessionMember!.MachineName; } - machinePath += "_" + clientInstanceId; + LocalPathSafety.ValidateComponent(clientInstanceId); + machinePath = clientInstanceId; var machineFullPath = IOUtils.Combine(sessionLocalPath, machinePath); if (!Directory.Exists(machineFullPath)) { - Directory.CreateDirectory(machineFullPath); + LocalPathSafety.CreateDirectory(machineFullPath); } return machineFullPath; @@ -87,6 +90,7 @@ public string GetInventoryPath(SharedFileDefinition sharedFileDefinition) public string GetInventoryPath(string clientInstanceId, string inventoryCodeAndId, LocalInventoryModes localInventoryMode) { + LocalPathSafety.ValidateComponent(inventoryCodeAndId); var machineFullPath = GetMachineFullPath(clientInstanceId); string fileName; @@ -106,13 +110,15 @@ public string GetInventoryPath(string clientInstanceId, string inventoryCodeAndI public string GetTempDeltaFullName(SharedDataPart source, SharedDataPart target) { + if (source.SignatureGuid != null) LocalPathSafety.ValidateComponent(source.SignatureGuid); + if (target.SignatureGuid != null) LocalPathSafety.ValidateComponent(target.SignatureGuid); var sessionLocalPath = GetSessionLocalPath(); var tempFullPath = IOUtils.Combine(sessionLocalPath, "Temp"); if (!Directory.Exists(tempFullPath)) { - Directory.CreateDirectory(tempFullPath); + LocalPathSafety.CreateDirectory(tempFullPath); } var cpt = 0; @@ -144,13 +150,14 @@ public string GetSynchronizationTempZipPath(SharedFileDefinition sharedFileDefin { if (sharedFileDefinition.IsSynchronization) { + LocalPathSafety.ValidateComponent(sharedFileDefinition.Id); var sessionLocalPath = GetSessionLocalPath(); var tempFullPath = IOUtils.Combine(sessionLocalPath, "Temp"); if (!Directory.Exists(tempFullPath)) { - Directory.CreateDirectory(tempFullPath); + LocalPathSafety.CreateDirectory(tempFullPath); } var fileName = $"{sharedFileDefinition.Id}_temp.zip"; diff --git a/src/ByteSync.Client/Services/Sessions/Connecting/AfterJoinSessionService.cs b/src/ByteSync.Client/Services/Sessions/Connecting/AfterJoinSessionService.cs index c1c8d80e4..11e279523 100644 --- a/src/ByteSync.Client/Services/Sessions/Connecting/AfterJoinSessionService.cs +++ b/src/ByteSync.Client/Services/Sessions/Connecting/AfterJoinSessionService.cs @@ -1,4 +1,4 @@ -using System.Text; +using System.Text; using ByteSync.Business.Arguments; using ByteSync.Business.Sessions.Connecting; using ByteSync.Common.Business.Inventories; @@ -141,6 +141,8 @@ private async Task FillDataNodes(AfterJoinSessionRequest request, List _logger; public DeltaManager(ICloudSessionLocalDataManager cloudSessionLocalDataManager, ITemporaryFileManagerFactory temporaryFileManagerFactory, - ILogger logger) + ILogger logger, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _cloudSessionLocalDataManager = cloudSessionLocalDataManager; _temporaryFileManagerFactory = temporaryFileManagerFactory; _logger = logger; @@ -37,8 +41,8 @@ public async Task BuildDelta(SharedActionsGroup sharedActionsGroup, Shar var deltaBuilder = new DeltaBuilder(); await using var targetMemoryStream = targetInventoryLoader.GetSignature(sharedDataPart.SignatureGuid!); - await using var newFileStream = new FileStream(sourceFullName, FileMode.Open, FileAccess.Read, FileShare.Read); - await using var deltaStream = new FileStream(deltaFullName, FileMode.Create, FileAccess.Write, FileShare.Read); + await using var newFileStream = LocalPathSafety.OpenRead(sharedActionsGroup.GetSourceFullName()); + await using var deltaStream = LocalPathSafety.OpenWrite(deltaFullName, true); await deltaBuilder.BuildDeltaAsync(newFileStream, new SignatureReader(targetMemoryStream, deltaBuilder.ProgressReport), @@ -49,12 +53,13 @@ await deltaBuilder.BuildDeltaAsync(newFileStream, public async Task ApplyDelta(string destinationFullName, string deltaFullName) { - await using var deltaStream = new FileStream(deltaFullName, FileMode.Open, FileAccess.Read, FileShare.Read); + await using var deltaStream = LocalPathSafety.OpenRead(deltaFullName); await ApplyDelta(destinationFullName, deltaStream); } public async Task ApplyDelta(string destinationFullName, Stream deltaStream) { + _authorization.ValidatePath(destinationFullName); var deltaApplier = new DeltaApplier { SkipHashCheck = false @@ -69,11 +74,12 @@ public async Task ApplyDelta(string destinationFullName, Stream deltaStream) { // This block is necessary, otherwise the disposals do not occur and the validate temporary file crashes { - await using var basisStream = new FileStream(destinationFullName, FileMode.Open, FileAccess.Read, FileShare.Read); - await using var newFileStream = new FileStream(destinationTemporaryPath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read); + await using var basisStream = LocalPathSafety.OpenRead(destinationFullName); + await using var newFileStream = LocalPathSafety.OpenWrite(destinationTemporaryPath, true, readable: true); await deltaApplier.ApplyAsync(basisStream, new BinaryDeltaReader(deltaStream, null), newFileStream); } + _authorization.ValidatePath(destinationFullName); temporaryFileManager.ValidateTemporaryFile(); } catch (Exception ex) diff --git a/src/ByteSync.Client/Services/Synchronizations/FileDatesSetter.cs b/src/ByteSync.Client/Services/Synchronizations/FileDatesSetter.cs index 6150a6eb7..10a8997d1 100644 --- a/src/ByteSync.Client/Services/Synchronizations/FileDatesSetter.cs +++ b/src/ByteSync.Client/Services/Synchronizations/FileDatesSetter.cs @@ -1,3 +1,4 @@ +using ByteSync.Interfaces.Controls.Inventories; using System.IO; using ByteSync.Business.Actions.Shared; using ByteSync.Business.Communications.Downloading; @@ -8,10 +9,13 @@ namespace ByteSync.Services.Synchronizations; public class FileDatesSetter : IFileDatesSetter { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ILogger _logger; - public FileDatesSetter(ILogger logger) + public FileDatesSetter(ILogger logger, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _logger = logger; } @@ -19,21 +23,20 @@ public Task SetDates(SharedFileDefinition sharedFileDefinition, string finalDest { return Task.Run(() => { + _authorization.ValidatePath(finalDestination); if (downloadTargetDates != null) { _logger.LogInformation("{sharedFileDefinitionId}: Setting CreationTime and LastWriteTime on {FinalDestination}", sharedFileDefinition.Id, finalDestination); - File.SetCreationTimeUtc(finalDestination, downloadTargetDates.CreationTimeUtc); - File.SetLastWriteTimeUtc(finalDestination, downloadTargetDates.LastWriteTimeUtc); + LocalPathSafety.SetDates(finalDestination, downloadTargetDates.CreationTimeUtc, downloadTargetDates.LastWriteTimeUtc); } else { _logger.LogInformation("{sharedFileDefinitionId}: Setting CreationTime and LastWriteTime on {FinalDestination} to now", sharedFileDefinition.Id, finalDestination); - File.SetCreationTimeUtc(finalDestination, DateTime.UtcNow); - File.SetLastWriteTimeUtc(finalDestination, DateTime.UtcNow); + LocalPathSafety.SetDates(finalDestination, DateTime.UtcNow, DateTime.UtcNow); } }); } @@ -42,21 +45,20 @@ public Task SetDates(SharedActionsGroup sharedActionsGroup, string finalDestinat { return Task.Run(() => { + _authorization.ValidatePath(finalDestination); if (downloadTargetDates != null) { _logger.LogInformation("{Type:l}: Setting CreationTime and LastWriteTime on {FinalDestination}", $"Synchronization.{sharedActionsGroup.Operator}", finalDestination); - File.SetCreationTimeUtc(finalDestination, downloadTargetDates.CreationTimeUtc); - File.SetLastWriteTimeUtc(finalDestination, downloadTargetDates.LastWriteTimeUtc); + LocalPathSafety.SetDates(finalDestination, downloadTargetDates.CreationTimeUtc, downloadTargetDates.LastWriteTimeUtc); } else { _logger.LogInformation("{Type:l}: Setting CreationTime and LastWriteTime on {FinalDestination} to now", $"Synchronization.{sharedActionsGroup.Operator}", finalDestination); - File.SetCreationTimeUtc(finalDestination, DateTime.UtcNow); - File.SetLastWriteTimeUtc(finalDestination, DateTime.UtcNow); + LocalPathSafety.SetDates(finalDestination, DateTime.UtcNow, DateTime.UtcNow); } }); } diff --git a/src/ByteSync.Client/Services/Synchronizations/LocalPathSafety.cs b/src/ByteSync.Client/Services/Synchronizations/LocalPathSafety.cs new file mode 100644 index 000000000..6c52d0f4d --- /dev/null +++ b/src/ByteSync.Client/Services/Synchronizations/LocalPathSafety.cs @@ -0,0 +1,368 @@ +using System.Text; +using System.ComponentModel; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; +using System.IO; + +namespace ByteSync.Services.Synchronizations; + +public static class LocalPathSafety +{ + public static StringComparison Comparison => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + public static void ValidateComponent(string? value) + { + ValidateRelativePath(value); + if (string.IsNullOrEmpty(value) || value.Contains('/')) throw new UnauthorizedAccessException("Invalid storage component"); + } + + public static void ValidateRelativePath(string? path) + { + if (path == null || path.Contains('\\') || path.Contains(':') || path.Contains('\0') || path.StartsWith('/') || + Path.IsPathRooted(path)) throw new UnauthorizedAccessException("Invalid relative path"); + if (path == "") return; + foreach (var component in path.Split('/')) + { + if (component is "" or "." or ".." || component.Any(char.IsControl)) throw new UnauthorizedAccessException("Ambiguous relative path"); + if (OperatingSystem.IsWindows()) + { + var basename = component.Split('.')[0]; + if (component.EndsWith(' ') || component.EndsWith('.') || component.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || + new[] { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" }.Contains(basename, StringComparer.OrdinalIgnoreCase)) + throw new UnauthorizedAccessException("Ambiguous Windows path"); + } + } + } + + public static void AssertNoLinks(string path) + { + var fullPath = Path.GetFullPath(path); + var root = Path.GetPathRoot(fullPath)!; + if (OperatingSystem.IsWindows() && root.StartsWith(@"\\")) throw new UnauthorizedAccessException("UNC sources are not supported"); + var current = root; + foreach (var component in fullPath[root.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)) + { + current = Path.Combine(current, component); + try + { + var attributes = File.GetAttributes(current); + if ((attributes & FileAttributes.ReparsePoint) != 0) throw new UnauthorizedAccessException("Links and reparse points are not allowed"); + } + catch (FileNotFoundException) { } + catch (DirectoryNotFoundException) { } + } + } + public static IDisposable Acquire(params string[] paths) => AcquireDirectories(1, paths); + + private static IDisposable AcquireDirectories(uint sharing, params string[] paths) + { + var handles = new List(); + try + { + foreach (var path in paths.Distinct()) + { + AssertNoLinks(path); + if (!OperatingSystem.IsWindows()) continue; + var full = Path.GetFullPath(path); + var current = Path.GetPathRoot(full)!; + foreach (var component in full[current.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)) + { + current = Path.Combine(current, component); + if (current == full || !Directory.Exists(current)) break; + var handle = OpenWindows(current, 0x80000000, sharing, 0x02200000); + handles.Add(handle); + } + } + return new DirectoryLease(handles); + } + catch + { + foreach (var handle in handles) handle.Dispose(); + throw; + } + } + + public static FileStream OpenRead(string path) + { + using var lease = Acquire(path); + if (!OperatingSystem.IsWindows()) return OpenUnixRead(path); + var handle = OpenWindows(path, 0x80000000, 1, 0x00200000); + return new FileStream(handle, FileAccess.Read); + } + + private static FileStream OpenUnixRead(string path) + { + var full = Path.GetFullPath(path); + var noFollow = OperatingSystem.IsMacOS() ? 0x100 : 0x20000; + var directory = OperatingSystem.IsMacOS() ? 0x100000 : 0x10000; + var fd = OpenAt(OperatingSystem.IsMacOS() ? -2 : -100, "/", directory | noFollow, 0); + if (fd < 0) throw new IOException("Cannot open root", new Win32Exception(Marshal.GetLastWin32Error())); + var handle = new SafeFileHandle((IntPtr)fd, true); + try + { + var components = full.TrimStart('/').Split('/'); + for (var i = 0; i < components.Length; i++) + { + var next = OpenAt(handle.DangerousGetHandle().ToInt32(), components[i], (OperatingSystem.IsMacOS() ? 4 : 0x800) | noFollow | (i < components.Length - 1 ? directory : 0), 0); + if (next < 0) throw new IOException("Cannot open file without following links", new Win32Exception(Marshal.GetLastWin32Error())); + handle.Dispose(); + handle = new SafeFileHandle((IntPtr)next, true); + } + AssertUnixRegularFile(handle); + return new FileStream(handle, FileAccess.Read); + } + catch { handle.Dispose(); throw; } + } + + + public static FileStream OpenWrite(string path, bool createNew = false, bool append = false, bool readable = false) + { + using var lease = Acquire(path); + SafeFileHandle handle; + if (OperatingSystem.IsWindows()) + handle = OpenWindows(path, readable ? 0xC0000080u : 0x40000080u, 1, 0x00200000, createNew ? 1u : 4u); + else + { + using var parent = OpenUnixParent(path, out var name); + var flags = (readable ? 2 : 1) | (OperatingSystem.IsMacOS() ? 4 : 0x800) | (OperatingSystem.IsMacOS() ? 0x200 : 0x40) | (OperatingSystem.IsMacOS() ? 0x100 : 0x20000); + if (createNew) flags |= OperatingSystem.IsMacOS() ? 0x800 : 0x80; + var fd = OpenAt(parent.DangerousGetHandle().ToInt32(), name, flags, 0x180); + if (fd < 0) throw new IOException("Cannot open destination", new Win32Exception(Marshal.GetLastWin32Error())); + handle = new SafeFileHandle((IntPtr)fd, true); + } + AssertUnixRegularFile(handle); + var stream = new FileStream(handle, readable ? FileAccess.ReadWrite : FileAccess.Write); + if (append) stream.Seek(0, SeekOrigin.End); + else stream.SetLength(0); + return stream; + } + + public static void CreateDirectory(string path) + { + if (!OperatingSystem.IsWindows()) + { + using var directory = OpenUnixDirectory(path, true); + return; + } + var full = Path.GetFullPath(path); + var current = Path.GetPathRoot(full)!; + var handles = new List(); + try + { + foreach (var component in full[current.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)) + { + current = Path.Combine(current, component); + Directory.CreateDirectory(current); + handles.Add(OpenWindows(current, 0x80000000, 1, 0x02200000)); + } + } + finally { foreach (var handle in handles) handle.Dispose(); } + } + + public static void Move(string source, string destination, bool overwrite = false) + { + if (OperatingSystem.IsWindows()) + { + if (!string.Equals(Path.GetDirectoryName(source), Path.GetDirectoryName(destination), StringComparison.Ordinal)) + throw new UnauthorizedAccessException("Replacement must stay in the same directory"); + using var initialLease = Acquire(source, destination); + using var file = OpenWindows(source, 0x80010080, 1, 0x00200000); + using var renameLease = AcquireDirectories(3, source, destination); + using var parent = OpenWindows(Path.GetDirectoryName(destination)!, 0x80000000, 3, 0x02200000); + initialLease.Dispose(); + var name = Encoding.Unicode.GetBytes(Path.GetFileName(destination)); + var handleOffset = IntPtr.Size == 8 ? 8 : 4; + var lengthOffset = handleOffset + IntPtr.Size; + var nameOffset = lengthOffset + 4; + var buffer = Marshal.AllocHGlobal(nameOffset + name.Length); + try + { + for (var i = 0; i < nameOffset; i++) Marshal.WriteByte(buffer, i, 0); + Marshal.WriteByte(buffer, 0, overwrite ? (byte)1 : (byte)0); + Marshal.WriteIntPtr(buffer, handleOffset, parent.DangerousGetHandle()); + Marshal.WriteInt32(buffer, lengthOffset, name.Length); + Marshal.Copy(name, 0, IntPtr.Add(buffer, nameOffset), name.Length); + var status = NtSetInformationFile(file, out _, buffer, (uint)(nameOffset + name.Length), 10); + if (status != 0) throw new IOException("Cannot replace destination", new Win32Exception((int)RtlNtStatusToDosError(status))); + } + finally { Marshal.FreeHGlobal(buffer); } + return; + } + using var sourceParent = OpenUnixParent(source, out var sourceName); + using var targetParent = OpenUnixParent(destination, out var targetName); + var result = OperatingSystem.IsMacOS() + ? RenameAtMac(sourceParent.DangerousGetHandle().ToInt32(), sourceName, targetParent.DangerousGetHandle().ToInt32(), targetName, overwrite ? 0u : 4u) + : RenameAtLinux(sourceParent.DangerousGetHandle().ToInt32(), sourceName, targetParent.DangerousGetHandle().ToInt32(), targetName, overwrite ? 0u : 1u); + if (result != 0) + throw new IOException("Cannot replace destination", new Win32Exception(Marshal.GetLastWin32Error())); + } + + public static void Delete(string path, bool directory = false) + { + using var lease = Acquire(path); + if (OperatingSystem.IsWindows()) + { + if (directory) Directory.Delete(path, false); else File.Delete(path); + return; + } + using var parent = OpenUnixParent(path, out var name); + if (UnlinkAt(parent.DangerousGetHandle().ToInt32(), name, directory ? (OperatingSystem.IsMacOS() ? 0x80 : 0x200) : 0) != 0 && + Marshal.GetLastWin32Error() != 2) throw new IOException("Cannot delete destination", new Win32Exception(Marshal.GetLastWin32Error())); + } + + public static void SetDates(string path, DateTime creation, DateTime write) + { + using var lease = Acquire(path); + if (OperatingSystem.IsWindows()) + { + using var handle = OpenWindows(path, 0x80000100, 1, 0x00200000); + File.SetCreationTimeUtc(handle, creation); + File.SetLastWriteTimeUtc(handle, write); + } + else + { + using var stream = OpenUnixRead(path); + File.SetCreationTimeUtc(stream.SafeFileHandle, creation); + File.SetLastWriteTimeUtc(stream.SafeFileHandle, write); + } + } + + private static SafeFileHandle OpenUnixParent(string path, out string name) + { + var full = Path.GetFullPath(path); + name = Path.GetFileName(full); + if (name.Length == 0) throw new UnauthorizedAccessException("Cannot operate on a filesystem root"); + return OpenUnixDirectory(Path.GetDirectoryName(full)!, false); + } + + private static SafeFileHandle OpenUnixDirectory(string path, bool create) + { + var flags = OperatingSystem.IsMacOS() ? 0x100100 : 0x30000; + var fd = OpenAt(OperatingSystem.IsMacOS() ? -2 : -100, "/", flags, 0); + if (fd < 0) throw new IOException("Cannot open directory root"); + var handle = new SafeFileHandle((IntPtr)fd, true); + try + { + foreach (var component in Path.GetFullPath(path).Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries)) + { + if (create && MkdirAt(handle.DangerousGetHandle().ToInt32(), component, 0x1C0) != 0 && Marshal.GetLastWin32Error() != 17) + throw new IOException("Cannot create directory", new Win32Exception(Marshal.GetLastWin32Error())); + var next = OpenAt(handle.DangerousGetHandle().ToInt32(), component, flags, 0); + if (next < 0) throw new IOException("Cannot access directory without following links", new Win32Exception(Marshal.GetLastWin32Error())); + handle.Dispose(); + handle = new SafeFileHandle((IntPtr)next, true); + } + return handle; + } + catch { handle.Dispose(); throw; } + } + + [DllImport("libc", SetLastError = true, EntryPoint = "mkdirat")] + private static extern int MkdirAt(int directory, string path, uint mode); + [DllImport("libc", SetLastError = true, EntryPoint = "renameat2")] + private static extern int RenameAtLinux(int sourceDirectory, string source, int targetDirectory, string target, uint flags); + [DllImport("libc", SetLastError = true, EntryPoint = "renameatx_np")] + private static extern int RenameAtMac(int sourceDirectory, string source, int targetDirectory, string target, uint flags); + [DllImport("libc", SetLastError = true, EntryPoint = "unlinkat")] + private static extern int UnlinkAt(int directory, string path, int flags); + + private static SafeFileHandle OpenWindows(string path, uint access, uint share, uint flags, uint disposition = 3) + { + var handle = CreateFile(path, access, share, IntPtr.Zero, disposition, flags, IntPtr.Zero); + if (handle.IsInvalid) { handle.Dispose(); throw new IOException("Cannot acquire path access", new Win32Exception(Marshal.GetLastWin32Error())); } + if (!GetFileInformationByHandleEx(handle, 9, out var info, 8) || (info.Attributes & FileAttributes.ReparsePoint) != 0) + { + handle.Dispose(); + throw new UnauthorizedAccessException("Links and reparse points are not allowed"); + } + if ((info.Attributes & FileAttributes.Directory) == 0 && + (!GetFileInformationByHandle(handle, out var fileInfo) || fileInfo.LinkCount != 1)) + { + handle.Dispose(); + throw new UnauthorizedAccessException("Hard-linked files are not allowed"); + } + return handle; + } + + private static void AssertUnixRegularFile(SafeFileHandle handle) + { + if (OperatingSystem.IsWindows()) return; + UnixFileInformation info; + var result = OperatingSystem.IsMacOS() && RuntimeInformation.ProcessArchitecture == Architecture.X64 + ? FStatMac64(handle.DangerousGetHandle().ToInt32(), out info) + : FStat(handle.DangerousGetHandle().ToInt32(), out info); + if (result != 0) + { + handle.Dispose(); + throw new IOException("Cannot inspect opened file"); + } + var mac = OperatingSystem.IsMacOS(); + var arm = RuntimeInformation.ProcessArchitecture == Architecture.Arm64; + if (!mac && RuntimeInformation.ProcessArchitecture is not (Architecture.X64 or Architecture.Arm64)) + { + handle.Dispose(); + throw new PlatformNotSupportedException("Unsupported filesystem ABI"); + } + var links = mac ? info.MacLinks : arm ? info.LinuxArmLinks : info.LinuxX64Links; + var mode = mac ? info.MacMode : arm ? info.LinuxArmMode : info.LinuxX64Mode; + if (links != 1 || (mode & 0xF000) != 0x8000) + { + handle.Dispose(); + throw new UnauthorizedAccessException("Only regular files with one link are allowed"); + } + } + + [StructLayout(LayoutKind.Explicit, Size = 256)] + private struct UnixFileInformation + { + [FieldOffset(16)] public ulong LinuxX64Links; + [FieldOffset(24)] public uint LinuxX64Mode; + [FieldOffset(20)] public uint LinuxArmLinks; + [FieldOffset(16)] public uint LinuxArmMode; + [FieldOffset(6)] public ushort MacLinks; + [FieldOffset(4)] public ushort MacMode; + } + + [StructLayout(LayoutKind.Explicit, Size = 52)] + private struct WindowsFileInformation + { + [FieldOffset(40)] public uint LinkCount; + } + + [DllImport("libc", SetLastError = true, EntryPoint = "fstat")] + private static extern int FStat(int descriptor, out UnixFileInformation information); + [DllImport("libc", SetLastError = true, EntryPoint = "fstat$INODE64")] + private static extern int FStatMac64(int descriptor, out UnixFileInformation information); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetFileInformationByHandle(SafeFileHandle handle, out WindowsFileInformation information); + + [StructLayout(LayoutKind.Sequential)] + private struct IoStatusBlock { public IntPtr Status; public UIntPtr Information; } + + [DllImport("ntdll.dll")] + private static extern int NtSetInformationFile(SafeFileHandle handle, out IoStatusBlock status, IntPtr information, uint length, int kind); + + [DllImport("ntdll.dll")] + private static extern uint RtlNtStatusToDosError(int status); + + private sealed class DirectoryLease(List handles) : IDisposable + { + public void Dispose() { foreach (var handle in handles) handle.Dispose(); } + } + + [StructLayout(LayoutKind.Sequential)] + private struct AttributeTagInfo { public FileAttributes Attributes; public uint Tag; } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CreateFileW")] + private static extern SafeFileHandle CreateFile(string name, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetFileInformationByHandleEx(SafeFileHandle handle, int kind, out AttributeTagInfo info, uint size); + + [DllImport("libc", SetLastError = true, EntryPoint = "openat")] + private static extern int OpenAt(int directory, string path, int flags, uint mode); + +} diff --git a/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionHandler.cs b/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionHandler.cs index ec5385449..a11666237 100644 --- a/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionHandler.cs +++ b/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionHandler.cs @@ -1,4 +1,5 @@ -using System.IO; +using ByteSync.Interfaces.Controls.Inventories; +using System.IO; using System.Threading; using ByteSync.Business.Actions.Shared; using ByteSync.Business.Communications.Downloading; @@ -16,6 +17,8 @@ namespace ByteSync.Services.Synchronizations; public class SynchronizationActionHandler : ISynchronizationActionHandler { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ISessionService _sessionService; private readonly IConnectionService _connectionService; private readonly IDeltaManager _deltaManager; @@ -31,8 +34,9 @@ public SynchronizationActionHandler(ISessionService sessionService, IConnectionS ISynchronizationActionRemoteUploader synchronizationActionRemoteUploader, ISynchronizationService synchronizationService, ISynchronizationApiClient synchronizationApiClient, IFileDatesSetter fileDatesSetter, - ILogger logger) + ILogger logger, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _sessionService = sessionService; _connectionService = connectionService; _deltaManager = deltaManager; @@ -51,6 +55,7 @@ public async Task RunSynchronizationAction(SharedActionsGroup sharedActionsGroup try { cancellationToken.ThrowIfCancellationRequested(); + _authorization.ValidatePlan(new[] { sharedActionsGroup }); if (sharedActionsGroup.IsCopyContentOnly || sharedActionsGroup.IsFinallyCopyContentAndDate) { @@ -137,6 +142,7 @@ private async Task RunCopyContentLocal(SharedActionsGroup sharedActionsGroup, Ha foreach (var localTarget in localTargets) { cancellationToken.ThrowIfCancellationRequested(); + _authorization.ValidatePlan(new[] { sharedActionsGroup }); var destinationFullName = sharedActionsGroup.GetFullName(localTarget); @@ -149,7 +155,7 @@ private async Task RunCopyContentLocal(SharedActionsGroup sharedActionsGroup, Ha _logger.LogInformation("{Type:l}: creating directory {directory}", $"Synchronization.{sharedActionsGroup.Operator}", destinationFileInfo.Directory); - destinationFileInfo.Directory.Create(); + LocalPathSafety.CreateDirectory(destinationFileInfo.Directory.FullName); } _logger.LogInformation("{Type:l}: copying from {source} to {destination}", @@ -157,7 +163,16 @@ private async Task RunCopyContentLocal(SharedActionsGroup sharedActionsGroup, Ha // For full copy, the transferred volume equals the file size transferredBytes = new FileInfo(sourceFullName).Length; - File.Copy(sourceFullName, destinationFullName, true); + var temporary = destinationFullName + "." + Guid.NewGuid().ToString("N") + ".bstemp"; + try + { + using (var input = LocalPathSafety.OpenRead(sourceFullName)) + using (var output = LocalPathSafety.OpenWrite(temporary, true)) input.CopyTo(output); + _authorization.ValidateDestination(sharedActionsGroup, destinationFullName); + LocalPathSafety.AssertNoLinks(destinationFullName); + LocalPathSafety.Move(temporary, destinationFullName, true); + } + finally { if (File.Exists(temporary)) File.Delete(temporary); } await ApplyDatesFromLocalSource(sharedActionsGroup, destinationFullName); } @@ -255,8 +270,10 @@ private async Task RunCopyDateSynchronizationAction(SharedActionsGroup sharedAct foreach (var localTarget in localTargets) { var destinationPath = sharedActionsGroup.GetFullName(localTarget); + using var access = LocalPathSafety.Acquire(destinationPath); cancellationToken.ThrowIfCancellationRequested(); + _authorization.ValidatePlan(new[] { sharedActionsGroup }); if (File.Exists(destinationPath)) { @@ -282,8 +299,10 @@ private async Task RunDeleteSynchronizationAction(SharedActionsGroup sharedActio foreach (var localTarget in localTargets) { var destinationPath = sharedActionsGroup.GetFullName(localTarget); + using var access = LocalPathSafety.Acquire(destinationPath); cancellationToken.ThrowIfCancellationRequested(); + _authorization.ValidatePlan(new[] { sharedActionsGroup }); if (sharedActionsGroup.IsFile && File.Exists(destinationPath)) { @@ -291,7 +310,7 @@ private async Task RunDeleteSynchronizationAction(SharedActionsGroup sharedActio _logger.LogInformation("{Type:l}: deleting {fileInfo}", $"Synchronization.{sharedActionsGroup.Operator}", fileInfo.FullName); - fileInfo.Delete(); + LocalPathSafety.Delete(fileInfo.FullName); } else if (sharedActionsGroup.IsDirectory && Directory.Exists(destinationPath)) { @@ -300,8 +319,7 @@ private async Task RunDeleteSynchronizationAction(SharedActionsGroup sharedActio _logger.LogInformation("{Type:l}: deleting {fileInfo}", $"Synchronization.{sharedActionsGroup.Operator}", directoryInfo.FullName); - var subFilesCount = directoryInfo.GetFiles("*", SearchOption.AllDirectories).Length; - directoryInfo.Delete(subFilesCount == 0); + LocalPathSafety.Delete(directoryInfo.FullName, true); } else { @@ -321,7 +339,9 @@ private async Task RunCreateSynchronizationAction(SharedActionsGroup sharedActio foreach (var localTarget in localTargets) { var destinationPath = sharedActionsGroup.GetFullName(localTarget); + using var access = LocalPathSafety.Acquire(destinationPath); cancellationToken.ThrowIfCancellationRequested(); + _authorization.ValidatePlan(new[] { sharedActionsGroup }); if (sharedActionsGroup.PathIdentity.FileSystemType == FileSystemTypes.Directory) { @@ -332,7 +352,7 @@ private async Task RunCreateSynchronizationAction(SharedActionsGroup sharedActio _logger.LogInformation("{Type:l}: creating {directoryInfo}", $"Synchronization.{sharedActionsGroup.Operator}", directoryInfo.FullName); - directoryInfo.Create(); + LocalPathSafety.CreateDirectory(directoryInfo.FullName); } else { diff --git a/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionRemoteUploader.cs b/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionRemoteUploader.cs index 3dd87ee28..8edaed068 100644 --- a/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionRemoteUploader.cs +++ b/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionRemoteUploader.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Threading; using ByteSync.Business.Actions.Shared; using ByteSync.Business.Synchronizations; @@ -122,6 +122,8 @@ public async Task UploadForRemote(SharedActionsGroup sharedActionsGroup) try { + sharedActionsGroup.GetSourceFullName(); + _currentMultiUploadZip.AccessValidators.Add(() => sharedActionsGroup.GetSourceFullName()); _currentMultiUploadZip.AddEntry(fileInfo, sharedActionsGroup.ActionsGroupId); } catch (Exception ex) @@ -146,6 +148,7 @@ public async Task UploadForRemote(SharedActionsGroup sharedActionsGroup) $"Synchronization.{sharedActionsGroup.Operator}", localFullName, deltaFullName != null); var fileUploader = _fileUploaderFactory.Build(uploadFullName, sharedFileDefinition); + fileUploader.ValidateAccess = () => sharedActionsGroup.GetSourceFullName(); var uploadTask = RunUploadTask(sharedActionsGroup, fileUploader, () => DeleteDeltaFile(deltaFullName)); @@ -158,7 +161,7 @@ private void DeleteDeltaFile(string? deltaFullName) if (deltaFullName != null) { _logger.LogInformation("Deleting delta file {delta}", deltaFullName); - File.Delete(deltaFullName); + LocalPathSafety.Delete(deltaFullName); } } @@ -232,6 +235,7 @@ private async Task CloseAndUploadCurrentMultiZip() var currentMultiUploadZip = _currentMultiUploadZip; var fileUploader = _fileUploaderFactory.Build(currentMultiUploadZip.MemoryStream, currentMultiUploadZip.SharedFileDefinition); + fileUploader.ValidateAccess = () => { foreach (var validate in currentMultiUploadZip.AccessValidators) validate(); }; var uploadTask = RunUploadTask(currentMultiUploadZip.ActionGroupsIds, fileUploader, () => currentMultiUploadZip.Dispose()); UploadTasks.Add(uploadTask); diff --git a/src/ByteSync.Client/Services/Synchronizations/SynchronizationDataReceiver.cs b/src/ByteSync.Client/Services/Synchronizations/SynchronizationDataReceiver.cs index dcc456cbd..c6e04ab97 100644 --- a/src/ByteSync.Client/Services/Synchronizations/SynchronizationDataReceiver.cs +++ b/src/ByteSync.Client/Services/Synchronizations/SynchronizationDataReceiver.cs @@ -1,4 +1,5 @@ -using ByteSync.Business.Actions.Shared; +using ByteSync.Interfaces.Controls.Inventories; +using ByteSync.Business.Actions.Shared; using ByteSync.Business.Communications; using ByteSync.Interfaces.Controls.Actions; using ByteSync.Interfaces.Controls.Synchronizations; @@ -10,6 +11,8 @@ namespace ByteSync.Services.Synchronizations; public class SynchronizationDataReceiver : ISynchronizationDataReceiver { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ICloudSessionLocalDataManager _cloudSessionLocalDataManager; private readonly ISharedAtomicActionRepository _sharedAtomicActionRepository; private readonly ISharedActionsGroupRepository _sharedActionsGroupRepository; @@ -19,8 +22,9 @@ public class SynchronizationDataReceiver : ISynchronizationDataReceiver public SynchronizationDataReceiver(ICloudSessionLocalDataManager cloudSessionLocalDataManager, ISharedAtomicActionRepository sharedAtomicActionRepository, ISharedActionsGroupRepository sharedActionsGroupRepository, ISynchronizationService synchronizationService, - ISharedActionsGroupOrganizer sharedActionsGroupOrganizer, ISynchronizationDataLogger synchronizationDataLogger) + ISharedActionsGroupOrganizer sharedActionsGroupOrganizer, ISynchronizationDataLogger synchronizationDataLogger, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _cloudSessionLocalDataManager = cloudSessionLocalDataManager; _sharedAtomicActionRepository = sharedAtomicActionRepository; _sharedActionsGroupRepository = sharedActionsGroupRepository; @@ -35,11 +39,15 @@ public async Task OnSynchronizationDataFileDownloaded(LocalSharedFile downloadTa var synchronizationDataSaver = new SynchronizationDataSaver(); var synchronizationData = synchronizationDataSaver.Load(synchronizationDataPath); + if (synchronizationData.SessionId != downloadTargetLocalSharedFile.SharedFileDefinition.SessionId || + synchronizationData.Endpoint.ClientInstanceId != downloadTargetLocalSharedFile.SharedFileDefinition.ClientInstanceId) + throw new UnauthorizedAccessException("Synchronization plan sender mismatch"); await SetSynchronizationStartData(synchronizationData); } private async Task SetSynchronizationStartData(SharedSynchronizationStartData sharedSynchronizationStartData) { + _authorization.ValidatePlan(sharedSynchronizationStartData.SharedActionsGroups); _sharedAtomicActionRepository.SetSharedAtomicActions(sharedSynchronizationStartData.SharedAtomicActions); _sharedActionsGroupRepository.SetSharedActionsGroups(sharedSynchronizationStartData.SharedActionsGroups); diff --git a/src/ByteSync.Client/Services/Synchronizations/SynchronizationService.cs b/src/ByteSync.Client/Services/Synchronizations/SynchronizationService.cs index a1709a1cf..6740dce7b 100644 --- a/src/ByteSync.Client/Services/Synchronizations/SynchronizationService.cs +++ b/src/ByteSync.Client/Services/Synchronizations/SynchronizationService.cs @@ -1,4 +1,5 @@ -using System.Reactive.Linq; +using ByteSync.Interfaces.Controls.Inventories; +using System.Reactive.Linq; using ByteSync.Business.Actions.Shared; using ByteSync.Business.Misc; using ByteSync.Business.Sessions; @@ -16,6 +17,8 @@ namespace ByteSync.Services.Synchronizations; public class SynchronizationService : ISynchronizationService { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ISessionService _sessionService; private readonly ISessionMemberService _sessionMemberService; private readonly ISynchronizationApiClient _synchronizationApiClient; @@ -26,8 +29,9 @@ public class SynchronizationService : ISynchronizationService public SynchronizationService(ISessionService sessionService, ISessionMemberService sessionMemberService, ISynchronizationApiClient synchronizationApiClient, ISynchronizationLooperFactory synchronizationLooperFactory, ITimeTrackingCache timeTrackingCache, - ILogger logger) + ILogger logger, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _sessionService = sessionService; _sessionMemberService = sessionMemberService; _synchronizationApiClient = synchronizationApiClient; @@ -130,6 +134,7 @@ public async Task OnSynchronizationStarted(Synchronization synchronization) public Task OnSynchronizationDataTransmitted(SharedSynchronizationStartData sharedSynchronizationStartData) { + _authorization.ValidatePlan(sharedSynchronizationStartData.SharedActionsGroups); SynchronizationProcessData.TotalVolumeToProcess = sharedSynchronizationStartData.TotalVolumeToProcess; SynchronizationProcessData.TotalActionsToProcess = sharedSynchronizationStartData.TotalAtomicActionsToProcess; diff --git a/src/ByteSync.Client/Services/Synchronizations/SynchronizationStartFactory.cs b/src/ByteSync.Client/Services/Synchronizations/SynchronizationStartFactory.cs index f2fad6a4a..955bf4cd1 100644 --- a/src/ByteSync.Client/Services/Synchronizations/SynchronizationStartFactory.cs +++ b/src/ByteSync.Client/Services/Synchronizations/SynchronizationStartFactory.cs @@ -1,4 +1,5 @@ -using ByteSync.Business.Actions.Shared; +using ByteSync.Interfaces.Controls.Inventories; +using ByteSync.Business.Actions.Shared; using ByteSync.Interfaces.Controls.Actions; using ByteSync.Interfaces.Controls.Synchronizations; using ByteSync.Interfaces.Repositories; @@ -9,6 +10,8 @@ namespace ByteSync.Services.Synchronizations; public class SynchronizationStartFactory : ISynchronizationStartFactory { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ISharedAtomicActionComputer _sharedAtomicActionComputer; private readonly ISynchronizationRulesService _synchronizationRulesService; private readonly ISharedActionsGroupComputer _sharedActionsGroupComputer; @@ -20,8 +23,9 @@ public class SynchronizationStartFactory : ISynchronizationStartFactory public SynchronizationStartFactory(ISharedAtomicActionComputer sharedAtomicActionComputer, ISynchronizationRulesService synchronizationRulesService, ISharedActionsGroupComputer sharedActionsGroupComputer, ISessionService sessionService, IConnectionService connectionService, ISharedActionsGroupOrganizer sharedActionsGroupOrganizer, - ISharedActionsGroupRepository sharedActionsGroupRepository) + ISharedActionsGroupRepository sharedActionsGroupRepository, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _sharedAtomicActionComputer = sharedAtomicActionComputer; _synchronizationRulesService = synchronizationRulesService; _sharedActionsGroupComputer = sharedActionsGroupComputer; @@ -39,6 +43,7 @@ public async Task PrepareSharedData() var sharedActionsGroups = _sharedActionsGroupRepository.Elements.ToList(); + _authorization.ValidatePlan(sharedActionsGroups); await _sharedActionsGroupOrganizer.OrganizeSharedActionGroups(); var looseSynchronizationRules = _synchronizationRulesService.GetLooseSynchronizationRules(); diff --git a/src/ByteSync.Client/Services/Synchronizations/TemporaryFileManager.cs b/src/ByteSync.Client/Services/Synchronizations/TemporaryFileManager.cs index c73f7d294..62d053d85 100644 --- a/src/ByteSync.Client/Services/Synchronizations/TemporaryFileManager.cs +++ b/src/ByteSync.Client/Services/Synchronizations/TemporaryFileManager.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using ByteSync.Interfaces.Controls.Synchronizations; namespace ByteSync.Services.Synchronizations; @@ -10,10 +10,10 @@ public class TemporaryFileManager : ITemporaryFileManager public TemporaryFileManager(string destinationFullName, ILogger logger) { _logger = logger; - + Reset(destinationFullName); } - + private void Reset(string destinationFullName) { DestinationFullName = destinationFullName; @@ -29,13 +29,13 @@ private void Reset(string destinationFullName) } public string DestinationFullName { get; set; } = null!; - + public string? DestinationTemporaryPath { get; set; } - + public string? PreviousFileTemporaryPath { get; set; } - + public bool HasValidationStarted { get; set; } - + public bool PreviousFileExistsBeforeValidation { get; set; } public bool WasPreviousFileMovedToTemp { get; set; } @@ -53,43 +53,34 @@ public string GetDestinationTemporaryPath() private string GetTemporaryPath() { - var cpt = 0; - var temporaryPath = DestinationFullName + $".bstemp_t{cpt}$"; - - while (File.Exists(temporaryPath)) - { - cpt += 1; - temporaryPath = DestinationFullName + $".bstemp_t{cpt}$"; - } - - return temporaryPath; + return DestinationFullName + "." + Guid.NewGuid().ToString("N") + ".bstemp"; } public void ValidateTemporaryFile() { HasValidationStarted = true; - + // Rename the existing file to “.bstemp_t$” if (File.Exists(DestinationFullName)) { PreviousFileExistsBeforeValidation = true; - + PreviousFileTemporaryPath = GetTemporaryPath(); - File.Move(DestinationFullName, PreviousFileTemporaryPath); - + LocalPathSafety.Move(DestinationFullName, PreviousFileTemporaryPath); + WasPreviousFileMovedToTemp = true; } // Rename the merged file to its final name - File.Move(DestinationTemporaryPath!, DestinationFullName); - + LocalPathSafety.Move(DestinationTemporaryPath!, DestinationFullName); + WasNewFileMovedFromTemp = true; if (PreviousFileExistsBeforeValidation) { // The old file is deleted - File.Delete(PreviousFileTemporaryPath!); - + LocalPathSafety.Delete(PreviousFileTemporaryPath!); + WasPreviousFileDeleted = true; } } @@ -98,7 +89,7 @@ public void TryRevertOnError(Exception exception) { try { - _logger.LogWarning("An exception has occurred during validation operations on file {file}: {type} - {message}. Trying to revert operation", + _logger.LogWarning("An exception has occurred during validation operations on file {file}: {type} - {message}. Trying to revert operation", DestinationFullName, exception.GetType().Name, exception.Message); if (!HasValidationStarted) { @@ -106,7 +97,7 @@ public void TryRevertOnError(Exception exception) if (File.Exists(DestinationTemporaryPath)) { _logger.LogWarning("Deleting {file}", DestinationTemporaryPath); - File.Delete(DestinationTemporaryPath); + LocalPathSafety.Delete(DestinationTemporaryPath); } else { @@ -125,7 +116,7 @@ public void TryRevertOnError(Exception exception) _logger.LogWarning("nothing seems to be undone here"); } } - else + else { // We go back from the end to the beginning if (WasPreviousFileDeleted) @@ -140,7 +131,7 @@ public void TryRevertOnError(Exception exception) else if (WasPreviousFileMovedToTemp) { _logger.LogWarning("The previous version of the file may still exist at location {previous}, " + - "while the new version of the file may be found at location {new}", + "while the new version of the file may be found at location {new}", PreviousFileTemporaryPath, DestinationTemporaryPath); } else @@ -152,7 +143,7 @@ public void TryRevertOnError(Exception exception) if (File.Exists(DestinationTemporaryPath)) { _logger.LogWarning("Deleting {file}", DestinationTemporaryPath); - File.Delete(DestinationTemporaryPath); + LocalPathSafety.Delete(DestinationTemporaryPath); } else { @@ -166,4 +157,4 @@ public void TryRevertOnError(Exception exception) _logger.LogError(ex, "A new exception has occurred, while trying to undo the effects on file {file}", DestinationFullName); } } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/ViewModels/Headers/ConnectionStatusViewModel.cs b/src/ByteSync.Client/ViewModels/Headers/ConnectionStatusViewModel.cs index 67d7e0943..e0c1e66d3 100644 --- a/src/ByteSync.Client/ViewModels/Headers/ConnectionStatusViewModel.cs +++ b/src/ByteSync.Client/ViewModels/Headers/ConnectionStatusViewModel.cs @@ -82,6 +82,7 @@ private void SetBrush() ConnectionStatuses.Connected => ConnectedBadgeBrush, ConnectionStatuses.Connecting => ConnectingBadgeBrush, ConnectionStatuses.ConnectionFailed => ConnectionFailedBadgeBrush, + ConnectionStatuses.RelayIncompatible => ConnectionFailedBadgeBrush, ConnectionStatuses.NotConnected => NotConnectedBadgeBrush, ConnectionStatuses.RetryConnectingSoon => RetryConnectingSoonBadgeBrush, _ => UnknownBadgeBrush @@ -109,15 +110,23 @@ private void SetText() ConnectionStatuses.Connected => _localizationService[nameof(Resources.ConnectionStatus_Connected)], ConnectionStatuses.Connecting => _localizationService[nameof(Resources.ConnectionStatus_Connecting)], ConnectionStatuses.ConnectionFailed => _localizationService[nameof(Resources.ConnectionStatus_ConnectionFailed)], + ConnectionStatuses.RelayIncompatible => _localizationService["ConnectionStatus_RelayIncompatible"], ConnectionStatuses.NotConnected => _localizationService[nameof(Resources.ConnectionStatus_NotConnected)], ConnectionStatuses.RetryConnectingSoon => _localizationService[nameof(Resources.ConnectionStatus_RetryConnectingSoon)], _ => _localizationService[nameof(Resources.ConnectionStatus_Unkown)] }; + + Details = connectionStatus == ConnectionStatuses.RelayIncompatible + ? _localizationService["ConnectionStatus_RelayIncompatibleDetails"] + : null; } [Reactive] public string Text { get; set; } + + [Reactive] + public string? Details { get; set; } [Reactive] public IBrush BadgeBrush { get; set; } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/ViewModels/TrustedNetworks/TrustedNetworkViewModel.cs b/src/ByteSync.Client/ViewModels/TrustedNetworks/TrustedNetworkViewModel.cs index d911a897d..160ac8111 100644 --- a/src/ByteSync.Client/ViewModels/TrustedNetworks/TrustedNetworkViewModel.cs +++ b/src/ByteSync.Client/ViewModels/TrustedNetworks/TrustedNetworkViewModel.cs @@ -1,4 +1,9 @@ -using System.Reactive; +using ByteSync.Interfaces.Services.Sessions; +using ByteSync.Interfaces.Services.Communications; +using ByteSync.Interfaces.Repositories; +using ByteSync.Business.Sessions; +using ByteSync.Business.Communications; +using System.Reactive; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Runtime.CompilerServices; @@ -40,7 +45,8 @@ public TrustedNetworkViewModel() public TrustedNetworkViewModel(IPublicKeysManager publicKeysManager, IApplicationSettingsRepository applicationSettingsManager, TrustedPublicKeysViewModel trustedPublicKeysViewModel, - IMessageBoxViewModelFactory messageBoxViewModelFactory) + IMessageBoxViewModelFactory messageBoxViewModelFactory, ISessionService session, + ICloudSessionConnectionRepository sessionConnection, IConnectionService connection) { #if DEBUG if (Design.IsDesignMode) @@ -56,7 +62,11 @@ public TrustedNetworkViewModel(IPublicKeysManager publicKeysManager, _messageBoxViewModelFactory = messageBoxViewModelFactory; var canRun = new BehaviorSubject(true); - RenewPublicKeyCommand = ReactiveCommand.CreateFromTask(RenewPublicKey, canRun); + var canRenew = Observable.CombineLatest(canRun, session.SessionObservable, + sessionConnection.ConnectionStatusObservable, connection.ConnectionStatus, + (idle, currentSession, sessionStatus, connectionStatus) => idle && currentSession == null && + sessionStatus == SessionConnectionStatus.NoSession && connectionStatus != ConnectionStatuses.Connecting); + RenewPublicKeyCommand = ReactiveCommand.CreateFromTask(RenewPublicKey, canRenew); DeleteTrustedPublicKeyCommand = ReactiveCommand.CreateFromTask(DeleteTrustedPublicKey, canRun); Observable.Merge(RenewPublicKeyCommand.IsExecuting, DeleteTrustedPublicKeyCommand.IsExecuting) .Select(executing => !executing).Subscribe(canRun); @@ -95,12 +105,12 @@ private async Task DeleteTrustedPublicKey(TrustedPublicKeyViewModel trustedPubli await AskAndDo(nameof(Resources.TrustedPublicKeyView_DeleteTrustedPublicKey_Title), nameof(Resources.TrustedPublicKeyView_DeleteTrustedPublicKey_Message), new string[] {trustedPublicKeyViewModel.ClientId, trustedPublicKeyViewModel.TrustedPublicKey.PublicKeyHash}, - () => _publicKeysManager.Delete(trustedPublicKeyViewModel.TrustedPublicKey)); + () => { _publicKeysManager.Delete(trustedPublicKeyViewModel.TrustedPublicKey); return Task.CompletedTask; }); TrustedPublicKeys.Refresh(); } - private async Task AskAndDo(string title, string message, string[]? messageArguments, Action action, + private async Task AskAndDo(string title, string message, string[]? messageArguments, Func action, [CallerMemberName] string caller = "") { try @@ -112,7 +122,7 @@ private async Task AskAndDo(string title, string message, string[]? messageArgum if (result == MessageBoxResult.Yes) { - action.Invoke(); + await action(); } } catch (Exception ex) diff --git a/src/ByteSync.Client/Views/Headers/ConnectionStatusView.axaml b/src/ByteSync.Client/Views/Headers/ConnectionStatusView.axaml index 7ea5afcc6..92292763c 100644 --- a/src/ByteSync.Client/Views/Headers/ConnectionStatusView.axaml +++ b/src/ByteSync.Client/Views/Headers/ConnectionStatusView.axaml @@ -12,7 +12,8 @@ - + diff --git a/src/ByteSync.Client/Views/TrustedNetworks/TrustedNetworkView.axaml b/src/ByteSync.Client/Views/TrustedNetworks/TrustedNetworkView.axaml index 9847e098e..a0b00540f 100644 --- a/src/ByteSync.Client/Views/TrustedNetworks/TrustedNetworkView.axaml +++ b/src/ByteSync.Client/Views/TrustedNetworks/TrustedNetworkView.axaml @@ -16,6 +16,7 @@