on
코드이그나이터CI REST API IP대역대 허용/차단
코드이그나이터CI REST API IP대역대 허용/차단
개발이야기
코드이그나이터 (이하, CI) 로 REST API 개발 시, 많이 쓰이는 오픈 라이브러리에서
특정 IP를 허용/차단 하는 기능이 있는데,
특정 IP를 (예- 1.1.1.1, 1.1.1.2) 지정해서 써야되는 불편함이 있어
해당 라이브러리를 커스터 마이징 했다
REST API LIBRARY
https://github.com/chriskacerguis/codeigniter-restserver
/application/config/rest.php
$config [ 'rest_ip_whitelist_enabled' ] = TRUE ;
$config [ 'rest_ip_whitelist' ] = '192.168.0.1, 192.168.0.2, 192.168.0/24' ;
위 화이트리스트의 설정값을 보면, 192.168.0.1, 192.168.0.2는 당연히 허용이 잘되지만,
이 외 다른 아이피로 접근 시, 접근 불가라는 문구가 뜬다
특정 IP만 걸러주지, 대역대로는 적용이 불가한것..
만약 내부망에서 유동 IP를 쓰고 있고, 특정 대역대로 차단/허용하게 된다면...
수십~ 수만개의 IP를 다 적어두는 불상사를 없애기 위해
처리하는 함수를 수정해줬다
/application/libraries/REST_Controller.php
protected function _check_whitelist_auth() { $whitelist = explode ( ',' , $this - > config - > item( 'rest_ip_whitelist' )); array_push ( $whitelist , '127.0.0.1' , '0.0.0.0' ); $is_ip_chk = FALSE; foreach ( $whitelist as & $ip ) { $ip = trim( $ip ); if (strpos( $ip , "/" ) ! = = FALSE) { if ( $this - > IP_Match( $ip , $this - > input - > ip_address()) = = TRUE) { $is_ip_chk = TRUE; break ; } } } if (in_array( $this - > input - > ip_address(), $whitelist ) = = = FALSE & & $is_ip_chk = = FALSE) { $this - > response([ $this - > config - > item( 'rest_status_field_name' ) = > FALSE, $this - > config - > item( 'rest_message_field_name' ) = > $this - > lang - > line( 'text_rest_ip_unauthorized' ) ], self ::HTTP_UNAUTHORIZED); } }
>>함수 추가
protected function IP_Match( $network , $ip ){ $ip_arr = explode ( "/" , $network ); $network_long =ip2long( $ip_arr [ 0 ]); $mask_long = pow( 2 , 32 ) - pow( 2 ,( 32 - $ip_arr [ 1 ])); $ip_long =ip2long( $ip ); if (( $ip_long & $mask_long ) = = $network_long ) { return TRUE; } else { return FALSE; } }
이렇게 적용하면, IP를 쭉~~~ 작성할 필요 없이 처리 가능하다
PHP ip2long
http://php.net/manual/kr/function.ip2long.php
PHP pow
http://php.net/manual/kr/function.pow.php
from http://sobob.tistory.com/30 by ccl(S) rewrite - 2020-04-02 14:27:17