CloudFlare経由のアクセスログを正しいIPアドレスに書き換えたい
問題
CloudFlareがCDNしてくれるので、サーバーの負荷が少なくて嬉しいんですが、問題もあって、アクセスログのIPアドレスがCloudFlareサーバーになってしまうんです。
本来はどこから人が来ているかが知りたくて、もっと言えば、変なアタックをしてくる輩のIPアドレスが知りたいのです。だから、Nginxのアクセスログを由緒正しい元のIPに書き換える方法を調べました。
あ、ApacheじゃなくてNginxのときのケースです。
対策
NginxのHttpRealipModuleを使います。Nginxのバージョンを見て「--with-http_realip_module"」が入っていればOK。どうやらAmimotoには標準装備になっているみたい。
$ nginx -V nginx version: nginx/1.4.7 built by gcc 4.8.2 20131212 (Red Hat 4.8.2-7) (GCC) TLS SNI support enabled configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/var/run/nginx.pid --lock-path=/var/lock/subsys/nginx --user=nginx --group=nginx --with-file-aio --with-ipv6 --with-http_ssl_module --with-http_spdy_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module --with-http_image_filter_module --with-http_geoip_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_stub_status_module --with-http_perl_module --with-mail --with-mail_ssl_module --with-pcre --with-google_perftools_module --with-debug --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic' --with-ld-opt=' -Wl,-E'
うん、うちの場合は無事入っていました。
参考:suz-lab - blog: NginxでELB対策(アクセスログにクライアントIP)
あとは、CloudFlareのIPアドレスを指定して、リアルなIPに書き換える命令を渡すだけです。
# Cloudflare set_real_ip_from 199.27.128.0/21; set_real_ip_from 173.245.48.0/20; set_real_ip_from 103.21.244.0/22; set_real_ip_from 103.22.200.0/22; set_real_ip_from 103.31.4.0/22; set_real_ip_from 141.101.64.0/18; set_real_ip_from 108.162.192.0/18; set_real_ip_from 190.93.240.0/20; set_real_ip_from 188.114.96.0/20; set_real_ip_from 197.234.240.0/22; set_real_ip_from 198.41.128.0/17; set_real_ip_from 162.158.0.0/15; set_real_ip_from 104.16.0.0/12; set_real_ip_from 2400:cb00::/32; set_real_ip_from 2606:4700::/32; set_real_ip_from 2803:f800::/32; set_real_ip_from 2405:b500::/32; set_real_ip_from 2405:8100::/32; real_ip_header CF-Connecting-IP;
あ、書きこむ場所はhttp {}の中みたいです。
実は...
公式ヘルプにも情報があったんですね。
参考:Does CloudFlare have an IP module for Nginx? – CloudFlare Support