From 475b749cf69f8a3064886e9a5ad2d45a3f5e68ac Mon Sep 17 00:00:00 2001 From: Guillaume DOTT Date: Wed, 2 Jan 2013 15:49:27 +0100 Subject: [PATCH] Add a rack middleware to forbid access to unsafe IP addresses --- lib/project-honeypot.rb | 3 ++- lib/project_honeypot/base.rb | 4 ++-- lib/project_honeypot/rack/forbidden.rb | 21 +++++++++++++++++++ .../{rack.rb => rack/header.rb} | 4 ++-- 4 files changed, 27 insertions(+), 5 deletions(-) create mode 100644 lib/project_honeypot/rack/forbidden.rb rename lib/project_honeypot/{rack.rb => rack/header.rb} (89%) diff --git a/lib/project-honeypot.rb b/lib/project-honeypot.rb index 971f376..175d943 100644 --- a/lib/project-honeypot.rb +++ b/lib/project-honeypot.rb @@ -1,7 +1,8 @@ require 'net/dns' require "project_honeypot/url" require "project_honeypot/base" -require "project_honeypot/rack" +require "project_honeypot/rack/header" +require "project_honeypot/rack/forbidden" module ProjectHoneypot class << self diff --git a/lib/project_honeypot/base.rb b/lib/project_honeypot/base.rb index e08cb03..f02d500 100644 --- a/lib/project_honeypot/base.rb +++ b/lib/project_honeypot/base.rb @@ -1,4 +1,4 @@ -module ProjectHoneypot +module ProjectHoneypot class Base def initialize(api_key) @api_key = api_key @@ -11,7 +11,7 @@ module ProjectHoneypot Url.new(ip_address, honeypot_score) end - private + private def url_to_ip(url) return url if url.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) diff --git a/lib/project_honeypot/rack/forbidden.rb b/lib/project_honeypot/rack/forbidden.rb new file mode 100644 index 0000000..a3ddf71 --- /dev/null +++ b/lib/project_honeypot/rack/forbidden.rb @@ -0,0 +1,21 @@ +module ProjectHoneypot::Rack + class Forbidden + def initialize(app, options={}) + @app = app + + raise ArgumentError, 'Must specify an API key' unless options[:api_key] + ProjectHoneypot.api_key = options[:api_key] + end + + def call(env) + request = ::Rack::Request.new(env) + url = ProjectHoneypot.lookup(request.ip) + + if url.safe? + @app.call(request.env) + else + [403, {"Content-Type" => "text/html"}, ["Forbidden"]] + end + end + end +end diff --git a/lib/project_honeypot/rack.rb b/lib/project_honeypot/rack/header.rb similarity index 89% rename from lib/project_honeypot/rack.rb rename to lib/project_honeypot/rack/header.rb index ee002c4..d7b3744 100644 --- a/lib/project_honeypot/rack.rb +++ b/lib/project_honeypot/rack/header.rb @@ -1,5 +1,5 @@ -module ProjectHoneypot - class Rack +module ProjectHoneypot::Rack + class Header def initialize(app, options={}) @app = app