Repository navigation
Expand file tree
/
Copy pathpage.go
More file actions
520 lines (468 loc) · 14.2 KB
/
Copy pathpage.go
File metadata and controls
520 lines (468 loc) · 14.2 KB
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
package engine
import (
"bufio"
"context"
"fmt"
"net/http"
"net/url"
"slices"
"strings"
"sync"
"time"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/proto"
"github.com/projectdiscovery/gologger"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/contextargs"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/generators"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/protocolstate"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/utils/vardump"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/utils"
httputil "github.com/projectdiscovery/nuclei/v3/pkg/protocols/utils/http"
"github.com/projectdiscovery/nuclei/v3/pkg/types"
"github.com/projectdiscovery/utils/errkit"
urlutil "github.com/projectdiscovery/utils/url"
)
// Page is a single page in an isolated browser instance
type Page struct {
ctx *contextargs.Context
inputURL *urlutil.URL
options *Options
page *rod.Page
rules []rule
instance *Instance
hijackRouter *rod.HijackRouter
hijackNative *Hijack
mutex *sync.RWMutex
History []HistoryData
InteractshURLs []string
ActionDurations []time.Duration
payloads map[string]interface{}
variables map[string]interface{}
lastActionNavigate *Action
cancel context.CancelFunc
screenshots int
}
// HistoryData contains the page request/response pairs
type HistoryData struct {
RawRequest string
RawResponse string
}
// Options contains additional configuration options for the browser instance
type Options struct {
Timeout time.Duration
DisableCookie bool
Options *types.Options
// OnNavigationResponse receives the response to the initial URL once the
// actions ran, even when they failed: the browser fails a navigation on
// an error status with an empty body, and that status still matters.
OnNavigationResponse func(*http.Response)
}
// Run runs a list of actions by creating a new page in the browser.
func (i *Instance) Run(ctx *contextargs.Context, actions []*Action, payloads map[string]interface{}, options *Options) (ActionData, *Page, error) {
if err := ctx.Context().Err(); err != nil {
return nil, nil, err
}
pageContext := ctx.Context()
cancelPage := func() {}
if options.Timeout > 0 {
pageContext, cancelPage = context.WithTimeout(pageContext, options.Timeout)
}
page, err := i.engine.Context(pageContext).Page(proto.TargetCreateTarget{})
if err != nil {
cancelPage()
return nil, nil, err
}
page = page.Context(pageContext)
createdPage := &Page{
options: options,
page: page,
ctx: ctx,
instance: i,
mutex: &sync.RWMutex{},
cancel: cancelPage,
}
successfulPageCreation := false
defer func() {
if !successfulPageCreation {
createdPage.Close()
}
}()
if err = i.browser.applyDefaultHeaders(page); err != nil {
return nil, nil, err
}
if i.browser.customAgent != "" {
if userAgentErr := page.SetUserAgent(&proto.NetworkSetUserAgentOverride{UserAgent: i.browser.customAgent}); userAgentErr != nil {
return nil, nil, userAgentErr
}
}
payloads = generators.MergeMaps(payloads,
generators.BuildPayloadFromOptions(i.browser.options),
)
target := ctx.MetaInput.Input
input, err := urlutil.Parse(target)
if err != nil {
return nil, nil, errkit.Wrapf(err, "could not parse URL %s", target)
}
hasTrailingSlash := httputil.HasTrailingSlash(target)
variables := utils.GenerateVariables(input, hasTrailingSlash, contextargs.GenerateVariables(ctx))
variables = generators.MergeMaps(variables, payloads)
if vardump.EnableVarDump {
gologger.Debug().Msgf("Headless Protocol request variables: %s\n", vardump.DumpVariables(variables))
}
createdPage.payloads = payloads
createdPage.variables = variables
createdPage.inputURL = input
if options != nil && options.Options != nil {
if netErr := protocolstate.SetupHeadlessNetworkPolicy(options.Options, page); netErr != nil {
return nil, nil, netErr
}
}
httpclient, err := i.browser.getHTTPClient()
if err != nil {
return nil, nil, err
}
// in case the page has request/response modification rules - enable global hijacking
if createdPage.hasModificationRules() || containsModificationActions(actions...) {
hijackRouter := page.HijackRequests()
if err := hijackRouter.Add("*", "", createdPage.routingRuleHandler(httpclient)); err != nil {
return nil, nil, err
}
createdPage.hijackRouter = hijackRouter
go hijackRouter.Run()
} else {
hijackRouter := NewHijack(page)
hijackRouter.SetPattern(&proto.FetchRequestPattern{
URLPattern: "*",
RequestStage: proto.FetchRequestStageResponse,
})
createdPage.hijackNative = hijackRouter
hijackRouterHandler := hijackRouter.Start(createdPage.routingRuleHandlerNative)
go func() {
_ = hijackRouterHandler()
}()
}
if err := page.SetViewport(&proto.EmulationSetDeviceMetricsOverride{Viewport: &proto.PageViewport{
Scale: 1,
Width: float64(1920),
Height: float64(1080),
}}); err != nil {
return nil, nil, err
}
// inject cookies
// each http request is performed via the native go http client
// we first inject the shared cookies
URL, err := url.Parse(ctx.MetaInput.Input)
if err != nil {
return nil, nil, err
}
if !options.DisableCookie {
if cookies := ctx.CookieJar.Cookies(URL); len(cookies) > 0 {
var NetworkCookies []*proto.NetworkCookie
for _, cookie := range cookies {
networkCookie := &proto.NetworkCookie{
Name: cookie.Name,
Value: cookie.Value,
Domain: cookie.Domain,
Path: cookie.Path,
HTTPOnly: cookie.HttpOnly,
Secure: cookie.Secure,
Expires: proto.TimeSinceEpoch(cookie.Expires.Unix()),
SameSite: proto.NetworkCookieSameSite(GetSameSite(cookie)),
Priority: proto.NetworkCookiePriorityLow,
}
NetworkCookies = append(NetworkCookies, networkCookie)
}
params := proto.CookiesToParams(NetworkCookies)
for _, param := range params {
param.URL = ctx.MetaInput.Input
}
err := page.SetCookies(params)
if err != nil {
return nil, nil, err
}
}
}
data, err := createdPage.ExecuteActions(ctx, actions)
if options.OnNavigationResponse != nil {
if resp := createdPage.NavigationResponse(); resp != nil {
options.OnNavigationResponse(resp)
}
}
if err != nil {
return nil, nil, err
}
// at the end of actions pull out the cookies from the browser. They are
// exposed as DSL variables, since the browser does not report Set-Cookie
// in the intercepted response headers, and they are injected into the
// shared cookie jar unless cookie reuse is disabled. The cookies are read
// for the whole host, because a cookie scoped to another path than the
// input URL is still set by the response.
var httpCookies []*http.Cookie
if cookies, err := page.Browser().GetCookies(); err == nil {
for _, cookie := range cookies {
if !cookieMatchesHost(cookie.Domain, URL.Hostname()) {
continue
}
httpCookie := &http.Cookie{
Name: cookie.Name,
Value: cookie.Value,
Domain: cookie.Domain,
Path: cookie.Path,
HttpOnly: cookie.HTTPOnly,
Secure: cookie.Secure,
}
httpCookies = append(httpCookies, httpCookie)
}
}
if !options.DisableCookie && len(httpCookies) > 0 {
ctx.CookieJar.SetCookies(URL, httpCookies)
}
if resp := createdPage.FirstResponse(); resp != nil {
headers := utils.HeadersToString(resp.Header)
data["header"] = headers
data["all_headers"] = headers
data["status_code"] = fmt.Sprint(resp.StatusCode)
addResponseVariables(data, resp, httpCookies)
}
successfulPageCreation = true // avoid closing the page in case of success in deferred function
return data, createdPage, nil
}
// Close closes a browser page
func (p *Page) Close() {
cleanupCtx, cancelCleanup := context.WithTimeout(context.Background(), browserCleanupTimeout)
defer cancelCleanup()
p.close(cleanupCtx)
}
func (p *Page) close(cleanupCtx context.Context) {
if p.hijackRouter != nil {
_ = p.hijackRouter.Stop()
}
if p.hijackNative != nil {
_ = p.hijackNative.Stop()
}
if p.page.GetContext().Err() != nil {
_, _ = proto.TargetCloseTarget{TargetID: p.page.TargetID}.Call(p.page.Browser().Context(cleanupCtx))
} else {
_ = p.page.Context(cleanupCtx).Close()
}
if p.cancel != nil {
p.cancel()
}
}
// Page returns the current page for the actions
func (p *Page) Page() *rod.Page {
return p.page
}
// Browser returns the browser that created the current page
func (p *Page) Browser() *rod.Browser {
return p.instance.engine
}
// URL returns the URL for the current page.
func (p *Page) URL() string {
info, err := p.page.Info()
if err != nil {
return ""
}
return info.URL
}
// FirstResponse returns the response to the very first request from the
// browser, which is assumed to be the one for the initial URL. It is nil when
// none was recorded.
func (p *Page) FirstResponse() *http.Response {
p.mutex.RLock()
if len(p.History) == 0 {
p.mutex.RUnlock()
return nil
}
raw := p.History[0].RawResponse
p.mutex.RUnlock()
return parseHistoryResponse(raw)
}
// NavigationResponse returns the response that ended the initial navigation,
// nil when none was recorded. Redirect hops are separate history items, so it
// follows Location from the first item to the response that was not a redirect.
func (p *Page) NavigationResponse() *http.Response {
p.mutex.RLock()
history := slices.Clone(p.History)
p.mutex.RUnlock()
return navigationResponse(history)
}
// maxNavigationRedirects matches the redirect limit of Chromium.
const maxNavigationRedirects = 20
func navigationResponse(history []HistoryData) *http.Response {
if len(history) == 0 {
return nil
}
resp := parseHistoryResponse(history[0].RawResponse)
current := historyRequestURL(history[0].RawRequest)
next := 1
for hop := 0; resp != nil && current != nil && hop < maxNavigationRedirects; hop++ {
if resp.StatusCode < 300 || resp.StatusCode > 399 {
break
}
location := resp.Header.Get("Location")
if location == "" {
break
}
target, err := current.Parse(location)
if err != nil {
break
}
found := false
for i := next; i < len(history); i++ {
candidate := historyRequestURL(history[i].RawRequest)
if candidate == nil || !sameResource(candidate, target) {
continue
}
hopResp := parseHistoryResponse(history[i].RawResponse)
if hopResp == nil {
break
}
resp, current, next, found = hopResp, candidate, i+1, true
break
}
if !found {
break
}
}
return resp
}
func parseHistoryResponse(raw string) *http.Response {
resp, err := http.ReadResponse(bufio.NewReader(strings.NewReader(raw)), nil)
if err != nil {
return nil
}
_ = resp.Body.Close()
return resp
}
// historyRequestURL reads the target of a recorded request. The native hijack
// records an absolute URL on the request line. The rod router records a path
// and a Host header.
func historyRequestURL(raw string) *url.URL {
lines := strings.Split(strings.ReplaceAll(raw, "\r\n", "\n"), "\n")
fields := strings.Fields(lines[0])
if len(fields) < 2 {
return nil
}
target, err := url.Parse(fields[1])
if err != nil {
return nil
}
if target.Host != "" {
return target
}
for _, line := range lines[1:] {
if line == "" {
break
}
name, value, ok := strings.Cut(line, ":")
if ok && strings.EqualFold(strings.TrimSpace(name), "Host") {
target.Host = strings.TrimSpace(value)
return target
}
}
return nil
}
// sameResource ignores the scheme, so an http to https redirect still matches
// when the recorded request has no scheme.
func sameResource(a, b *url.URL) bool {
pathOf := func(u *url.URL) string {
if u.EscapedPath() == "" {
return "/"
}
return u.EscapedPath()
}
return strings.EqualFold(a.Host, b.Host) && pathOf(a) == pathOf(b) && a.RawQuery == b.RawQuery
}
// DumpHistory returns the full page navigation history
func (p *Page) DumpHistory() string {
p.mutex.RLock()
defer p.mutex.RUnlock()
var historyDump strings.Builder
for _, historyData := range p.History {
historyDump.WriteString(historyData.RawRequest)
historyDump.WriteString(historyData.RawResponse)
}
return historyDump.String()
}
// addToHistory adds a request/response pair to the page history
func (p *Page) addToHistory(historyData ...HistoryData) {
p.mutex.Lock()
defer p.mutex.Unlock()
p.History = append(p.History, historyData...)
}
func (p *Page) addInteractshURL(URLs ...string) {
p.mutex.Lock()
defer p.mutex.Unlock()
p.InteractshURLs = append(p.InteractshURLs, URLs...)
}
// appendRule records a request/response modification rule. The hijack handler
// reads p.rules from a separate goroutine, so writes must be synchronized.
func (p *Page) appendRule(r rule) {
p.mutex.Lock()
defer p.mutex.Unlock()
p.rules = append(p.rules, r)
}
// rulesSnapshot returns a copy of the current rules for lock-free iteration by
// the hijack handler (which performs network I/O and must not hold the lock).
func (p *Page) rulesSnapshot() []rule {
p.mutex.RLock()
defer p.mutex.RUnlock()
return slices.Clone(p.rules)
}
func (p *Page) hasModificationRules() bool {
for _, rule := range p.rulesSnapshot() {
if containsAnyModificationActionType(rule.Action) {
return true
}
}
return false
}
// updateLastNavigatedURL updates the last navigated URL in the instance's
// request log.
func (p *Page) updateLastNavigatedURL() {
if p.lastActionNavigate == nil {
return
}
templateURL := p.lastActionNavigate.GetArg("url")
p.instance.requestLog[templateURL] = p.URL()
}
func containsModificationActions(actions ...*Action) bool {
for _, action := range actions {
if containsAnyModificationActionType(action.ActionType.ActionType) {
return true
}
}
return false
}
func containsAnyModificationActionType(actionTypes ...ActionType) bool {
for _, actionType := range actionTypes {
switch actionType {
case ActionSetMethod:
return true
case ActionAddHeader:
return true
case ActionSetHeader:
return true
case ActionDeleteHeader:
return true
case ActionSetBody:
return true
}
}
return false
}
func GetSameSite(cookie *http.Cookie) string {
switch cookie.SameSite {
case http.SameSiteNoneMode:
return "none"
case http.SameSiteLaxMode:
return "lax"
case http.SameSiteStrictMode:
return "strict"
case http.SameSiteDefaultMode:
fallthrough
default:
return ""
}
}