|
| 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