-
Notifications
You must be signed in to change notification settings - Fork 2
/
hijack.go
242 lines (212 loc) · 7.26 KB
/
hijack.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
package browser
import (
"context"
"encoding/json"
"io"
"net/http"
"strings"
"github.com/pyneda/sukyan/db"
"github.com/pyneda/sukyan/lib"
"github.com/pyneda/sukyan/pkg/http_utils"
"github.com/pyneda/sukyan/pkg/passive"
"fmt"
"github.com/go-rod/rod"
"github.com/rs/zerolog/log"
"gorm.io/datatypes"
)
// HijackConfig represents a hijack configuration to apply when using the browser
type HijackConfig struct {
AnalyzeJs bool
AnalyzeHTML bool
}
type HijackResult struct {
History *db.History
DiscoveredURLs []string
}
func HijackWithContext(config HijackConfig, browser *rod.Browser, source string, resultsChannel chan HijackResult, ctx context.Context, workspaceID, taskID uint) *rod.HijackRouter {
router := browser.HijackRequests()
ignoreKeywords := []string{"google", "pinterest", "facebook", "instagram", "tiktok", "hotjar", "doubleclick", "yandex", "127.0.0.2"}
router.MustAdd("*", func(hj *rod.Hijack) {
select {
case <-ctx.Done():
router.Stop()
return // Stop processing if context is cancelled
default:
// Continue as usual
}
err := hj.LoadResponse(http.DefaultClient, true)
mustSkip := false
if err != nil {
log.Error().Err(err).Str("url", hj.Request.URL().String()).Msg("Error loading hijacked response")
mustSkip = true
}
for _, skipWord := range ignoreKeywords {
if strings.Contains(hj.Request.URL().Host, skipWord) {
mustSkip = true
}
}
if mustSkip {
log.Debug().Str("url", hj.Request.URL().String()).Msg("Skipping processing of hijacked response")
} else {
go func() {
defer func() {
// recover from potential panics (such as sending on closed channel, though it should be avoided by context check)
if recover() != nil {
log.Warn().Msg("Recovered from panic in a hijack goroutine, possibly due to closed channel")
}
}()
// Additional check for context cancellation
history := CreateHistoryFromHijack(hj.Request, hj.Response, source, "Create history from hijack", workspaceID, taskID)
linksFound := passive.ExtractedURLS{}
if hj.Request.Type() != "Image" && hj.Request.Type() != "Font" && hj.Request.Type() != "Media" {
linksFound = passive.ExtractURLsFromHistoryItem(history)
}
hijackResult := HijackResult{
History: history,
DiscoveredURLs: linksFound.Web,
}
select {
case resultsChannel <- hijackResult:
case <-ctx.Done():
router.Stop()
return // Stop processing if context is cancelled
}
}()
}
})
// go func() {
// defer func() {
// router.Stop()
// close(resultsChannel)
// }()
// router.Run()
// }()
go router.Run()
return router
}
func Hijack(config HijackConfig, browser *rod.Browser, source string, resultsChannel chan HijackResult, workspaceID, taskID uint) {
router := browser.HijackRequests()
ignoreKeywords := []string{"google", "pinterest", "facebook", "instagram", "tiktok", "hotjar", "doubleclick", "yandex", "127.0.0.2"}
httpClient := http_utils.CreateHttpClient()
router.MustAdd("*", func(ctx *rod.Hijack) {
err := ctx.LoadResponse(httpClient, true)
mustSkip := false
if err != nil {
log.Error().Err(err).Str("url", ctx.Request.URL().String()).Msg("Error loading hijacked response")
mustSkip = true
}
for _, skipWord := range ignoreKeywords {
if strings.Contains(ctx.Request.URL().Host, skipWord) {
mustSkip = true
}
}
if mustSkip {
log.Debug().Str("url", ctx.Request.URL().String()).Msg("Skipping processing of hijacked response")
} else {
go func() {
history := CreateHistoryFromHijack(ctx.Request, ctx.Response, source, "Create history from hijack", workspaceID, taskID)
linksFound := passive.ExtractedURLS{}
if ctx.Request.Type() != "Image" && ctx.Request.Type() != "Font" && ctx.Request.Type() != "Media" {
linksFound = passive.ExtractURLsFromHistoryItem(history)
}
hijackResult := HijackResult{
History: history,
DiscoveredURLs: linksFound.Web,
}
if resultsChannel != nil {
resultsChannel <- hijackResult
}
}()
}
})
go router.Run()
}
func DumpHijackRequest(req *rod.HijackRequest) (raw string, body string) {
var dump strings.Builder
// Request Line
// dump.WriteString(fmt.Sprintf("%s %s %s\n", req.Method(), req.URL(), "HTTP/1.1")) // Using HTTP/1.1 as a placeholder
method := req.Req().Method
dump.WriteString(fmt.Sprintf("%s %s %s\n", method, req.URL(), "HTTP/1.1")) // Using HTTP/1.1 as a placeholder
// Headers
for k, v := range req.Headers() {
dump.WriteString(fmt.Sprintf("%s: %s\n", k, v))
}
// Body
body = req.Body()
if len(body) > 0 {
dump.WriteString("\n")
dump.WriteString(string(body))
} else {
reader := req.Req().Body
if reader != nil {
bodyBytes, _ := io.ReadAll(reader)
body = string(bodyBytes)
if len(bodyBytes) > 0 {
dump.WriteString("\n")
dump.WriteString(body)
}
}
}
raw = dump.String()
return raw, body
}
func DumpHijackResponse(res *rod.HijackResponse) (rawResponse string, body string) {
var dump strings.Builder
// Status Line
dump.WriteString(fmt.Sprintf("HTTP/1.1 %d %s\n", res.Payload().ResponseCode, http.StatusText(res.Payload().ResponseCode))) // Using HTTP/1.1 as a placeholder
// Headers
for k, values := range res.Headers() {
for _, v := range values {
dump.WriteString(fmt.Sprintf("%s: %s\n", k, v))
}
}
// Body
body = res.Body()
if len(body) > 0 {
dump.WriteString("\n")
dump.WriteString(body)
}
return dump.String(), body
}
// CreateHistoryFromHijack saves a history request from hijack request/response items.
func CreateHistoryFromHijack(request *rod.HijackRequest, response *rod.HijackResponse, source string, note string, workspaceID, taskID uint) *db.History {
requestHeaders, err := json.Marshal(request.Headers())
if err != nil {
log.Error().Err(err).Msg("Error converting request headers to json")
}
responseHeaders, err := json.Marshal(response.Headers())
if err != nil {
log.Error().Err(err).Msg("Error converting response headers to json")
}
rawRequest, reqBody := DumpHijackRequest(request)
rawResponse, responseBody := DumpHijackResponse(response)
historyUrl := request.URL().String()
history := db.History{
StatusCode: response.Payload().ResponseCode,
URL: historyUrl,
Depth: lib.CalculateURLDepth(historyUrl),
RequestHeaders: datatypes.JSON(requestHeaders),
RequestBody: []byte(reqBody),
RequestBodySize: len(reqBody),
RequestContentLength: request.Req().ContentLength,
RequestContentType: request.Req().Header.Get("Content-Type"),
ResponseHeaders: datatypes.JSON(responseHeaders),
ResponseBody: []byte(responseBody), // []byte(response.Body()),
ResponseContentType: response.Headers().Get("Content-Type"),
Evaluated: false,
Method: request.Req().Method,
// ParametersCount: len(request.URL().Query()),
Note: note,
Source: source,
RawRequest: []byte(rawRequest),
RawResponse: []byte(rawResponse),
// ResponseContentLength: response.ContentLength,
WorkspaceID: &workspaceID,
TaskID: &taskID,
PlaygroundSessionID: nil,
Proto: request.Req().Proto,
}
createdHistory, _ := db.Connection.CreateHistory(&history)
log.Debug().Interface("history", history).Msg("New history record created")
return createdHistory
}