Home > OS >  How to return ECONNREFUSED in ASP.NET Middleware to hide my API?
How to return ECONNREFUSED in ASP.NET Middleware to hide my API?

Time:11-29

I basically have a little web server receiving webhooks from a few things. It has been running in test and I log everything. I noticed I get more random requests from Search Engines, IP crawlers and all sorts than my own requests.

I have created a simple middle ware

app.Use(async (context, next) =>
{
    await next();

    // Do not respond to random fkn bot and search engine garbage.. just be silent!
    if (context.Response.StatusCode != 200)
    {
        context.Abort();
    }
});

[In postman]

When server is running I hit a 404 the middleware produces a socket hang up

When server is NOT running it produces ECONNREFUSED <-- This is what I want to return if the endpoint does not exist.

I want it to be silent pretend like nothing is there.

Because the abort send back the socket hung up that is a clear indication there is something there. Can I force a connection refused (even after a wee bit of processing time)

CodePudding user response:

Not in the general case.

"Connection refused" means the socket connection was refused. By the time your method is invoked, the socket connection has already been accepted. The socket connection must be accepted before any request headers or body are read. So it's not possible to accept a socket, read the request, and then go back in time and not accept the socket.

There is a technique called "port knocking". You can look into that if you want, but it does require changes to your legitimate clients, so it won't work if they're just simple webhooks.

  • Related