using System;
|
using System.Collections.Generic;
|
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Http;
|
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Logging;
|
using System.Threading.Tasks;
|
|
namespace APIGetway.Filter
|
{
|
public class FolderFilter
|
{
|
// 配置节:Gateway:FolderFilter:Enabled(默认 true)、Gateway:FolderFilter:BlockedFolders(数组,覆盖默认值)。
|
private const string Section = "Gateway:FolderFilter";
|
private const string ExtensionsKey = "BlockedFolders";
|
|
// 默认拦截的文件夹名(忽略大小写),不允许访问 bin、obj、vlog、dll 等编译输出目录,也不允许访问上级目录。
|
private static readonly Dictionary<string, int> DefaultFolders = new Dictionary<string, int>
|
{
|
["bin"] = 1,
|
["obj"] = 1,
|
["vlog"] = 1,
|
["dll"] = 1,
|
};
|
|
|
private readonly RequestDelegate _next;
|
|
private readonly ILogger<FileExtensionFilter> _logger;
|
|
private readonly bool _enabled;
|
|
private readonly Dictionary<string, int> _folders;
|
|
public FolderFilter(RequestDelegate next, ILogger<FileExtensionFilter> logger, IConfiguration configuration)
|
{
|
_next = next;
|
_logger = logger;
|
_enabled = configuration.GetValue<bool>($"{Section}:Enabled");
|
_folders = ResolveFolders(configuration);
|
}
|
|
public Task InvokeAsync(HttpContext context)
|
{
|
if (_enabled)
|
{
|
var folder = MatchFolders(context.Request.Path);
|
if (folder != null)
|
{
|
_logger.LogWarning("已拦截 {Folder} 文件夹访问: {Method} {Path},来源 {RemoteIp}",
|
folder,
|
context.Request.Method,
|
context.Request.Path.Value,
|
context.Connection.RemoteIpAddress);
|
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
return Task.CompletedTask;
|
}
|
}
|
return _next(context);
|
}
|
|
private static Dictionary<string, int> ResolveFolders(IConfiguration configuration)
|
{
|
var folders = new Dictionary<string, int>();
|
foreach (var item in configuration.GetSection(Section).GetSection(ExtensionsKey).GetChildren())
|
{
|
var value = item.Key?.Trim();
|
if (string.IsNullOrEmpty(value))
|
{
|
continue;
|
}
|
|
folders[value] = 1;
|
}
|
|
return folders.Count > 0 ? folders : DefaultFolders;
|
}
|
|
|
public string? MatchFolders(PathString path)
|
{
|
if(!path.HasValue)
|
{
|
return null;
|
}
|
|
//var segments = path.Value.Split('/', StringSplitOptions.RemoveEmptyEntries);
|
|
//if(segments.Length == 0)
|
//{
|
// return null;
|
//}
|
//foreach (var segment in segments)
|
//{
|
|
// if(_folders.TryGetValue(segment.ToLower(), out _))
|
// {
|
// return segment;
|
// }
|
//}
|
|
// 使用 ReadOnlySpan<char> 替代 Split 方案
|
ReadOnlySpan<char> pathSpan = path.Value.AsSpan();
|
|
while(!pathSpan.IsEmpty)
|
{
|
int slashIndex = pathSpan.IndexOf('/');
|
|
// 取当前路径片段;没有斜杠时,剩余的部分就是最后一个片段
|
ReadOnlySpan<char> segment = slashIndex >= 0 ?
|
pathSpan[..slashIndex] : pathSpan;
|
|
// 检查当前片段是否在拦截列表中(忽略大小写)
|
if (!segment.IsEmpty)
|
{
|
// 直接通过字段key判断 当前路径是否在字典中,如果在字典中,则认为是敏感文件夹,返回该文件夹名称。无需判断字典Key的值,因为字典的值只是占位符。
|
// 默认字典key 取小写路径。分割的片段全部需要按照小写处理
|
if(_folders.ContainsKey(segment.ToString().ToLowerInvariant()))
|
{
|
return segment.ToString();
|
}
|
}
|
|
if (slashIndex < 0)
|
{
|
break; // 没有更多的斜杠,结束循环
|
}
|
|
pathSpan = pathSpan[(slashIndex + 1)..]; // 移动到下一个片段
|
}
|
|
return null;
|
}
|
}
|
|
|
|
|
public static class FolderFilterExtensions
|
{
|
/// <summary>
|
/// 注册文件路径拦截。必须放在 UseStaticFiles / MapReverseProxy 之前。
|
/// </summary>
|
public static IApplicationBuilder UseFolderFilter(this IApplicationBuilder builder)
|
{
|
return builder.UseMiddleware<FolderFilter>();
|
}
|
}
|
}
|