创建Java代理MITM

时间:2013-09-07 17:51:29

标签: java proxy man-in-the-middle

我正在尝试创建一个Java程序作为代理来查看来自传入源的数据包以进行调试。为此,我创建了一个简单的Java服务器应用程序,并在设备上编辑了我的主机文件。到目前为止一切正常,(甚至是我的Relay类文件),但我试图将它变成一个完整的代理。我如何合并元素以将数据发送到服务器,并将响应发送回客户端?有点像Man-In-The-Middle类型的东西。

import java.net.*;
import java.io.*;
import org.ini4j.Ini;

public class RelayMultiClient extends Thread {
    private Socket socket = null;
    Socket relay = null;

    public RelayMultiClient(Socket socket) {
    super("RelayMultiClient");
    this.socket = socket;
    }

    public void run() {

    try {
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    socket.getInputStream()));
        if(Relay.max_clients == Relay.connected_clients) {
            //There are too many clients on the server.
            System.out.println("Connection refused from " + socket.getRemoteSocketAddress() + ": Too many clients connected!");
            out.close();
            in.close();
            socket.close();
        }
        else {
            Ini ini = new Ini(new File("settings.ini"));
            Relay.connected_clients++;
            System.out.println("Connection from client " + socket.getRemoteSocketAddress() + " established. Clients Connected: " + Relay.connected_clients);
            while (in.readLine() != null) {
                //Send data to the server
                //Receive data from server and send back to client
            }
            System.out.println("Connection from client " + socket.getRemoteSocketAddress() + " lost.");
            Relay.connected_clients--;
            out.close();
            in.close();
            socket.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    }
}

谢谢, 克里斯

P.S:我没有尝试获取HTTP数据,我试图从我创建的游戏中获取数据。我不知道这类数据是否需要额外处理。

1 个答案:

答案 0 :(得分:2)

  

如何合并元素以将数据发送到服务器,并将响应发送回客户端?

请尝试以下示例作为基本代理:

public class Proxy {
public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = new ServerSocket(1230); // proxy port
    Socket socket = serverSocket.accept();
    Socket relay = new Socket("localhost", 1234); // server address
    new ProxyThread(relay.getInputStream(), socket.getOutputStream()).start();
    new ProxyThread(socket.getInputStream(), relay.getOutputStream()).start();
}
}

class ProxyThread extends Thread {
    private InputStream inputStream;
    private OutputStream outputStream;

ProxyThread(InputStream inputStream, OutputStream outputStream) {
    this.inputStream = inputStream;
    this.outputStream = outputStream;
}

public void run() {
    try {
        int i;
        while ((i = inputStream.read()) != -1){
            outputStream.write(i);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

它缺乏适当的异常处理,只是展示了基本的想法。