| 1 | package http_proxy |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "crypto/tls" |
| 8 | "crypto/x509" |
| 9 | "fmt" |
| 10 | "io/ioutil" |
| 11 | "net" |
| 12 | "net/http" |
| 13 | "net/url" |
| 14 | "path/filepath" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | "time" |
| 18 | |
| 19 | "github.com/bettercap/bettercap/firewall" |
| 20 | "github.com/bettercap/bettercap/session" |
| 21 | btls "github.com/bettercap/bettercap/tls" |
| 22 | |
| 23 | "github.com/elazarl/goproxy" |
| 24 | "github.com/inconshreveable/go-vhost" |
| 25 | |
| 26 | "github.com/evilsocket/islazy/fs" |
| 27 | "github.com/evilsocket/islazy/log" |
| 28 | "github.com/evilsocket/islazy/str" |
| 29 | "github.com/evilsocket/islazy/tui" |
| 30 | ) |
| 31 | |
| 32 | const ( |
| 33 | httpReadTimeout = 5 * time.Second |
| 34 | httpWriteTimeout = 10 * time.Second |
| 35 | ) |
| 36 | |
| 37 | type HTTPProxy struct { |
| 38 | Name string |
| 39 | Address string |
| 40 | Server *http.Server |
| 41 | Redirection *firewall.Redirection |
| 42 | Proxy *goproxy.ProxyHttpServer |
| 43 | Script *HttpProxyScript |
| 44 | CertFile string |
| 45 | KeyFile string |
| 46 | Blacklist []string |
| 47 | Whitelist []string |
| 48 | Sess *session.Session |
| 49 | Stripper *SSLStripper |
| 50 | |
| 51 | jsHook string |
| 52 | isTLS bool |
| 53 | isRunning bool |
| 54 | doRedirect bool |
| 55 | sniListener net.Listener |
| 56 | tag string |
| 57 | } |
| 58 | |
| 59 | func stripPort(s string) string { |
| 60 | ix := strings.IndexRune(s, ':') |
| 61 | if ix == -1 { |
| 62 | return s |
| 63 | } |
| 64 | return s[:ix] |
| 65 | } |
| 66 | |
| 67 | type dummyLogger struct { |
| 68 | p *HTTPProxy |
| 69 | } |
| 70 | |
| 71 | func (l dummyLogger) Printf(format string, v ...interface{}) { |
| 72 | l.p.Debug("[goproxy.log] %s", str.Trim(fmt.Sprintf(format, v...))) |
| 73 | } |
| 74 | |
| 75 | func NewHTTPProxy(s *session.Session, tag string) *HTTPProxy { |
| 76 | p := &HTTPProxy{ |
| 77 | Name: "http.proxy", |
| 78 | Proxy: goproxy.NewProxyHttpServer(), |
| 79 | Sess: s, |
| 80 | Stripper: NewSSLStripper(s, false), |
| 81 | isTLS: false, |
| 82 | doRedirect: true, |
| 83 | Server: nil, |
| 84 | Blacklist: make([]string, 0), |
| 85 | Whitelist: make([]string, 0), |
| 86 | tag: session.AsTag(tag), |
| 87 | } |
| 88 | |
| 89 | p.Proxy.Verbose = false |
| 90 | p.Proxy.Logger = dummyLogger{p} |
| 91 | |
| 92 | p.Proxy.NonproxyHandler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 93 | if p.doProxy(req) { |
| 94 | if !p.isTLS { |
| 95 | req.URL.Scheme = "http" |
| 96 | } |
| 97 | req.URL.Host = req.Host |
| 98 | p.Proxy.ServeHTTP(w, req) |
| 99 | } |
| 100 | }) |
| 101 | |
| 102 | p.Proxy.OnRequest().HandleConnect(goproxy.AlwaysMitm) |
| 103 | p.Proxy.OnRequest().DoFunc(p.onRequestFilter) |
| 104 | p.Proxy.OnResponse().DoFunc(p.onResponseFilter) |
| 105 | |
| 106 | return p |
| 107 | } |
| 108 | |
| 109 | func (p *HTTPProxy) Debug(format string, args ...interface{}) { |
| 110 | p.Sess.Events.Log(log.DEBUG, p.tag+format, args...) |
| 111 | } |
| 112 | |
| 113 | func (p *HTTPProxy) Info(format string, args ...interface{}) { |
| 114 | p.Sess.Events.Log(log.INFO, p.tag+format, args...) |
| 115 | } |
| 116 | |
| 117 | func (p *HTTPProxy) Warning(format string, args ...interface{}) { |
| 118 | p.Sess.Events.Log(log.WARNING, p.tag+format, args...) |
| 119 | } |
| 120 | |
| 121 | func (p *HTTPProxy) Error(format string, args ...interface{}) { |
| 122 | p.Sess.Events.Log(log.ERROR, p.tag+format, args...) |
| 123 | } |
| 124 | |
| 125 | func (p *HTTPProxy) Fatal(format string, args ...interface{}) { |
| 126 | p.Sess.Events.Log(log.FATAL, p.tag+format, args...) |
| 127 | } |
| 128 | |
| 129 | func (p *HTTPProxy) doProxy(req *http.Request) bool { |
| 130 | if req.Host == "" { |
| 131 | p.Error("got request with empty host: %v", req) |
| 132 | return false |
| 133 | } |
| 134 | |
| 135 | hostname := strings.Split(req.Host, ":")[0] |
| 136 | for _, local := range []string{"localhost", "127.0.0.1"} { |
| 137 | if hostname == local { |
| 138 | p.Error("got request with localed host: %s", req.Host) |
| 139 | return false |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | return true |
| 144 | } |
| 145 | |
| 146 | func (p *HTTPProxy) shouldProxy(req *http.Request) bool { |
| 147 | hostname := strings.Split(req.Host, ":")[0] |
| 148 | |
| 149 | // check for the whitelist |
| 150 | for _, expr := range p.Whitelist { |
| 151 | if matched, err := filepath.Match(expr, hostname); err != nil { |
| 152 | p.Error("error while using proxy whitelist expression '%s': %v", expr, err) |
| 153 | } else if matched { |
| 154 | p.Debug("hostname '%s' matched whitelisted element '%s'", hostname, expr) |
| 155 | return true |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | // then the blacklist |
| 160 | for _, expr := range p.Blacklist { |
| 161 | if matched, err := filepath.Match(expr, hostname); err != nil { |
| 162 | p.Error("error while using proxy blacklist expression '%s': %v", expr, err) |
| 163 | } else if matched { |
| 164 | p.Debug("hostname '%s' matched blacklisted element '%s'", hostname, expr) |
| 165 | return false |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | return true |
| 170 | } |
| 171 | |
| 172 | func (p *HTTPProxy) Configure(address string, proxyPort int, httpPort int, doRedirect bool, scriptPath string, |
| 173 | jsToInject string, stripSSL bool) error { |
| 174 | var err error |
| 175 | |
| 176 | // check if another http(s) proxy is using sslstrip and merge strippers |
| 177 | if stripSSL { |
| 178 | for _, mname := range []string{"http.proxy", "https.proxy"}{ |
| 179 | err, m := p.Sess.Module(mname) |
| 180 | if err == nil && m.Running() { |
| 181 | var mextra interface{} |
| 182 | var mstripper *SSLStripper |
| 183 | mextra = m.Extra() |
| 184 | mextramap := mextra.(map[string]interface{}) |
| 185 | mstripper = mextramap["stripper"].(*SSLStripper) |
| 186 | if mstripper != nil && mstripper.Enabled() { |
| 187 | p.Info("found another proxy using sslstrip -> merging strippers...") |
| 188 | p.Stripper = mstripper |
| 189 | break |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | p.Stripper.Enable(stripSSL) |
| 196 | p.Address = address |
| 197 | p.doRedirect = doRedirect |
| 198 | p.jsHook = "" |
| 199 | |
| 200 | if strings.HasPrefix(jsToInject, "http://") || strings.HasPrefix(jsToInject, "https://") { |
| 201 | p.jsHook = fmt.Sprintf("<script src=\"%s\" type=\"text/javascript\"></script></head>", jsToInject) |
| 202 | } else if fs.Exists(jsToInject) { |
| 203 | if data, err := ioutil.ReadFile(jsToInject); err != nil { |
| 204 | return err |
| 205 | } else { |
| 206 | jsToInject = string(data) |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | if p.jsHook == "" && jsToInject != "" { |
| 211 | if !strings.HasPrefix(jsToInject, "<script ") { |
| 212 | jsToInject = fmt.Sprintf("<script type=\"text/javascript\">%s</script>", jsToInject) |
| 213 | } |
| 214 | p.jsHook = fmt.Sprintf("%s</head>", jsToInject) |
| 215 | } |
| 216 | |
| 217 | if scriptPath != "" { |
| 218 | if err, p.Script = LoadHttpProxyScript(scriptPath, p.Sess); err != nil { |
| 219 | return err |
| 220 | } else { |
| 221 | p.Debug("proxy script %s loaded.", scriptPath) |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | p.Server = &http.Server{ |
| 226 | Addr: fmt.Sprintf("%s:%d", p.Address, proxyPort), |
| 227 | Handler: p.Proxy, |
| 228 | ReadTimeout: httpReadTimeout, |
| 229 | WriteTimeout: httpWriteTimeout, |
| 230 | } |
| 231 | |
| 232 | if p.doRedirect { |
| 233 | if !p.Sess.Firewall.IsForwardingEnabled() { |
| 234 | p.Info("enabling forwarding.") |
| 235 | p.Sess.Firewall.EnableForwarding(true) |
| 236 | } |
| 237 | |
| 238 | p.Redirection = firewall.NewRedirection(p.Sess.Interface.Name(), |
| 239 | "TCP", |
| 240 | httpPort, |
| 241 | p.Address, |
| 242 | proxyPort) |
| 243 | |
| 244 | if err := p.Sess.Firewall.EnableRedirection(p.Redirection, true); err != nil { |
| 245 | return err |
| 246 | } |
| 247 | |
| 248 | p.Debug("applied redirection %s", p.Redirection.String()) |
| 249 | } else { |
| 250 | p.Warning("port redirection disabled, the proxy must be set manually to work") |
| 251 | } |
| 252 | |
| 253 | p.Sess.UnkCmdCallback = func(cmd string) bool { |
| 254 | if p.Script != nil { |
| 255 | return p.Script.OnCommand(cmd) |
| 256 | } |
| 257 | return false |
| 258 | } |
| 259 | |
| 260 | return nil |
| 261 | } |
| 262 | |
| 263 | func (p *HTTPProxy) TLSConfigFromCA(ca *tls.Certificate) func(host string, ctx *goproxy.ProxyCtx) (*tls.Config, error) { |
| 264 | return func(host string, ctx *goproxy.ProxyCtx) (c *tls.Config, err error) { |
| 265 | parts := strings.SplitN(host, ":", 2) |
| 266 | hostname := parts[0] |
| 267 | port := 443 |
| 268 | if len(parts) > 1 { |
| 269 | port, err = strconv.Atoi(parts[1]) |
| 270 | if err != nil { |
| 271 | port = 443 |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | cert := getCachedCert(hostname, port) |
| 276 | if cert == nil { |
| 277 | p.Info("creating spoofed certificate for %s:%d", tui.Yellow(hostname), port) |
| 278 | cert, err = btls.SignCertificateForHost(ca, hostname, port) |
| 279 | if err != nil { |
| 280 | p.Warning("cannot sign host certificate with provided CA: %s", err) |
| 281 | return nil, err |
| 282 | } |
| 283 | |
| 284 | setCachedCert(hostname, port, cert) |
| 285 | } else { |
| 286 | p.Debug("serving spoofed certificate for %s:%d", tui.Yellow(hostname), port) |
| 287 | } |
| 288 | |
| 289 | config := tls.Config{ |
| 290 | InsecureSkipVerify: true, |
| 291 | Certificates: []tls.Certificate{*cert}, |
| 292 | } |
| 293 | |
| 294 | return &config, nil |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | func (p *HTTPProxy) ConfigureTLS(address string, proxyPort int, httpPort int, doRedirect bool, scriptPath string, |
| 299 | certFile string, |
| 300 | keyFile string, jsToInject string, stripSSL bool) (err error) { |
| 301 | if err = p.Configure(address, proxyPort, httpPort, doRedirect, scriptPath, jsToInject, stripSSL); err != nil { |
| 302 | return err |
| 303 | } |
| 304 | |
| 305 | p.isTLS = true |
| 306 | p.Name = "https.proxy" |
| 307 | p.CertFile = certFile |
| 308 | p.KeyFile = keyFile |
| 309 | |
| 310 | rawCert, _ := ioutil.ReadFile(p.CertFile) |
| 311 | rawKey, _ := ioutil.ReadFile(p.KeyFile) |
| 312 | ourCa, err := tls.X509KeyPair(rawCert, rawKey) |
| 313 | if err != nil { |
| 314 | return err |
| 315 | } |
| 316 | |
| 317 | if ourCa.Leaf, err = x509.ParseCertificate(ourCa.Certificate[0]); err != nil { |
| 318 | return err |
| 319 | } |
| 320 | |
| 321 | goproxy.GoproxyCa = ourCa |
| 322 | goproxy.OkConnect = &goproxy.ConnectAction{Action: goproxy.ConnectAccept, TLSConfig: p.TLSConfigFromCA(&ourCa)} |
| 323 | goproxy.MitmConnect = &goproxy.ConnectAction{Action: goproxy.ConnectMitm, TLSConfig: p.TLSConfigFromCA(&ourCa)} |
| 324 | goproxy.HTTPMitmConnect = &goproxy.ConnectAction{Action: goproxy.ConnectHTTPMitm, TLSConfig: p.TLSConfigFromCA(&ourCa)} |
| 325 | goproxy.RejectConnect = &goproxy.ConnectAction{Action: goproxy.ConnectReject, TLSConfig: p.TLSConfigFromCA(&ourCa)} |
| 326 | |
| 327 | return nil |
| 328 | } |
| 329 | |
| 330 | func (p *HTTPProxy) httpWorker() error { |
| 331 | p.isRunning = true |
| 332 | return p.Server.ListenAndServe() |
| 333 | } |
| 334 | |
| 335 | type dumbResponseWriter struct { |
| 336 | net.Conn |
| 337 | } |
| 338 | |
| 339 | func (dumb dumbResponseWriter) Header() http.Header { |
| 340 | panic("Header() should not be called on this ResponseWriter") |
| 341 | } |
| 342 | |
| 343 | func (dumb dumbResponseWriter) Write(buf []byte) (int, error) { |
| 344 | if bytes.Equal(buf, []byte("HTTP/1.0 200 OK\r\n\r\n")) { |
| 345 | return len(buf), nil // throw away the HTTP OK response from the faux CONNECT request |
| 346 | } |
| 347 | return dumb.Conn.Write(buf) |
| 348 | } |
| 349 | |
| 350 | func (dumb dumbResponseWriter) WriteHeader(code int) { |
| 351 | panic("WriteHeader() should not be called on this ResponseWriter") |
| 352 | } |
| 353 | |
| 354 | func (dumb dumbResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { |
| 355 | return dumb, bufio.NewReadWriter(bufio.NewReader(dumb), bufio.NewWriter(dumb)), nil |
| 356 | } |
| 357 | |
| 358 | func (p *HTTPProxy) httpsWorker() error { |
| 359 | var err error |
| 360 | |
| 361 | // listen to the TLS ClientHello but make it a CONNECT request instead |
| 362 | p.sniListener, err = net.Listen("tcp", p.Server.Addr) |
| 363 | if err != nil { |
| 364 | return err |
| 365 | } |
| 366 | |
| 367 | p.isRunning = true |
| 368 | for p.isRunning { |
| 369 | c, err := p.sniListener.Accept() |
| 370 | if err != nil { |
| 371 | p.Warning("error accepting connection: %s.", err) |
| 372 | continue |
| 373 | } |
| 374 | |
| 375 | go func(c net.Conn) { |
| 376 | now := time.Now() |
| 377 | c.SetReadDeadline(now.Add(httpReadTimeout)) |
| 378 | c.SetWriteDeadline(now.Add(httpWriteTimeout)) |
| 379 | |
| 380 | tlsConn, err := vhost.TLS(c) |
| 381 | if err != nil { |
| 382 | p.Warning("error reading SNI: %s.", err) |
| 383 | return |
| 384 | } |
| 385 | |
| 386 | hostname := tlsConn.Host() |
| 387 | if hostname == "" { |
| 388 | p.Warning("client does not support SNI.") |
| 389 | return |
| 390 | } |
| 391 | |
| 392 | p.Debug("proxying connection from %s to %s", tui.Bold(stripPort(c.RemoteAddr().String())), tui.Yellow(hostname)) |
| 393 | |
| 394 | req := &http.Request{ |
| 395 | Method: "CONNECT", |
| 396 | URL: &url.URL{ |
| 397 | Opaque: hostname, |
| 398 | Host: net.JoinHostPort(hostname, "443"), |
| 399 | }, |
| 400 | Host: hostname, |
| 401 | Header: make(http.Header), |
| 402 | RemoteAddr: c.RemoteAddr().String(), |
| 403 | } |
| 404 | p.Proxy.ServeHTTP(dumbResponseWriter{tlsConn}, req) |
| 405 | }(c) |
| 406 | } |
| 407 | |
| 408 | return nil |
| 409 | } |
| 410 | |
| 411 | func (p *HTTPProxy) Start() { |
| 412 | go func() { |
| 413 | var err error |
| 414 | |
| 415 | strip := tui.Yellow("enabled") |
| 416 | if !p.Stripper.Enabled() { |
| 417 | strip = tui.Dim("disabled") |
| 418 | } |
| 419 | |
| 420 | p.Info("started on %s (sslstrip %s)", p.Server.Addr, strip) |
| 421 | |
| 422 | if p.isTLS { |
| 423 | err = p.httpsWorker() |
| 424 | } else { |
| 425 | err = p.httpWorker() |
| 426 | } |
| 427 | |
| 428 | if err != nil && err.Error() != "http: Server closed" { |
| 429 | p.Fatal("%s", err) |
| 430 | } |
| 431 | }() |
| 432 | } |
| 433 | |
| 434 | func (p *HTTPProxy) Stop() error { |
| 435 | if p.doRedirect && p.Redirection != nil { |
| 436 | p.Debug("disabling redirection %s", p.Redirection.String()) |
| 437 | if err := p.Sess.Firewall.EnableRedirection(p.Redirection, false); err != nil { |
| 438 | return err |
| 439 | } |
| 440 | p.Redirection = nil |
| 441 | } |
| 442 | |
| 443 | p.Sess.UnkCmdCallback = nil |
| 444 | |
| 445 | if p.isTLS { |
| 446 | p.isRunning = false |
| 447 | p.sniListener.Close() |
| 448 | return nil |
| 449 | } else { |
| 450 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 451 | defer cancel() |
| 452 | return p.Server.Shutdown(ctx) |
| 453 | } |
| 454 | } |