Nginx

Nginx restrict access by ip 사용자 ip로 제한하기

babbeolicoding 2023. 6. 26. 21:55

우선 기본적으로  nginx에서 ip기준으로

서비스를 차단, 허용하는  방법은 allow, deny를 사용하는 것이다.

allow ip
deny all;
-> 이런  경우특정 ip 만 허용되고 나머지 경우는 전부 차단된다.

 

하지만 lb를 통해 유입되는 경우 client ip가 아닌

lb ip로 변환된 상태로 서비스유입이 된다.
해당경우는  client ip로 제어를 하기 힘들다.
이런 경우 X-Forwarded-For 기능을 사용해

client ip를 보존해 해당 ip를 통해 allow, deny가 가능하다.

 

Client IP를 사용하는 방법

 

우선 nginx log 포맷은 아래와 같은 상태로 진행해봤다.

log_format  main    '$http_x_forwarded_for - $remote_addr - $remote_user [$time_local] '
                        '"$request" $status $body_bytes_sent "$http_referer" '
                        '"$http_user_agent"' ;

log_format  vhosts    '$http_x_forwarded_for - $remote_addr - $remote_user [$time_local] '
                            '"$request" $status $body_bytes_sent "$http_referer" '
                            '"$http_user_agent"'
                           '$request_time $upstream_response_time $pipe';

 

1. real_ip로 변환 후 세팅

real_ip_header X-Forwarded-For;  #real client ip를 찾을 헤더 명시
set_real_ip_from 0.0.0.0/0;      #체크할 client ip 대역대 
real_ip_recursive on;            #set_real_ip_from으로 선언된 신뢰할 수 있는 프록시 서버 목록만 client로 보는 기능

allow {allow_ip1};
allow {allow_ip2};
allow {allow_ip3};
deny all;

해당 방법을 사용하면 real ip로 덮어써진 상태로 서비스가 유입이 된다.
하지만 로그를 확인하면 lb ip는 지워지고 client ip만 남게 된다.

원래 아래 형태로 log가 남아야 하는데
-{clientip}-{lbip} - -"....." 200 0 "-" "-"

client ip로 덮어써져 둘다 clientip로 로그가 남는다
-{clientip}-{clientip} - - "....." 200 0 "-" "-"

 

2. $http_x_forwarded_for 사용

 모든 log를 남기기 위해 생각한 방법은
 $http_x_forwarded_for 변수를 사용하는 방법이다.
 
 if ( $http_x_forwarded_for !~ 'allow_ip1|allowip2' )
 {
       return 403;
 }
 => 해당 ip가 아닌 경우 403을 return 하는 기능
 
 이렇게 사용하면 ip를 통해 filter도 가능하고 client ip, lb ip 모두 보존이 가능하다.
 차단한 로그도 모두 남기 때문에 모든 로그 추적이 가능하다.
 
 성공하는 경우
 -{clientip}- {lbip} - - "....." 200 0 "-" "-"
 실패하는 경우
 -{clientip}- {lbip} - - "....." 403 0 "-" "-"
 
 성공, 실패를 상관없이 nginx에 서비스 접속을 시도한 모든 로그를 확인할 수 있다.