Skip to content

Instantly share code, notes, and snippets.

@marshall-lee
Last active November 29, 2017 01:40
Show Gist options
  • Save marshall-lee/a660528f8d53436d9f47303647fdbc90 to your computer and use it in GitHub Desktop.
Save marshall-lee/a660528f8d53436d9f47303647fdbc90 to your computer and use it in GitHub Desktop.
# Prevent HTTP requests to be made into private network (in Ruby!)
# Just an example, don't use it in production!
require 'http'
require 'resolv'
class StaticResolveTCPSocket
def initialize(lookup)
@lookup = lookup.dup
@lookup.default_proc = proc do |_h, host|
raise "Unresolvable host #{host}!"
end
end
def open(host, port)
TCPSocket.open(@lookup[host], port)
end
end
IPV4_PRIVATE_BLOCKS = %w[
10.0.0.0/8
172.16.0.0/12
192.168.0.0/16
].map(&IPAddr.method(:new)).freeze
def validate_addr!(addr)
addr = IPAddr.new(addr) if addr.is_a? String
raise "#{addr} belongs to a private network!" if IPV4_PRIVATE_BLOCKS.any? { |b| b.include? addr }
end
def safe_post(uri, body)
uri = URI.parse(uri) if uri.is_a? String
host = uri.host
addr = Resolv.getaddress(host)
validate_addr!(addr)
socket_class = StaticResolveTCPSocket.new(host => addr)
HTTP.post(uri, socket_class: socket_class, body: body)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment