// // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ // █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ // ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ // │ Copyright (c) JP Dillingham. // │ // │ This program is free software: you can redistribute it and/or modify // │ it under the terms of the GNU Affero General Public License as published // │ by the Free Software Foundation, version 3. // │ // │ This program is distributed in the hope that it will be useful, // │ but WITHOUT ANY WARRANTY; without even the implied warranty of // │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // │ GNU Affero General Public License for more details. // │ // │ You should have received a copy of the GNU Affero General Public License // │ along with this program. If not, see https://www.gnu.org/licenses/. // │ // │ This program is distributed with Additional Terms pursuant to Section 7 // │ of the AGPLv3. See the LICENSE file in the root directory of this // │ project for the complete terms and conditions. // │ // │ https://slskd.org // │ // ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ // │ SPDX-FileCopyrightText: JP Dillingham // │ SPDX-License-Identifier: AGPL-3.0-only // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // using Microsoft.Extensions.Options; namespace slskd.Relay { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Net.Http.Headers; using Serilog; using slskd.Shares; /// /// Relay. /// [Route("api/v{version:apiVersion}/[controller]")] [ApiVersion("0")] [ApiController] public class RelayController : ControllerBase { private const long ONE_GIBIBYTE = 1L * 1024L * 1024L * 1024L; // 1073741824 private const long ONE_TEBIBYTE = 1024L * ONE_GIBIBYTE; // 1099511627776 /// /// Initializes a new instance of the class. /// /// /// /// public RelayController( IRelayService relayService, IOptionsMonitor optionsMonitor, OptionsAtStartup optionsAtStartup) { Relay = relayService; OptionsMonitor = optionsMonitor; OptionsAtStartup = optionsAtStartup; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IRelayService Relay { get; } private OptionsAtStartup OptionsAtStartup { get; } private RelayMode OperationMode => OptionsAtStartup.Relay.Mode.ToEnum(); private IOptionsMonitor OptionsMonitor { get; } /// /// Connects to the configured controller. /// /// [HttpPut("agent")] [Authorize(Policy = AuthPolicy.JwtOnly, Roles = AuthRole.AdministratorOnly)] public async Task Connect() { if (!OptionsAtStartup.Relay.Enabled || !new[] { RelayMode.Agent, RelayMode.Debug }.Contains(OperationMode)) { return Forbid(); } await Relay.Client.StartAsync(); return Ok(); } /// /// Disconnects from the connected controller. /// /// [HttpDelete("agent")] [Authorize(Policy = AuthPolicy.JwtOnly, Roles = AuthRole.AdministratorOnly)] public async Task Disconnect() { if (!OptionsAtStartup.Relay.Enabled || !new[] { RelayMode.Agent, RelayMode.Debug }.Contains(OperationMode)) { return Forbid(); } await Relay.Client.StopAsync(); return NoContent(); } /// /// Downloads a file from the connected controller. /// /// The unique identifier for the request. /// [HttpGet("controller/downloads/{token}")] [Authorize(Policy = AuthPolicy.ApiKeyOnly, Roles = AuthRole.Any)] public IActionResult DownloadFile([FromRoute] string token) { if (!OptionsAtStartup.Relay.Enabled || !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OperationMode)) { return Forbid(); } if (!Guid.TryParse(token, out var guid)) { return BadRequest("Token is not in a valid format"); } var agentName = Request.Headers["X-Relay-Agent"].FirstOrDefault(); var credential = Request.Headers["X-Relay-Credential"].FirstOrDefault(); var filename = Request.Headers["X-Relay-Filename-Base64"].FirstOrDefault()?.FromBase64(); if (!Relay.RegisteredAgents.Any(a => a.Name == agentName) || string.IsNullOrEmpty(credential)) { return Unauthorized(); } if (string.IsNullOrEmpty(filename)) { return BadRequest(); } // check the path; the caller has a valid API key but we haven't validated the credential yet, so this is worth // doing here instead of relying on the CombineSafely() backstop if (FileSafety.ContainsTraversalSegments(filename)) { Log.Warning("Suspicious attempt to download a file containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); return BadRequest(); } Log.Information("Handling file download of {Filename} ({Token}) from a caller claiming to be agent {Agent}", filename, token, agentName); // note: the token remains valid after the validation attempt, unlike most other endpoints. // this is done to support retries if (!Relay.TryValidateFileDownloadCredential(token: guid, agentName, filename, credential)) { Log.Warning("Failed to authenticate file upload token {Token} from a caller claiming to be agent {Agent}", guid, agentName); return Unauthorized(); } // if we get this far, the caller has supplied a valid credential and filename, meaning the request // to download is being made in response to the controller signaling the agent that a download had completed. // it's not possible for the client to download arbitrary files; credentials are computed from a token, and // this token is cached in the controller, so only file downloads that the controller solicited are possible // still, for the abundance of caution, use the CombineSafely method in case the filename has traversal segments var sourceFile = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, filename); Log.Information("Agent {Agent} authenticated for token {Token}. Sending file {Filename}", agentName, guid, filename); var stream = new FileStream(sourceFile, FileMode.Open); return File(stream, "application/octet-stream"); } /// /// Uploads a file to the connected controller. /// /// The unique identifier for the request. /// [HttpPost("controller/files/{token}")] [RequestSizeLimit(10L * ONE_TEBIBYTE)] [RequestFormLimits(MultipartBodyLengthLimit = 10L * ONE_TEBIBYTE)] [DisableFormValueModelBinding] [Authorize(Policy = AuthPolicy.ApiKeyOnly, Roles = AuthRole.ReadWriteOrAdministrator)] public async Task UploadFile(string token) { if (!OptionsAtStartup.Relay.Enabled || !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OperationMode)) { return Forbid(); } if (!Guid.TryParse(token, out var guid)) { return BadRequest("Token is not in a valid format"); } if (!Request.HasFormContentType || !MediaTypeHeaderValue.TryParse(Request.ContentType, out var mediaTypeHeader) || string.IsNullOrEmpty(mediaTypeHeader.Boundary.Value)) { return new UnsupportedMediaTypeResult(); } var agentName = Request.Headers["X-Relay-Agent"].FirstOrDefault(); var credential = Request.Headers["X-Relay-Credential"].FirstOrDefault(); if (!Relay.RegisteredAgents.Any(a => a.Name == agentName) || string.IsNullOrEmpty(credential)) { return Unauthorized(); } Stream stream = default; string filename = default; try { try { // note: while the actual HTTP request is the same as the one we use for uploading shares, we handle it // differently so that we can capture the stream 'in flight' and avoid any buffering. resist the urge to // refactor one or the other to make them match! var reader = new MultipartReader(HeaderUtilities.RemoveQuotes(mediaTypeHeader.Boundary).Value, Request.Body); var fileSection = await reader.ReadNextSectionAsync(); var contentDisposition = ContentDispositionHeaderValue.Parse(fileSection.ContentDisposition); filename = contentDisposition.FileName.Value; stream = fileSection.Body; if (string.IsNullOrEmpty(filename)) { throw new ArgumentException("Upload filename is null or empty"); } // use an abundance of caution; the caller has a valid API key but we haven't validated the credential yet // this is a really unlikely attack vector and it wouldn't do anything, but we're taking a hard stance on input validation if (FileSafety.ContainsTraversalSegments(filename)) { Log.Warning("Suspicious attempt to upload a file containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); return BadRequest(); } if (stream == null || !stream.CanRead) { throw new ArgumentException("Unable to obtain stream from request"); } } catch (Exception ex) { Log.Warning("Failed to handle file upload for token {Token} from a caller claiming to be agent {Agent}: {Message}", token, agentName, ex.Message); Log.Debug(ex, "Failed to handle file upload"); return BadRequest(); } Log.Information("Handling file upload of {Filename} ({Token}) from a caller claiming to be agent {Agent}", filename, token, agentName); // agents must encrypt the Id they were given in the request with the secret they share with the controller, and // provide the encrypted value as the credential with the request. the validation below verifies a bunch of // things, including that the encrypted value matches the expected value. the goal here is to ensure that the // caller is the same caller that received the request, and that the caller knows the shared secret. if (!Relay.TryValidateFileStreamResponseCredential(token: guid, agentName: agentName, filename: filename, credential: credential)) { Log.Warning("Failed to authenticate file upload token {Token} from a caller claiming to be agent {Agent}", guid, agentName); return Unauthorized(); } Log.Information("Agent {Agent} authenticated for token {Token}. Forwarding file stream for {Filename}", agentName, guid, filename); // pass the stream back to the relay service, which will in turn pass it to the upload service, and use it to // feed data into the remote upload. await this call, it will complete when the upload is complete, one way or the other. await Relay.HandleFileStreamResponseAsync(agentName, id: guid, stream); Log.Information("File upload of {Filename} ({Token}) from agent {Agent} complete", filename, token, agentName); return Ok(); } finally { stream?.TryDispose(); } } /// /// Uploads share information to the connected controller. /// /// The unique identifier for the request. /// [HttpPost("controller/shares/{token}")] [RequestSizeLimit(ONE_TEBIBYTE)] [RequestFormLimits(MultipartBodyLengthLimit = ONE_TEBIBYTE)] [Authorize(Policy = AuthPolicy.ApiKeyOnly, Roles = AuthRole.ReadWriteOrAdministrator)] public async Task UploadShares(string token) { if (!OptionsAtStartup.Relay.Enabled || !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OperationMode)) { return Forbid(); } if (!Guid.TryParse(token, out var guid)) { return BadRequest("Token is not a valid Guid"); } if (!Request.HasFormContentType || !MediaTypeHeaderValue.TryParse(Request.ContentType, out var mediaTypeHeader) || string.IsNullOrEmpty(mediaTypeHeader.Boundary.Value)) { return new UnsupportedMediaTypeResult(); } var agentName = Request.Headers["X-Relay-Agent"].FirstOrDefault(); var credential = Request.Headers["X-Relay-Credential"].FirstOrDefault(); if (!Relay.RegisteredAgents.Any(a => a.Name == agentName) || string.IsNullOrEmpty(credential)) { return Unauthorized(); } IEnumerable shares; IFormFile database; try { shares = Request.Form["shares"].ToString().FromJson>(); database = Request.Form.Files[0]; } catch (Exception ex) { Log.Warning("Failed to handle share upload from agent {Agent}: {Message}", agentName, ex.Message); return BadRequest(); } Log.Information("Handling share upload ({Token}) from a caller claiming to be agent {Agent}", token, agentName); if (!Relay.TryValidateShareUploadCredential(token: guid, agentName, credential)) { Log.Warning("Failed to authenticate share upload from caller claiming to be agent {Agent} using token {Token}", agentName, guid); return Unauthorized(); } Directory.CreateDirectory(FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName)); var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_{FileSafety.SanitizeFilename(agentName)}_{Path.GetRandomFileName()}.db"); try { Log.Information("Agent {Agent} authenticated for token {Token}. Beginning download of shares to {Filename}", agentName, guid, temp); var sw = new Stopwatch(); sw.Start(); using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); using var inputStream = database.OpenReadStream(); await inputStream.CopyToAsync(outputStream); sw.Stop(); Log.Information("Download of shares from {Agent} ({Token}) complete ({Size} in {Duration}ms)", agentName, guid, ((double)inputStream.Length).SizeSuffix(), sw.ElapsedMilliseconds); await Relay.HandleShareUploadAsync(agentName, id: guid, shares, temp); return Ok(); } catch (ShareValidationException ex) { return BadRequest(ex.Message); } finally { try { System.IO.File.Delete(temp); System.IO.File.Delete(temp + "-wal"); System.IO.File.Delete(temp + "-shm"); } catch (Exception ex) { Log.Debug(ex, "Failed to remove temporary share upload file: {Message}", ex.Message); } } } } }