2012年9月4日火曜日

mod_securityでWebのメソッド制限

アプリケーションサーバと連携をしているApacheだとメソッドの制限がWebとAPでそれぞれ別になるっていう事がある。
それぞれで設定するのは面倒だし、アプリケーションサーバが変わるたびに調査をしないといけないので、Apacheのみでやる事を検討してみた。
どうやら、mod_securityはそういった事もできるみたい。
CentOSだとepelに入っているので、yumでインストール。
WAFは仕事で使う場合、特に稼働中のサービスだったりすると影響が怖いのでせっかくのデフォルトのルールもいったん消す。

# cd /etc/httpd/modsecurity.d
# mv base_rules base_rules.bak
# mkdir base_rules

ルールを新しく作成。
# Accept only commonly used request methods
SecRule REQUEST_METHOD "!@rx ^(?:GET|HEAD|POST)$" \ "phase:1,t:none,deny,msg:'Only standard request methods allowed',logdata:%{REQUEST_METHOD}"
これでいつでもOPTIONSでもDELETEもしらないメソッドもマッチすると落としてくれるみたい。
$ telnet localhost 80
Trying ::1...
Connected to localhost.
Escape character is '^]'.
OPTIONS / HTTP/1.1
HOST: localhost

HTTP/1.1 403 Forbidden
Date: Mon, 03 Sep 2012 18:46:14 GMT
Server: Apache
Last-Modified: Mon, 03 Sep 2012 17:10:29 GMT
ETag: "40a61-1200-4c8cf37fd9f7e"
Accept-Ranges: bytes
Content-Length: 4608
Connection: close
Content-Type: text/html; charset=UTF-8

OPTIONSもへんな結果でない。
$ telnet localhost 80
Trying ::1...
Connected to localhost.
Escape character is '^]'.
aaaaaaaaaaaaa /example/ HTTP/1.1
HOST: localhost.localdomain

HTTP/1.1 403 Forbidden
Date: Mon, 03 Sep 2012 19:13:13 GMT
Server: Apache
Last-Modified: Mon, 03 Sep 2012 17:10:29 GMT
ETag: "40a61-1200-4c8cf37fd9f7e"
Accept-Ranges: bytes
Content-Length: 4608
Connection: close
Content-Type: text/html; charset=UTF-8

よし。
$ telnet localhost 80
Trying ::1...
Connected to localhost.
Escape character is '^]'.
DELETE /example/ HTTP/1.1
HOST: localhost

HTTP/1.1 403 Forbidden
Date: Mon, 03 Sep 2012 19:14:34 GMT
Server: Apache
Last-Modified: Mon, 03 Sep 2012 17:10:29 GMT
ETag: "40a61-1200-4c8cf37fd9f7e"
Accept-Ranges: bytes
Content-Length: 4608
Connection: close
Content-Type: text/html; charset=UTF-8

満足ぢゃ!