Rails에 대해 현재 공부중입니다. 다음은 완벽하게 동작하는 화이트리스트 기반 IP 필터링 예시입니다. 단순 IP필터링부터 Subnet마스크를 이용한 범위 설정까지 설정이 가능합니다. 컨트롤러에 before_filter로 설정하여 사용하는 예시입니다.

before_filter :protect

def protect
@ips = ['127.0.0.1', '192.168.1.0/24'] # 다수의 IP설정 가능
allowed = false
# Remote IP를 Integer형으로 변경합니다.
bremote_ip = request.remote_ip.split('.').map(&:to_i).pack('C*').unpack('N').first
@ips.each do |ipstring|
ip, mask = ipstring.split '/'
# 비교할 IP도 Integer로 변경합니다.
bip = ip.split('.').map(&:to_i).pack('C*').unpack('N').first
# 넷마스크값을 정의합니다. 설정되어있지 않을경우 /32로 간주합니다.
mask = mask ? mask.to_i : 32
bmask = ((1 << mask) - 1) << (32 - mask)
if bip & bmask == bremote_ip & bmask
allowed = true
break
end
end

if not allowed
render :text => "You are unauthorized"
return
end
end


참고: http://stackoverflow.com/questions/11636228/whitelisting-list-of-ips-with-some-subnets-in-rails-3-application
크리에이티브 커먼즈 라이센스
Creative Commons License

트랙백을 보내세요

트랙백 주소 :: http://theeye.pe.kr/trackback/535