Piotr Gabryanczyk’s Blog

Java, Refactoring, AOP, Spring, DDD, TDD, etc.

  • Blogroll

    • I have joined Anti-IF Campaign

PortSpy in Ruby

Posted by Piotr Gabryanczyk on October 22, 2008

To trace all the traffic between your browser and google run:
ruby portspy.rb 80 http://www.google.com 80
And then point your browser to
http://localhost:80

Enjoy!

require "socket"
STDOUT.sync = true
STDERR.sync = true

SERVER_PORT, REDIRECT_HOST, REDIRECT_PORT, *rest = ARGV


puts "Forwarding from port #{SERVER_PORT} to #{REDIRECT_HOST}:#{REDIRECT_PORT}"

server = TCPServer.new(SERVER_PORT)

counter = 0
while( session = server.accept)
    counter += 1
    redirect = TCPSocket.new REDIRECT_HOST, REDIRECT_PORT
    puts "#{counter}>OPENING CONNECTION"
    Thread.new(session, redirect, counter) do |s, r, c|
        begin
            req = File.new("data/request-#{c}.txt", "w")
            req.sync = true
            until( s.eof? )
                line = s.readpartial(128)
                puts "\n#{c}>REQUEST:'#{Regexp.escape(line)}'"
                r.write line
                req.write line
                r.flush
            end
            s.close_read
            req.close
            r.close_write
            puts "\n#{c}>CLOSING REQUEST SOCKET:"
        rescue => e
            puts "\n#{c}Error #{e}\n#{e.backtrace}"
            exit -1
        end
    end

    Thread.new(session, redirect, counter) do |s, r, c|
        begin
            resp = File.new("data/response-#{c}.txt", "w")
            resp.sync = true
            until( r.eof? )
                line = r.readpartial(128)
                puts "\n#{c}>RESPONSE:'#{Regexp.escape(line)}'"
                resp.write line
                s.write line
                s.flush
            end
            puts "\n#{c}CLOSING RESPONSE"
            r.close_read       
            resp.close
            s.close_write
        rescue =>  e
            puts "\n#{c}Error #{e}\n#{e.backtrace.join "\n\t"}"
            exit -1
        end

    end
end
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: