Last active
November 29, 2017 01:40
-
-
Save marshall-lee/a660528f8d53436d9f47303647fdbc90 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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