set setting reset

脂肪と糖にはたらくやつ

powershell で X-ASPNET-VERSION ヘッダを削除する

サーバ全体で無効化する方法がないか調べてみたところ msdn ブログがヒットしました。

MSDN Blogs

方法は 2 種類あって、web.config に追加する方法と、サーバレベルでサーバ変数を利用した rewrite を行う方法があるようです。
ただし、後者は ヘッダそのものではなく、ヘッダの値を隠蔽 するというものになっています。

web.config での方法

以下の 3 行をトップレベルの web.config に追記します。

  <system.web>
      <httpRuntime enableVersionHeader="false" />
  </system.web>

または下記コマンドを実行します。

c:\windows\system32\inetsrv\appcmd.exe set config -section:system.web/httpRuntime -enableVersionHeader:false /commit:webroot /clr:4

.NET2 の場合は /clr:2 とします。
すると ROOT である C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\Web.config に上記内容が追加されます。

IISフォーラム先生ありがとうございます。
System.Web in Applicationhost.config not working anymore (IIS8.5) : The Official Microsoft IIS Forums

applicationHost.config での方法

IIS 8 からは applicationHost.config での system.web セクションは廃止されたとのこと。

rewrite での方法

Please note that it will not remove the header all together but it will remove the value of it.

f:id:rriifftt:20151027162807p:plain

あまり意味はなさそうですが、とりあえずやってみようということで、サイト内の手順に沿って IIS マネージャから設定したところ、 applicationHost.config に設定が追加されてしまいました。

    <system.webServer>
        <rewrite>
            <allowedServerVariables>
                <add name="RESPONSE_X-ASPNET-VERSION" />
            </allowedServerVariables>
            <outboundRules>
                <rule name="RESPONSE_X-ASPNET-VERSION">
                    <match serverVariable="RESPONSE_X-ASPNET-VERSION" pattern=".+" />
                    <action type="Rewrite" />
                </rule>
            </outboundRules>
        </rewrite>
    </system.webServer>

powershell でできないか調べてみたところ、いくつかのコマンドレットを使うとよさそうです。

Get-WebConfigurationProperty
Add-WebConfigurationProperty
Set-WebConfiguration

スクリプトは以下のようになりました。
if 文があるのは無駄に chef で実行されることを想定したのでちょっとだけ冪等性を考えたためです。

# add allowedServerVariables
$asv = Get-WebConfigurationProperty `
       -filter "//rewrite/allowedServerVariables/add"`
       -name name

if ($asv -eq $null)
{
  Add-WebConfigurationProperty `
    -Filter "//rewrite/allowedServerVariables" `
    -PSPath "IIS:\" `
    -Name "Collection" `
    -Value @{name="RESPONSE_X-ASPNET-VERSION"}
}

# add rule
$rule = Get-WebConfigurationProperty `
          -filter "//rewrite/outboundRules/rule[@name='REMOVE_X-ASPNET-VERSION']/match"`
          -name serverVariable

if ($rule -eq $null)
{
  Add-WebConfigurationProperty `
    -Filter "//rewrite/outboundRules" `
    -PSPath "IIS:\" `
    -Name "Collection" `
    -Value @{name="REMOVE_X-ASPNET-VERSION"}

  Set-WebConfiguration `
    -Filter "//rewrite/outboundRules/rule[@name='REMOVE_X-ASPNET-VERSION']/match" `
    -PSPath "IIS:\" `
    -Value @{serverVariable="RESPONSE_X-ASPNET-VERSION";pattern=".+"}
  
  Set-WebConfiguration `
    -Filter "//rewrite/outboundRules/rule[@name='REMOVE_X-ASPNET-VERSION']/action" `
    -PSPath "IIS:\" `
    -Value @{type="Rewrite"}
}

ていうか、カスタムエラーページのハンドリングをちゃんとしないと。。。