Skip to content

Commit 34296a6

Browse files
committed
proxytest: proxy HTTPS request using MITM
The proxytest now can proxy HTTPS requests using a men in the middle (MITM) approach to allow to fully control the requests between the proxy and the target server.
1 parent 1f3ade3 commit 34296a6

File tree

6 files changed

+648
-155
lines changed

6 files changed

+648
-155
lines changed

NOTICE.txt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1264,11 +1264,11 @@ SOFTWARE
12641264

12651265
--------------------------------------------------------------------------------
12661266
Dependency : github.com/elastic/elastic-agent-libs
1267-
Version: v0.12.1
1267+
Version: v0.12.2-0.20241016085313-16569381887f
12681268
Licence type (autodetected): Apache-2.0
12691269
--------------------------------------------------------------------------------
12701270

1271-
Contents of probable licence file $GOMODCACHE/github.com/elastic/[email protected].1/LICENSE:
1271+
Contents of probable licence file $GOMODCACHE/github.com/elastic/[email protected].2-0.20241016085313-16569381887f/LICENSE:
12721272

12731273
Apache License
12741274
Version 2.0, January 2004

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ require (
1414
github.com/dolmen-go/contextio v0.0.0-20200217195037-68fc5150bcd5
1515
github.com/elastic/elastic-agent-autodiscover v0.9.0
1616
github.com/elastic/elastic-agent-client/v7 v7.16.0
17-
github.com/elastic/elastic-agent-libs v0.12.1
17+
github.com/elastic/elastic-agent-libs v0.12.2-0.20241016085313-16569381887f
1818
github.com/elastic/elastic-agent-system-metrics v0.11.3
1919
github.com/elastic/elastic-transport-go/v8 v8.6.0
2020
github.com/elastic/go-elasticsearch/v8 v8.15.0

go.sum

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -264,8 +264,8 @@ github.com/elastic/elastic-agent-autodiscover v0.9.0 h1:+iWIKh0u3e8I+CJa3FfWe9h0
264264
github.com/elastic/elastic-agent-autodiscover v0.9.0/go.mod h1:5iUxLHhVdaGSWYTveSwfJEY4RqPXTG13LPiFoxcpFd4=
265265
github.com/elastic/elastic-agent-client/v7 v7.16.0 h1:yKGq2+CxAuW8Kh0EoNl202tqAyQKfBcPRawVKs2Jve0=
266266
github.com/elastic/elastic-agent-client/v7 v7.16.0/go.mod h1:6h+f9QdIr3GO2ODC0Y8+aEXRwzbA5W4eV4dd/67z7nI=
267-
github.com/elastic/elastic-agent-libs v0.12.1 h1:5jkxMx15Bna8cq7/Sz/XUIVUXfNWiJ80iSk4ICQ7KJ0=
268-
github.com/elastic/elastic-agent-libs v0.12.1/go.mod h1:5CR02awPrBr+tfmjBBK+JI+dMmHNQjpVY24J0wjbC7M=
267+
github.com/elastic/elastic-agent-libs v0.12.2-0.20241016085313-16569381887f h1:Pp2f6/uzvStgVGAhPuTQa4QMBWd1Ls3YGr0izmPUL80=
268+
github.com/elastic/elastic-agent-libs v0.12.2-0.20241016085313-16569381887f/go.mod h1:5CR02awPrBr+tfmjBBK+JI+dMmHNQjpVY24J0wjbC7M=
269269
github.com/elastic/elastic-agent-system-metrics v0.11.3 h1:LDzRwP8kxvsYEtMDgMSKZs1TgPcSEukit+/EAP5Y28A=
270270
github.com/elastic/elastic-agent-system-metrics v0.11.3/go.mod h1:saqLKe9fuyuAo6IADAnnuy1kaBI7VNlxfwMo8KzSRyQ=
271271
github.com/elastic/elastic-transport-go/v8 v8.6.0 h1:Y2S/FBjx1LlCv5m6pWAF2kDJAHoSjSRSJCApolgfthA=

testing/proxytest/https.go

Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,216 @@
1+
package proxytest
2+
3+
import (
4+
"bufio"
5+
"bytes"
6+
"crypto/rand"
7+
"crypto/rsa"
8+
"crypto/tls"
9+
"errors"
10+
"fmt"
11+
"io"
12+
"log/slog"
13+
"net"
14+
"net/http"
15+
"net/url"
16+
17+
"github.com/elastic/elastic-agent-libs/testing/certutil"
18+
)
19+
20+
func (p *Proxy) serveHTTPS(w http.ResponseWriter, r *http.Request) {
21+
log := loggerFromReqCtx(r)
22+
log.Debug("handling CONNECT")
23+
24+
clientCon, err := hijack(w)
25+
if err != nil {
26+
p.http500Error(clientCon, "cannot handle request", err, log)
27+
return
28+
}
29+
defer clientCon.Close()
30+
31+
// Hijack successful, w is now useless, let's make sure it isn't used by
32+
// mistake ;)
33+
w = nil
34+
log.Debug("hijacked request")
35+
36+
// ==================== CONNECT accepted, let the client know
37+
_, err = clientCon.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
38+
if err != nil {
39+
p.http500Error(clientCon, "failed to send 200-OK after CONNECT", err, log)
40+
return
41+
}
42+
43+
// ==================== TLS handshake
44+
// client will proceed to perform the TLS handshake with the "target",
45+
// which we're impersonating.
46+
47+
// generate a TLS certificate matching the target's host
48+
cert, err := p.newTLSCert(r.URL)
49+
if err != nil {
50+
p.http500Error(clientCon, "failed generating certificate", err, log)
51+
return
52+
}
53+
54+
tlscfg := p.TLS.Clone()
55+
tlscfg.Certificates = []tls.Certificate{*cert}
56+
clientTLSConn := tls.Server(clientCon, tlscfg)
57+
defer clientTLSConn.Close()
58+
err = clientTLSConn.Handshake()
59+
if err != nil {
60+
p.http500Error(clientCon, "failed TLS handshake with client", err, log)
61+
return
62+
}
63+
64+
clientTLSReader := bufio.NewReader(clientTLSConn)
65+
66+
notEOF := func(r *bufio.Reader) bool {
67+
_, err = r.Peek(1)
68+
return !errors.Is(err, io.EOF)
69+
}
70+
// ==================== Handle the actual request
71+
for notEOF(clientTLSReader) {
72+
// read request from the client sent after the 1s CONNECT request
73+
req, err := http.ReadRequest(clientTLSReader)
74+
if err != nil {
75+
p.http500Error(clientTLSConn, "failed reading client request", err, log)
76+
return
77+
}
78+
79+
// carry over the original remote addr
80+
req.RemoteAddr = r.RemoteAddr
81+
82+
// the read request is relative to the host from the original CONNECT
83+
// request and without scheme. Therefore, set them in the new request.
84+
req.URL, err = url.Parse("https://" + r.Host + req.URL.String())
85+
if err != nil {
86+
p.http500Error(clientTLSConn, "failed reading request URL from client", err, log)
87+
return
88+
}
89+
cleanUpHeaders(req.Header)
90+
91+
// now the request is ready, it can be altered just as an HTTP request
92+
// can.
93+
resp, err := p.processRequest(req)
94+
if err != nil {
95+
p.http500Error(clientTLSConn, "failed performing request to target", err, log)
96+
return
97+
}
98+
99+
// Send response from target to client
100+
// 1st - the status code
101+
_, err = clientTLSConn.Write([]byte("HTTP/1.1 " + resp.Status + "\r\n"))
102+
if err != nil {
103+
p.http500Error(clientTLSConn, "failed writing response status line", err, log)
104+
return
105+
}
106+
107+
// 2nd - the headers
108+
if err = resp.Header.Write(clientTLSConn); err != nil {
109+
p.http500Error(clientTLSConn, "failed writing TLS response header", err, log)
110+
return
111+
}
112+
113+
// 3rd - indicates the headers are done and the body will follow
114+
if _, err = clientTLSConn.Write([]byte("\r\n")); err != nil {
115+
p.http500Error(clientTLSConn, "failed writing TLS header/body separator", err, log)
116+
return
117+
}
118+
119+
// copy the body else
120+
_, err = io.CopyBuffer(clientTLSConn, resp.Body, make([]byte, 4096))
121+
if err != nil {
122+
p.http500Error(clientTLSConn, "failed writing response body", err, log)
123+
return
124+
}
125+
126+
_ = resp.Body.Close()
127+
}
128+
129+
log.Debug("EOF reached, finishing HTTPS handler")
130+
}
131+
132+
func (p *Proxy) newTLSCert(u *url.URL) (*tls.Certificate, error) {
133+
// generate the certificate key - it needs to be RSA because Elastic Defend
134+
// do not support EC :/
135+
priv, err := rsa.GenerateKey(rand.Reader, 2048)
136+
if err != nil {
137+
return nil, fmt.Errorf("could not create RSA private key: %w", err)
138+
}
139+
host := u.Hostname()
140+
141+
var name string
142+
var ips []net.IP
143+
ip := net.ParseIP(host)
144+
if ip == nil { // host isn't an IP, therefore it must be an DNS
145+
name = host
146+
} else {
147+
ips = append(ips, ip)
148+
}
149+
150+
cert, _, err := certutil.GenerateGenericChildCert(
151+
name,
152+
ips,
153+
priv,
154+
&priv.PublicKey,
155+
p.ca.capriv,
156+
p.ca.cacert)
157+
if err != nil {
158+
return nil, fmt.Errorf("could not generate TLS certificate for %s: %w",
159+
host, err)
160+
}
161+
162+
return cert, nil
163+
}
164+
165+
func (p *Proxy) http500Error(clientCon net.Conn, msg string, err error, log *slog.Logger) {
166+
p.httpError(clientCon, http.StatusInternalServerError, msg, err, log)
167+
}
168+
169+
func (p *Proxy) httpError(clientCon net.Conn, status int, msg string, err error, log *slog.Logger) {
170+
log.Error(msg, "err", err)
171+
172+
_, err = clientCon.Write(generateHTTPResponse(status, []byte(msg)))
173+
if err != nil {
174+
log.Error("failed writing response", "err", err)
175+
}
176+
}
177+
178+
func hijack(w http.ResponseWriter) (net.Conn, error) {
179+
hijacker, ok := w.(http.Hijacker)
180+
if !ok {
181+
w.WriteHeader(http.StatusInternalServerError)
182+
_, _ = fmt.Fprint(w, "cannot handle request")
183+
return nil, errors.New("http.ResponseWriter does not support hijacking")
184+
}
185+
186+
clientCon, _, err := hijacker.Hijack()
187+
if err != nil {
188+
w.WriteHeader(http.StatusInternalServerError)
189+
_, err = fmt.Fprint(w, "cannot handle request")
190+
191+
return nil, fmt.Errorf("could not Hijack HTTPS CONNECT request: %w", err)
192+
}
193+
194+
return clientCon, err
195+
}
196+
197+
func cleanUpHeaders(h http.Header) {
198+
h.Del("Proxy-Connection")
199+
h.Del("Proxy-Authenticate")
200+
h.Del("Proxy-Authorization")
201+
h.Del("Connection")
202+
}
203+
204+
func generateHTTPResponse(statusCode int, body []byte) []byte {
205+
resp := bytes.Buffer{}
206+
resp.WriteString(fmt.Sprintf("HTTP/1.1 %d %s\r\n",
207+
statusCode, http.StatusText(statusCode)))
208+
resp.WriteString("Content-Type: text/plain\r\n")
209+
resp.WriteString(fmt.Sprintf("Content-Length: %d\r\n", len(body)))
210+
resp.WriteString("\r\n")
211+
if len(body) > 0 {
212+
resp.Write(body)
213+
}
214+
215+
return resp.Bytes()
216+
}

0 commit comments

Comments
 (0)