C# (ASP.NET Core)
Para entornos empresariales de Microsoft, integrar ProxyTracer directamente en la canalización de solicitudes HTTP de ASP.NET Core garantiza que el tráfico malicioso sea rechazado antes de que active el enrutamiento, el enlace de modelos o consultas a bases de datos.
El Middleware
Esta implementación utiliza System.Text.Json para una deserialización ultra rápida, impone un estricto límite de tiempo de espera a través de HttpClient e interrumpe la canalización con una respuesta 403 Forbidden si detecta riesgo.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace ProxyTracer.Security
{
public class ProxyTracerMiddleware
{
private readonly RequestDelegate _next;
private readonly HttpClient _httpClient;
private readonly ILogger<ProxyTracerMiddleware> _logger;
private readonly string _apiKey;
public ProxyTracerMiddleware(RequestDelegate next, IConfiguration config, ILogger<ProxyTracerMiddleware> logger)
{
_next = next;
_logger = logger;
_apiKey = config["PROXYTRACER_API_KEY"] ?? throw new ArgumentNullException("PROXYTRACER_API_KEY is missing");
// Reusable client with strict 500ms timeout
_httpClient = new HttpClient { Timeout = TimeSpan.FromMilliseconds(500) };
}
public async Task InvokeAsync(HttpContext context)
{
// 1. Extract the IP (Requires app.UseForwardedHeaders() configured in Program.cs)
var ip = context.Connection.RemoteIpAddress?.ToString();
// Skip local development IPs
if (!string.IsNullOrEmpty(ip) && ip != "127.0.0.1" && ip != "::1")
{
try
{
// 2. Query ProxyTracer API asynchronously
using var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.proxytracer.com/v1/check/{ip}");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
using var response = await _httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
using var jsonStream = await response.Content.ReadAsStreamAsync();
var ptResponse = await JsonSerializer.DeserializeAsync<ProxyTracerResult>(jsonStream);
// 3. Drop the connection if a proxy/VPN is detected
if (ptResponse != null && ptResponse.Proxy)
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync("{\"error\": \"Access Denied: VPN or Proxy detected.\"}");
return; // Short-circuit the request pipeline
}
}
}
catch (Exception ex)
{
// Fail open: Log the error and allow the request through
_logger.LogWarning($"ProxyTracer validation failed: {ex.Message}");
}
}
// 4. Traffic is clean, proceed to controllers
await _next(context);
}
// Lightweight struct mapping exactly to the {"proxy": true|false} response
private class ProxyTracerResult
{
[JsonPropertyName("proxy")]
public bool Proxy { get; set; }
}
}
}Configuración
Para activar la protección, registra el middleware en tu archivo Program.cs. Asegúrate de colocarlo después de UseForwardedHeaders pero antes de UseRouting y UseAuthentication.
var app = builder.Build();
// 1. Ensure real IPs are extracted if behind an NGINX/Cloudflare load balancer
app.UseForwardedHeaders();
// 2. Drop malicious traffic early
app.UseMiddleware<ProxyTracer.Security.ProxyTracerMiddleware>();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();Last updated on