Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Server from HTTP Response in WCF

Tags:

c#

wcf

iis-7.5

I have an internet exposed WCF service running on IIS 7.5 that I need to secure. I would like to remove the "Server" header in the HTTP response.

I've implemented an IDispatchMessageInspector with code as follows.

public void BeforeSendReply(ref Message reply, object correlationState)
{
    var context = WebOperationContext.Current;
    if (context != null)
    {
        context.OutgoingResponse.Headers.Remove(
            HttpResponseHeader.Server);
    }
}

However, the Server header is still in the response. On debugging I can see that the OutgoingResponse.Headers does not include HttpResonseHead.Server, and if I write my own value it is clearly being overriten by something further down the line in the IIS pipeline.

Edit 1

Tried the following, no good either

public class SecureServerHeaderModule : IHttpModule
{
    #region Implementation of IHttpModule

    public void Init(HttpApplication context)
    {
        context.PreSendRequestHeaders += OnPreSendRequestHeaders;
    }

    public void Dispose() { }

    #endregion

    private static void OnPreSendRequestHeaders(object sender, EventArgs e)
    {
        var context = HttpContext.Current;
        if (context != null)
        {
            context.Response.Headers.Remove("Server");                
        }
    }
}

<system.web>
  <httpModules>
    <add "snip" />
  </httpModlules>
</system.web>
<system.webServer>
  <modules>
    <add "snip" />
  </modlules>
</system.webServer>

Edit 2

Also did not work.

public void BeforeSendReply(ref Message reply, object correlationState)
{
    var context = OperationContext.Current;
    if (context != null)
    {
        context.OutgoingMessageProperties.Remove(
            HttpResponseHeader.Server.ToString());
        context.OutgoingMessageProperties.Add(
            HttpResponseHeader.CacheControl.ToString(), "no-store");
    }
}
like image 251
M Afifi Avatar asked Feb 20 '23 21:02

M Afifi


1 Answers

This works using an IDispatchMessageInspector

public class SecureBehaviour : IDispatchMessageInspector
{
    public object AfterReceiveRequest(ref Message request,
        IClientChannel channel, InstanceContext instanceContext)
    {
        return null;
    }

    public void BeforeSendReply(ref Message reply, object correlationState)
    {

        var httpCtx = HttpContext.Current;
        if (httpCtx != null)
        {
            httpCtx.Response.Headers.Remove(
                HttpResponseHeader.Server.ToString());
        }
    }
}
like image 195
M Afifi Avatar answered Feb 22 '23 09:02

M Afifi