Files
raven/server/AyaNova/Controllers/LogFilesController.cs
John Cardinal e58ab2c100 case 4715 - download file names checked
report/download and export/download (any download key), the log-file routes and
backup download built a path from the file name in the URL with Path.Combine
and no check, so on Windows a name with a folder part or an absolute path could
reach files outside the folder (security review F21). New helper
FileUtil.FullPathInFolderOrNull accepts only a bare file name that resolves
directly inside the folder; TemporaryFileExists and BackupFileExists use it
(the download routes already call them first), and so do both log routes.
A refused name gets the same 404 as a missing file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 12:20:25 -07:00

166 lines
5.8 KiB
C#

using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using AyaNova.Models;
using AyaNova.Util;
using AyaNova.Api.ControllerHelpers;
using AyaNova.Biz;
using System.Threading.Tasks;
using System;
using System.IO;
namespace AyaNova.Api.Controllers
{
/// <summary>
/// Log files controller
/// </summary>
[ApiController]
[Asp.Versioning.ApiVersion("8.0")]
[Route("api/v{version:apiVersion}/log-file")]
//[Produces("application/json")]
[Authorize]
public class LogFilesController : ControllerBase
{
private readonly AyContext ct;
private readonly ILogger<LogFilesController> log;
private readonly ApiServerState serverState;
/// <summary>
/// ctor
/// </summary>
/// <param name="dbcontext"></param>
/// <param name="logger"></param>
/// <param name="apiServerState"></param>
public LogFilesController(AyContext dbcontext, ILogger<LogFilesController> logger, ApiServerState apiServerState)
{
ct = dbcontext;
log = logger;
serverState = apiServerState;
}
/// <summary>
/// Get server log
/// </summary>
/// <param name="logname"></param>
/// <returns>A single log file in plain text</returns>
[HttpGet("{logname}")]
public ActionResult GetLog([FromRoute] string logname)
{
//NOTE: this route deliberately open even when server closed as a troubleshooting measure
if (!Authorized.HasReadFullRole(HttpContext.Items, AyaType.LogFile))
{
return StatusCode(403, new ApiNotAuthorizedResponse());
}
if (!ModelState.IsValid)
{
return BadRequest(new ApiErrorResponse(ModelState));
}
//stream the file contents into a json object and return
//build the full path from the log file name and defined path
//case 4715: only a bare file name inside the log folder
var logFilePath = FileUtil.FullPathInFolderOrNull(ServerBootConfig.AYANOVA_LOG_PATH, logname);
//does file exist?
if (logFilePath == null || !System.IO.File.Exists(logFilePath))
{
return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
}
//Log
//nlog update now locks file for writing so needs to be opened this way
FileStreamOptions fso = new FileStreamOptions();
fso.Access = FileAccess.Read;
fso.Mode = FileMode.Open;
fso.Share = FileShare.ReadWrite;
using (StreamReader sr = new StreamReader(logFilePath, fso))
{
return Content(sr.ReadToEnd());
}
//return Content(System.IO.File.ReadAllText(logFilePath));
}
/// <summary>
/// Get list of operations logs
/// </summary>
/// <returns></returns>
[HttpGet()]
public ActionResult ListLogs()
{
//NOTE: this route deliberately open even when server closed as a troubleshooting measure
if (!Authorized.HasReadFullRole(HttpContext.Items, AyaType.LogFile))
{
return StatusCode(403, new ApiNotAuthorizedResponse());
}
if (!ModelState.IsValid)
{
return BadRequest(new ApiErrorResponse(ModelState));
}
//Iterate all log files and build return
var files = System.IO.Directory.GetFiles(ServerBootConfig.AYANOVA_LOG_PATH, "log-ayanova*.txt");
//newest archive first by file date, archive numbers only increase since NLog 6 so name order breaks past 9
var ret = files.Where(z => !z.EndsWith("ayanova.txt")).OrderByDescending(z => System.IO.File.GetLastWriteTimeUtc(z)).Select(z => System.IO.Path.GetFileName(z)).ToList();
ret.Insert(0, "log-ayanova.txt");
return Ok(ApiOkResponse.Response(ret));
}
/// <summary>
/// Download log
/// </summary>
/// <param name="logname"></param>
/// <param name="t">download token</param>
/// <returns>A single log file</returns>
[AllowAnonymous]
[HttpGet("download/{logname}")]
public async Task<IActionResult> DownloadLog([FromRoute] string logname, [FromQuery] string t)
{
//NOTE: this route deliberately open even when server closed as a troubleshooting measure
if (!ModelState.IsValid)
return BadRequest(new ApiErrorResponse(ModelState));
var user = await UserBiz.ValidateDownloadTokenAndReturnUserAsync(t, ct);
if (user == null)
{
await Task.Delay(AyaNova.Util.ServerBootConfig.FAILED_AUTH_DELAY);//DOS protection
return StatusCode(401, new ApiErrorResponse(ApiErrorCode.AUTHENTICATION_FAILED));
}
if (!Authorized.HasReadFullRole(user.Roles, AyaType.LogFile))
return StatusCode(403, new ApiNotAuthorizedResponse());
//case 4715: only a bare file name inside the log folder
var logFilePath = FileUtil.FullPathInFolderOrNull(ServerBootConfig.AYANOVA_LOG_PATH, logname);
if (logFilePath == null || !System.IO.File.Exists(logFilePath))
return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
//Note: this works with new Nlog file locking for write so it must be opening it as read and shareable
return PhysicalFile(logFilePath, "text/plain", $"{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}-{logname}");
}
//------------
}
}