soenneker/soenneker.utils.httpclientcache.ssrf
GitHub: soenneker/soenneker.utils.httpclientcache.ssrf
该库为 .NET 应用提供内置 SSRF 防护与 DNS 重绑定防御的 HttpClient 缓存,确保服务端发起的外部 HTTP 请求不会触及内部网络。
Stars: 0 | Forks: 0
[](https://www.nuget.org/packages/soenneker.utils.httpclientcache.ssrf/)
[](https://github.com/soenneker/soenneker.utils.httpclientcache.ssrf/actions/workflows/publish-package.yml)
[](https://www.nuget.org/packages/soenneker.utils.httpclientcache.ssrf/)
#  Soenneker.Utils.HttpClientCache.Ssrf
### 防范 SSRF 且抵御 DNS 重绑定的 HttpClient 缓存。
## 安装说明
```
dotnet add package Soenneker.Utils.HttpClientCache.Ssrf
```
## 注册
```
using Soenneker.Utils.HttpClientCache.Ssrf.Registrars;
services.AddSsrfHttpClientCacheAsSingleton();
```
同时也提供 `AddSsrfHttpClientCacheAsScoped()` 方法。如果底层的
`Soenneker.Utils.HttpClientCache` 服务尚未注册,这两个方法均会使用相匹配的生命周期对其进行注册。
## 用法
```
using Soenneker.Utils.HttpClientCache.Ssrf.Abstract;
public sealed class RemoteDocumentClient
{
private readonly ISsrfHttpClientCache _clientCache;
public RemoteDocumentClient(ISsrfHttpClientCache clientCache)
{
_clientCache = clientCache;
}
public async ValueTask Download(Uri uri, CancellationToken cancellationToken)
{
HttpClient client = await _clientCache.Get("remote-documents", cancellationToken);
return await client.GetStringAsync(uri, cancellationToken);
}
}
```
该缓存实现了与 `IHttpClientCache` 相同的 API,包括同步和异步的
option 工厂、缓存移除以及销毁。
## 安全行为
- 在打开连接时会解析 DNS。
- 每个解析出的地址必须是公网可路由的。
- socket 直接连接到经过验证的地址集,防止第二次 DNS 查询更改目标地址。
- 重定向目标也会经过相同的连接验证。
- 对于 IPv4 和 IPv6,会阻止 Loopback、private、link-local、carrier-grade NAT、documentation、benchmark、multicast 和保留的地址范围。
- 代理、自定义的 `HttpClientHandler` 实例以及自定义的 `SslOptions` 会被拒绝,因为它们会扩大或绕过缓存的受控传输配置。
调用者既不拥有返回的 `HttpClient` 也不拥有其 handler。当不再需要缓存的 client 时,请使用 `Remove`/`RemoveSync`,或者通过其依赖注入的 scope 来销毁缓存。
标签:HttpClient, SSRF防护, 多人体追踪, 缓存, 网络请求