ruby-on-rails-3 - Rails 3 应用程序中具有某些子网的 IP 白名单

标签 ruby-on-rails-3 controller ip before-filter

除了少数 IP 地址和几个 IP 子网外,我一直在尝试找出阻止访问我们的 Rails 3 应用程序的正确方法。

在寻找方法时,我发现了这个 question/answer .建议代码如下:

应用程序 Controller

before_filter :protect

def protect
  @ips = ['127.0.0.1', '203.123.10.1'] #And so on ...]
  if not @ips.include? request.remote_ip
     # Check for your subnet stuff here, for example
     # if not request.remote_ip.include?('127.0,0')
     render :text => "You are unauthorized"
     return
  end
end

这行得通,所以我将其更改为重定向到静态页面,而不仅仅是文本消息。

不过,我想做的是允许从与 Rails 应用程序服务器位于同一子网上的本地 IP 进行访问。子网就是 192.168.1.0/24

将子网添加到接受的 IP 的最简单/最干净的方法是什么?

最佳答案

要测试给定的 IP 地址 foo 是否在地址 net 和掩码 mask 指定的网络内,您可以将掩码应用于网络地址和测试地址,并查看结果是否相等: foo & mask == net & mask 。您必须先将 IP 地址和掩码转换为整数。 /24 的掩码是将 24 位设置为 1,然后将 8 位设置为 0 - 0xFFFFFF00255.255.255.0 点分四组符号。

before_filter :protect

def protect
  @ips = ['127.0.0.1', '192.168.1.0/24'] #And so on ...]
  allowed = false
  # Convert remote IP to an integer.
  bremote_ip = request.remote_ip.split('.').map(&:to_i).pack('C*').unpack('N').first
  @ips.each do |ipstring|
    ip, mask = ipstring.split '/'
    # Convert tested IP to an integer.
    bip = ip.split('.').map(&:to_i).pack('C*').unpack('N').first
    # Convert mask to an integer, and assume /32 if not specified.
    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

关于ruby-on-rails-3 - Rails 3 应用程序中具有某些子网的 IP 白名单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11636228/

相关文章:

ruby-on-rails - 带有 redirect_to 的 Rails 3 应用程序 before_filter

ruby-on-rails - 如何从 URL 中删除子域?

c - 转移套接字的 TCP 校验和计算

c - 为什么在ping程序中内核没有去掉IP层

ios - PKPaymentAuthorizationViewController 总是返回 nil?

c++ - QHostInfo问题

ruby-on-rails - 为什么Rails实例方法可以用作rspec中的类方法

ruby-on-rails - Rails - 在部署时自动填充表中的数据 - 角色

php - 如何确定 MVC 中的 Controller ?

ruby-on-rails - rails 4.1.6 在似乎未显示的 rake route 添加索引