-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurl-scan.go
410 lines (352 loc) · 9.94 KB
/
url-scan.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
package main
import (
"context"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/chromedp/chromedp"
"github.com/chromedp/cdproto/network"
"golang.org/x/net/html"
)
type Crawler struct {
Queue chan string
Visited map[string]bool
Mutex sync.Mutex
WG sync.WaitGroup
OutputCh chan string
InScope []string
OutScope []string
}
func NewCrawler(inscope, outscope []string) *Crawler {
return &Crawler{
Queue: make(chan string, 100),
Visited: make(map[string]bool),
OutputCh: make(chan string),
InScope: inscope,
OutScope: outscope,
}
}
func (c *Crawler) Crawl(startURL string, outputFile string) {
inScopeFile := outputFile + "_in_scope.txt"
outScopeFile := outputFile + "_out_scope.txt"
inScopeCh := make(chan string)
outScopeCh := make(chan string)
go c.writeToFiles(inScopeFile, outScopeFile, inScopeCh, outScopeCh)
c.Queue <- startURL
c.WG.Add(1)
go c.worker(inScopeCh, outScopeCh)
c.WG.Wait()
c.CrawlWithChrome(startURL, inScopeCh, outScopeCh)
close(inScopeCh)
close(outScopeCh)
log.Println("SCAN FINISHED")
}
func (c *Crawler) worker(inScopeCh, outScopeCh chan<- string) {
for url := range c.Queue {
c.processURL(url, inScopeCh, outScopeCh)
c.WG.Done()
}
}
func (c *Crawler) processURL(pageURL string, inScopeCh, outScopeCh chan<- string) {
c.Mutex.Lock()
if c.Visited[pageURL] {
c.Mutex.Unlock()
return
}
c.Visited[pageURL] = true
c.Mutex.Unlock()
fmt.Println("Crawling:", pageURL)
resp, err := c.fetchURL(pageURL)
if err != nil || resp.StatusCode != http.StatusOK {
log.Printf("Error fetching URL %s: %v", pageURL, err)
return
}
defer resp.Body.Close()
doc, err := html.Parse(resp.Body)
if err != nil {
log.Printf("Error parsing HTML for URL %s: %v", pageURL, err)
return
}
urls := c.extractLinks(pageURL, doc)
for _, u := range urls {
if c.isValidURL(u) {
if c.isInScope(u) {
log.Printf("In-scope URL found: %s", u)
inScopeCh <- "In-scope: " + u
c.Queue <- u
c.WG.Add(1)
} else {
log.Printf("Out-of-scope URL found: %s", u)
outScopeCh <- "Out-Of-Scope: " + u
}
} else {
log.Printf("Invalid URL found: %s", u)
}
if isCodeFile(u) {
c.extractURLsFromScript(u, inScopeCh, outScopeCh)
}
}
}
func (c *Crawler) CrawlWithChrome(startURL string, inScopeCh, outScopeCh chan<- string) {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
var wg sync.WaitGroup
ch := make(chan string, 100)
chromedp.ListenTarget(ctx, func(ev interface{}) {
if ev, ok := ev.(*network.EventRequestWillBeSent); ok {
ch <- ev.Request.URL
}
})
wg.Add(1)
go func() {
defer wg.Done()
if err := chromedp.Run(ctx,
network.Enable(),
chromedp.Navigate(startURL),
chromedp.Sleep(5*time.Second),
); err != nil {
log.Printf("Error navigating to URL %s with Chrome: %v", startURL, err)
}
close(ch)
}()
wg.Add(1)
go func() {
defer wg.Done()
for req := range ch {
log.Printf("URL found via Chrome: %s", req)
if c.isValidURL(req) {
if c.isInScope(req) {
log.Printf("In-scope URL found via Chrome: %s", req)
inScopeCh <- "In-scope: " + req
} else {
log.Printf("Out-of-scope URL found via Chrome: %s", req)
outScopeCh <- "Out-Of-Scope: " + req
}
}
}
}()
wg.Wait()
}
func (c *Crawler) extractLinks(base string, n *html.Node) []string {
var urls []string
if n.Type == html.ElementNode {
switch n.Data {
case "a", "link", "img", "iframe", "frame", "embed", "script", "source", "track", "video", "audio", "applet", "object", "area", "base", "input", "form":
for _, a := range n.Attr {
if a.Key == "href" || a.Key == "src" || a.Key == "data" || a.Key == "action" {
absoluteURL := c.formatURL(base, a.Val)
urls = append(urls, absoluteURL)
}
}
case "meta":
for _, a := range n.Attr {
if a.Key == "content" && (strings.Contains(a.Val, "url=") || strings.Contains(a.Val, "URL=")) {
absoluteURL := c.formatURL(base, strings.Split(a.Val, "=")[1])
urls = append(urls, absoluteURL)
}
}
case "button":
for _, a := range n.Attr {
if a.Key == "formaction" {
absoluteURL := c.formatURL(base, a.Val)
urls = append(urls, absoluteURL)
}
}
case "blockquote", "del", "ins", "q":
for _, a := range n.Attr {
if a.Key == "cite" {
absoluteURL := c.formatURL(base, a.Val)
urls = append(urls, absoluteURL)
}
}
case "command":
for _, a := range n.Attr {
if a.Key == "icon" {
absoluteURL := c.formatURL(base, a.Val)
urls = append(urls, absoluteURL)
}
}
case "data":
for _, a := range n.Attr {
if a.Key == "value" {
absoluteURL := c.formatURL(base, a.Val)
urls = append(urls, absoluteURL)
}
}
}
}
for child := n.FirstChild; child != nil; child = child.NextSibling {
urls = append(urls, c.extractLinks(base, child)...)
}
return urls
}
func isCodeFile(u string) bool {
codeExtensions := []string{
".js", ".jsp", ".xml", ".html", ".htm", ".php", ".asp", ".aspx", ".css", ".json",
".txt", ".md", ".yaml", ".csv", ".doc", ".docx", ".pdf", ".ppt", ".pptx", ".xls",
".xlsx", ".ts", ".py", ".rb", ".java", ".c", ".h", ".cs", ".swift", ".kt",
".pl", ".sh", ".bat", ".go"}
for _, ext := range codeExtensions {
if strings.HasSuffix(u, ext) {
return true
}
}
return false
}
func (c *Crawler) extractURLsFromScript(scriptURL string, inScopeCh, outScopeCh chan<- string) {
resp, err := c.fetchURL(scriptURL)
if err != nil || resp.StatusCode != http.StatusOK {
log.Printf("Error fetching script URL %s: %v", scriptURL, err)
return
}
defer resp.Body.Close()
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("Error reading script body for URL %s: %v", scriptURL, err)
return
}
body := string(bodyBytes)
urlRegex := regexp.MustCompile(`http[s]?://[^\s"']+`)
urls := urlRegex.FindAllString(body, -1)
seen := make(map[string]bool)
for _, u := range urls {
if seen[u] {
continue
}
seen[u] = true
log.Printf("URL found in script: %s", u)
if c.isInScope(u) {
log.Printf("In-scope URL found: %s", u)
inScopeCh <- "In-scope: " + u
} else {
log.Printf("Out-of-scope URL found: %s", u)
outScopeCh <- "Out-Of-Scope: " + u
}
}
}
func (c *Crawler) fetchURL(pageURL string) (*http.Response, error) {
var redirectURL string
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
redirectURL = req.URL.String()
log.Printf("Redirected from %s to %s", via[len(via)-1].URL, redirectURL)
return nil
},
}
req, err := http.NewRequest("GET", pageURL, nil)
if err != nil {
log.Printf("Error creating request for URL %s: %v", pageURL, err)
return nil, err
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3")
resp, err := client.Do(req)
if err != nil && redirectURL != "" {
log.Printf("Error fetching URL %s: %v, but redirected to %s", pageURL, err, redirectURL)
} else if err != nil {
log.Printf("Error fetching URL %s: %v", pageURL, err)
}
if err == nil && resp.StatusCode == http.StatusOK {
return resp, nil
}
u, _ := url.Parse(pageURL)
if u.Scheme == "http" {
u.Scheme = "https"
} else {
u.Scheme = "http"
}
req.URL = u
resp, err = client.Do(req)
if err != nil {
log.Printf("Error fetching URL %s: %v", u, err)
}
return resp, err
}
func (c *Crawler) formatURL(base, href string) string {
u, err := url.Parse(href)
if err != nil || u.IsAbs() {
return href
}
baseURL, err := url.Parse(base)
if err != nil {
return href
}
return baseURL.ResolveReference(u).String()
}
func (c *Crawler) isValidURL(u string) bool {
match, _ := regexp.MatchString(`^http[s]?://`, u)
return match
}
func (c *Crawler) isInScope(u string) bool {
parsedURL, err := url.Parse(u)
if err != nil {
return false
}
for _, scope := range c.InScope {
if strings.HasSuffix(parsedURL.Host, scope) {
return true
}
}
for _, scope := range c.OutScope {
if strings.HasSuffix(parsedURL.Host, scope) {
return false
}
}
return len(c.InScope) == 0
}
func (c *Crawler) writeToFiles(inScopeFile, outScopeFile string, inScopeCh, outScopeCh <-chan string) {
inScope, err := os.Create(inScopeFile)
if err != nil {
log.Fatalf("Could not create file %s: %v", inScopeFile, err)
}
defer inScope.Close()
outScope, err := os.Create(outScopeFile)
if err != nil {
log.Fatalf("Could not create file %s: %v", outScopeFile, err)
}
defer outScope.Close()
inScope.WriteString("--IN SCOPE URLS:---\n")
outScope.WriteString("--OUT OF SCOPE URLS:---\n")
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
for u := range inScopeCh {
_, err := inScope.WriteString(u + "\n")
if err != nil {
log.Printf("Could not write URL %s to file: %v", u, err)
}
}
}()
go func() {
defer wg.Done()
for u := range outScopeCh {
_, err := outScope.WriteString(u + "\n")
if err != nil {
log.Printf("Could not write URL %s to file: %v", u, err)
}
}
}()
wg.Wait()
}
func main() {
urlPtr := flag.String("url", "", "URL to start crawling from")
outputPtr := flag.String("output", "output.txt", "Output file to write URLs to")
inScopePtr := flag.String("inscope", "", "Comma-separated list of in-scope base URLs")
outScopePtr := flag.String("outscope", "", "Comma-separated list of out-of-scope base URLs")
flag.Parse()
if *urlPtr == "" {
log.Fatal("Provide a starting URL using -url flag")
}
inScope := strings.Split(*inScopePtr, ",")
outScope := strings.Split(*outScopePtr, ",")
crawler := NewCrawler(inScope, outScope)
crawler.Crawl(*urlPtr, *outputPtr)
}