5

I have been trying to get rid of the "Server" header returning "Microsoft-HTTPAPI/2.0" on my self hosted webapi2 application hosted as a stateless service on azure service fabric. Things that I have tried but did not work:

I tried to implement an IFilter to remove the header from the webapi service but debugging the app showed that the header was not there to remove at that point.

Also tried to substitute the value which resulted in getting the new value appended to the "Microsoft-HTTPAPI/2.0" value.

I tried to setup webserver flags within out app.config file (kind of like using it as web.config), but no luck.

I tried to override the OnSerdingHeaders event of the OWIN pipeline but the "Server" header was not there to remove, it clearly gets added at an even later stage.

I tried every suggestion I could find online regarding clearing the server in code by using the application builder.

I tried implementing a custom delegating handler to clear/override the header but no luck there also.

I even tried tampering the registry on my debugging machine just to check but that also did not succeed.

My Pen-testers insist on getting rid of it. Is there another way?

Thanks in advance!

Achilles P.
  • 195
  • 1
  • 1
  • 6

1 Answers1

3

Following middleware solved the problem:

public class RemoveServerHeaderMiddleware
{
    private readonly RequestDelegate next;

    public RemoveServerHeaderMiddleware(RequestDelegate next)
    {
        this.next = Argument.NotNull(next, nameof(next));
    }

    public async Task Invoke(HttpContext context)
    {
        context.Response.OnStarting(() =>
        {
            context.Response.Headers.Add("Server", string.Empty);

            return Task.CompletedTask;
        });

        await this.next(context).ConfigureAwait(false);
    }
}

Of course, don't forget to register the middleware:

app.UseMiddleware<RemoveServerHeaderMiddleware>();

The solution is based on these links:

https://github.com/aspnet/HttpSysServer/issues/445

https://blogs.msdn.microsoft.com/timomta/2016/12/03/how-to-remove-the-server-header-from-weblistener/

MaMazav
  • 1,773
  • 3
  • 19
  • 33
  • I used it as `appBuilder.Use(typeof(RemoveServerHeaderMiddleware));` and placed it before the appBuilder.UseWebApi and other appBuilder.Use methods. This way it worked – Sahin Jan 31 '23 at 21:59