How to make http.Server handle requests from a connection

My current goal: write a proxy server with the ability to decrypt https connections.

The problem is the following: after hijacking connections in http.Handler and tls handshake, I get a decrypted connection with http traffic, which I want to process with http.Server, so I do not write my cycle of handling http requests.

How can I do this most correctly and without extra memory allocations?

In the fasthttp library, there is an excellent method of fasthttp.ServeConn, can I do something similar in net.http?

It sounds like you’re building a HTTPS proxy. The net/http/httputil.ReverseProxy type is nice for this and lets you inspect and modify both the request and response in flight. Would that work for you instead of doing hijacking and stuff?

Alternatively, if you want to serve incoming requests from regular http.Handlers, can you not just use a standard listening http.Server?

I do not really understand how httputil.ReverseProxy will help me in the case of MITM.

I will illustrate by an example (the question in the commentary to the code):

	http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) {
		hj, ok := w.(http.Hijacker)
		if !ok {
			http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
			return
		}
		conn, bufrw, err := hj.Hijack()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// Don't forget to close the connection:
		defer conn.Close()

		tls_conn := tls.Server(conn, tlsConfig)
		if err := tls_conn.Handshake(); err != nil {
			return nil, fmt.Errorf("Handshake error: %s", err)
		}
		
		// TODO: How to handle http stream from tls_conn using http.Server?
	})

I don’t understand what happens in your example, so that makes two of us. When you are in the handler function the TLS handshake and HTTP request has already happened, and the request you are looking at is in cleartext. Hijacking to start another handshake at this point doesn’t make sense to me. It is not what a proxy server does.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.