This repository has been archived by the owner on Mar 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebanalyze.go
384 lines (311 loc) · 8.13 KB
/
webanalyze.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
package webanalyze
import (
"bytes"
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/bobesa/go-domain-util/domainutil"
)
const VERSION = "1.0"
var (
timeout = 8 * time.Second
wa *WebAnalyzer
)
// Result type encapsulates the result information from a given host
type Result struct {
Host string `json:"host"`
Matches []Match `json:"matches"`
Duration time.Duration `json:"duration"`
Error error `json:"error"`
}
// Match type encapsulates the App information from a match on a document
type Match struct {
App `json:"app"`
AppName string `json:"app_name"`
Matches [][]string `json:"matches"`
Version string `json:"version"`
}
// WebAnalyzer types holds an analyzation job
type WebAnalyzer struct {
appDefs *AppsDefinition
scheduler chan *Job
client *http.Client
}
func (m *Match) updateVersion(version string) {
if version != "" {
m.Version = version
}
}
// NewWebAnalyzer initializes webanalyzer by passing a reader of the
// app definition and an schedulerChan, which allows the scanner to
// add scan jobs on its own
func NewWebAnalyzer(apps io.Reader, client *http.Client) (*WebAnalyzer, error) {
wa := new(WebAnalyzer)
if err := wa.loadApps(apps); err != nil {
return nil, err
}
wa.client = client
return wa, nil
}
// worker loops until channel is closed. processes a single host at once
func (wa *WebAnalyzer) Process(job *Job) (Result, []string) {
// fix missing http scheme
u, err := url.Parse(job.URL)
if u.Scheme == "" {
u.Scheme = "http"
}
job.URL = u.String()
// measure time
t0 := time.Now()
result, links, err := wa.process(job, wa.appDefs)
t1 := time.Now()
res := Result{
Host: job.URL,
Matches: result,
Duration: t1.Sub(t0),
Error: err,
}
return res, links
}
func (wa *WebAnalyzer) CategoryById(cid string) string {
if _, ok := wa.appDefs.Cats[cid]; !ok {
return ""
}
return wa.appDefs.Cats[cid].Name
}
func fetchHost(host string, client *http.Client) (*http.Response, error) {
if client == nil {
client = &http.Client{
Timeout: timeout,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
Proxy: http.ProxyFromEnvironment,
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
req, err := http.NewRequest("GET", host, nil)
if err != nil {
return nil, err
}
req.Header.Add("Accept", "*/*")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
func unique(strSlice []string) []string {
keys := make(map[string]bool)
list := []string{}
for _, entry := range strSlice {
if _, value := keys[entry]; !value {
keys[entry] = true
list = append(list, entry)
}
}
return list
}
func sameUrl(u1, u2 *url.URL) bool {
return u1.Hostname() == u2.Hostname() &&
u1.Port() == u2.Port() &&
u1.RequestURI() == u2.RequestURI()
}
func parseLinks(doc *goquery.Document, base *url.URL, searchSubdomain bool) []string {
var links []string
doc.Find("a").Each(func(i int, s *goquery.Selection) {
val, ok := s.Attr("href")
if !ok {
return
}
u, err := url.Parse(val)
if err != nil {
return
}
urlResolved := base.ResolveReference(u)
if !searchSubdomain && urlResolved.Hostname() != base.Hostname() {
return
}
if searchSubdomain && !isSubdomain(base, u) {
return
}
if urlResolved.RequestURI() == "" {
urlResolved.Path = "/"
}
if sameUrl(base, urlResolved) {
return
}
// only allow http/https
if urlResolved.Scheme != "http" && urlResolved.Scheme != "https" {
return
}
links = append(links, urlResolved.String())
})
return unique(links)
}
func isSubdomain(base, u *url.URL) bool {
return domainutil.Domain(base.String()) == domainutil.Domain(u.String())
}
// do http request and analyze response
func (wa *WebAnalyzer) process(job *Job, appDefs *AppsDefinition) ([]Match, []string, error) {
var apps = make([]Match, 0)
var err error
var cookies []*http.Cookie
var cookiesMap = make(map[string]string)
var body []byte
var headers http.Header
var links []string
// get response from host if allowed
if job.forceNotDownload {
body = job.Body
headers = job.Headers
cookies = job.Cookies
} else {
resp, err := fetchHost(job.URL, wa.client)
if err != nil {
return nil, links, fmt.Errorf("Failed to retrieve: %v", err)
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err == nil {
headers = resp.Header
cookies = resp.Cookies()
}
}
for _, c := range cookies {
cookiesMap[c.Name] = c.Value
}
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(body))
if err != nil {
return nil, links, err
}
// handle crawling
if job.Crawl > 0 {
base, _ := url.Parse(job.URL)
for c, link := range parseLinks(doc, base, job.SearchSubdomain) {
if c >= job.Crawl {
break
}
links = append(links, link)
}
}
for appname, app := range appDefs.Apps {
// TODO: Reduce complexity in this for-loop by functionalising out
// the sub-loops and checks.
findings := Match{
App: app,
AppName: appname,
Matches: make([][]string, 0),
}
// check raw html
if m, v := findMatches(string(body), app.HTMLRegex); len(m) > 0 {
findings.Matches = append(findings.Matches, m...)
findings.updateVersion(v)
}
// check response header
headerFindings, version := app.FindInHeaders(headers)
findings.Matches = append(findings.Matches, headerFindings...)
findings.updateVersion(version)
// check url
if m, v := findMatches(job.URL, app.URLRegex); len(m) > 0 {
findings.Matches = append(findings.Matches, m...)
findings.updateVersion(v)
}
// check script tags
doc.Find("script").Each(func(i int, s *goquery.Selection) {
if script, exists := s.Attr("src"); exists {
if m, v := findMatches(script, app.ScriptRegex); len(m) > 0 {
findings.Matches = append(findings.Matches, m...)
findings.updateVersion(v)
}
}
})
// check meta tags
for _, h := range app.MetaRegex {
selector := fmt.Sprintf("meta[name='%s']", h.Name)
doc.Find(selector).Each(func(i int, s *goquery.Selection) {
content, _ := s.Attr("content")
if m, v := findMatches(content, []AppRegexp{h}); len(m) > 0 {
findings.Matches = append(findings.Matches, m...)
findings.updateVersion(v)
}
})
}
// check cookies
for _, c := range app.CookieRegex {
if _, ok := cookiesMap[c.Name]; ok {
// if there is a regexp set, ensure it matches.
// otherwise just add this as a match
if c.Regexp != nil {
// only match single AppRegexp on this specific cookie
if m, v := findMatches(cookiesMap[c.Name], []AppRegexp{c}); len(m) > 0 {
findings.Matches = append(findings.Matches, m...)
findings.updateVersion(v)
}
} else {
findings.Matches = append(findings.Matches, []string{c.Name})
}
}
}
if len(findings.Matches) > 0 {
apps = append(apps, findings)
// handle implies
for _, implies := range app.Implies {
for implyAppname, implyApp := range appDefs.Apps {
if implies != implyAppname {
continue
}
f2 := Match{
App: implyApp,
AppName: implyAppname,
Matches: make([][]string, 0),
}
apps = append(apps, f2)
}
}
}
}
return apps, links, nil
}
// runs a list of regexes on content
func findMatches(content string, regexes []AppRegexp) ([][]string, string) {
var m [][]string
var version string
for _, r := range regexes {
matches := r.Regexp.FindAllStringSubmatch(content, -1)
if matches == nil {
continue
}
m = append(m, matches...)
if r.Version != "" {
version = findVersion(m, r.Version)
}
}
return m, version
}
// parses a version against matches
func findVersion(matches [][]string, version string) string {
var v string
for _, matchPair := range matches {
// replace backtraces (max: 3)
for i := 1; i <= 3; i++ {
bt := fmt.Sprintf("\\%v", i)
if strings.Contains(version, bt) && len(matchPair) >= i {
v = strings.Replace(version, bt, matchPair[i], 1)
}
}
// return first found version
if v != "" {
return v
}
}
return ""
}