ruby​​ SSL代理(MITM)

问题描述:

我想代理SSL数据,HTTPS在这种情况下。ruby​​ SSL代理(MITM)

这里是我的代码:

begin 
     server = TCPServer.open(on_demand_port) 
rescue Exception => e 
     sleep 5 
     retry 
end 
sslContext = OpenSSL::SSL::SSLContext.new 
sslContext.verify_mode = OpenSSL::SSL::VERIFY_NONE 
begin 
    sslContext.cert = OpenSSL::X509::Certificate.new(File.open("#{Dir.pwd}/Cert/cert.pem")) 
    sslContext.key = OpenSSL::PKey::RSA.new(File.open("#{Dir.pwd}/Cert/key.pem"), "1234") 

rescue Exception => e 
     sleep 5 
     retry 
end 
begin 
    sslServer = OpenSSL::SSL::SSLServer.new(server, sslContext) 
rescue Exception => e 
     sleep 5 
     retry 
end 

while true 

    begin 
     threads << Thread.new(sslServer.accept) do |client| # Putting new connections into the thread pool 
     tcp_proxy(client, db_name, db_user, db_password, remote_host, remote_port, patterns) 
     end 
    rescue Exception => e 
    end 



    threads = threads.select { |t| t.alive? ? true : (t.join; false) } 
     while threads.size >= on_demand_max_threads 
      sleep 1 
      threads = threads.select { |t| t.alive? ? true : (t.join; false) } 
    end 
end 

这是 “tcp_proxy” 这是真正的SSL代理

begin 
begin 
    ssl_context = OpenSSL::SSL::SSLContext.new 
    ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE 
    cert_store = OpenSSL::X509::Store.new 
    cert_store.set_default_paths 
    ssl_context.cert_store = cert_store 
    tcp_socket = TCPSocket.new(remote_host, remote_port) 
    server_socket = OpenSSL::SSL::SSLSocket.new tcp_socket, ssl_context 
    server_socket.sync_close = true 
    server_socket.connect 
rescue Exception => e 
      client.close 
end   
while true 
    # Wait for data to be available on either socket. 
    (ready_sockets, dummy, dummy) = IO.select([client, server_socket]) 
    begin 
     ready_sockets.each do |socket| 
      data = socket.readpartial(4096) 
      if socket == client 
       # Read from client, write to server. 
       server_socket.write data 
       server_socket.flush 
      else 
       # Read from server, write to client. 
       client.write data 
       client.flush 
      end 
    end 
    rescue Exception => e 
    end 
end 
    rescue StandardError => e 
    end 
    begin 
     client.close 
     server_socket.close 
    rescue Exception => e 
    end 

现在,这是工作在正常的TCP和HTTP很大,但是,当我在SSL \ HTTPS中使用它时,在升级套接字时,它开始变得非常慢,有时会超时。

任何想法为什么?

您必须小心阅读和选择,因为读取是在SSL级完成的,而select是在TCP级。

SSL将数据放入帧中,其中每个帧最多可以包含16384个字节。它需要从底层TCP套接字读取完整帧,然后SSL套接字上的读取才能从帧中返回任何数据。这意味着如果你有一个有4097字节有效负载的帧,它需要从TCP套接字读取完整帧,然后才能从SSL套接字读取任何内容。如果您只从SSL套接字读取4096个字节,它将返回前4096个字节,并将其余(1个字节)留在SSL缓冲区中。如果您在TCP级别选择新数据进行检查,则可能会阻止它,因为在TCP级别上没有未读数据,即使SSL缓冲区内仍有单字节。

有两种方法可以解决此问题:

  • 检查与pending是否还有在SSL缓存数据。如果有,请阅读它们而不是进行选择。
  • 或者尝试每次读取时至少读取16384个字节,即SSL帧的最大大小。我不确定在ruby中的实现,但在Perl中,这个读取只会调用底层的SSL_read,这只能读取单个帧中的数据。因此,读取大小为16384字节时,不会有未决数据,您可以像现在一样调用select。
+0

使用IO.select,并将“读取”设置为16384似乎工作,我会研究植入挂起但目前它的窍门。 – Ba7a7chy 2014-10-20 18:51:16