-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlblaster.go
More file actions
2348 lines (2095 loc) · 90.2 KB
/
sqlblaster.go
File metadata and controls
2348 lines (2095 loc) · 90.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
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"context"
"database/sql"
"encoding/json"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/fatih/color"
"github.com/mitchellh/mapstructure"
"github.com/schollz/progressbar/v3"
)
// Config holds all configuration options
type Config struct {
Host string `json:"host"`
Port int `json:"port"`
SingleUser string `json:"singleUser"`
UserList string `json:"userList"`
SinglePass string `json:"singlePass"`
PassList string `json:"passList"`
Verbose bool `json:"verbose"`
FirstOnly bool `json:"firstOnly"`
UserFirst bool `json:"userFirst"`
ExecCmd string `json:"execCmd"`
AllowDangerous bool `json:"allowDangerous"`
LogFile string `json:"logFile"`
UseSSL bool `json:"useSSL"`
SkipSSL bool `json:"skipSSL"`
Workers int `json:"workers"`
Enum bool `json:"enum"`
EnumOutputFile string `json:"enumOutputFile"`
Dump bool `json:"dump"`
DumpDir string `json:"dumpDir"`
QuietDump bool `json:"quietDump"`
MaxRowsPerFile int `json:"maxRowsPerFile"`
}
// State struct to hold the last tested credentials
type State struct {
LastUser string `json:"last_user"`
LastPass string `json:"last_pass"`
}
// Global configuration
var cfg Config
var connectMode bool
// verbosePrintf prints a message if verbose mode is enabled
func verbosePrintf(format string, a ...interface{}) {
if cfg.Verbose {
fmt.Printf(format, a...)
}
}
// verbosePrintln prints a line if verbose mode is enabled
func verbosePrintln(a ...interface{}) {
if cfg.Verbose {
fmt.Println(a...)
}
}
func main() {
// Always display the banner at program start
displayBanner()
// Define command-line flags
flag.StringVar(&cfg.Host, "h", "", "Remote MySQL server address (required)")
flag.StringVar(&cfg.SingleUser, "u", "", "Single username to test")
flag.StringVar(&cfg.UserList, "U", "", "File containing usernames, one per line")
flag.IntVar(&cfg.Port, "port", 3306, "MySQL server port")
flag.StringVar(&cfg.SinglePass, "p", "", "Single password to test")
flag.StringVar(&cfg.PassList, "P", "", "File containing passwords, one per line")
flag.BoolVar(&cfg.Verbose, "v", false, "Enable verbose mode")
flag.BoolVar(&cfg.FirstOnly, "f", false, "Stop at first successful login")
flag.BoolVar(&cfg.UserFirst, "user-first", false, "Loop over all usernames before next password")
// Fix for the -e flag: Define with default value as a separate variable
execCmdFlag := flag.String("e", "SHOW DATABASES;", "MySQL command to execute on success")
flag.BoolVar(&cfg.AllowDangerous, "allow-dangerous", false, "Allow dangerous commands")
var help bool
flag.BoolVar(&help, "help", false, "Display help message")
flag.StringVar(&cfg.LogFile, "log-file", "", "Log output to a file")
var configFile string
flag.StringVar(&configFile, "config", "", "Load settings from a JSON config file")
flag.BoolVar(&cfg.UseSSL, "use-ssl", false, "Enable SSL/TLS for MySQL connection")
flag.BoolVar(&cfg.SkipSSL, "skip-ssl", false, "Skip SSL/TLS entirely (overrides --use-ssl)")
flag.IntVar(&cfg.Workers, "workers", 10, "Number of concurrent workers")
var generateConfig bool
flag.BoolVar(&generateConfig, "generate-config", false, "Generate a sample config file and exit")
var resume bool
flag.BoolVar(&resume, "resume", false, "Resume from the last tested credentials")
flag.BoolVar(&cfg.Enum, "Enum", false, "Enumerate privileges, databases, and tables on success")
flag.StringVar(&cfg.EnumOutputFile, "enum-output", "", "Save enumeration results to a file")
flag.BoolVar(&connectMode, "connect", false, "Enter interactive mode after successful login")
// New dump flags
flag.BoolVar(&cfg.Dump, "dump", false, "Dump all databases and tables to files")
flag.StringVar(&cfg.DumpDir, "dump-dir", "mysql_dump", "Directory to save dumped data")
flag.BoolVar(&cfg.QuietDump, "quiet-dump", false, "Only show progress during dump, not actual data")
flag.IntVar(&cfg.MaxRowsPerFile, "max-rows", 10000, "Maximum rows per dump file (0 for unlimited)")
flag.Parse()
// Ensure the SQL command doesn't contain flags (sanitize it)
cfg.ExecCmd = sanitizeCommand(*execCmdFlag)
// Set up context for graceful shutdown
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Create a context with the cancel function for global access
ctx = context.WithValue(ctx, "cancelFunc", cancel)
// Set up signal handling
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
go func() {
<-sigChan
fmt.Println("\nShutting down gracefully...")
cancel()
}()
// Generate config file and exit if requested
if generateConfig {
verbosePrintln("Generating sample configuration file")
createSampleConfig()
return
}
// Load config file if specified
if configFile != "" {
verbosePrintln("Loading configuration from", configFile)
loadConfig(configFile)
}
// Show help and exit if requested
if help {
showHelp()
return
}
// Display verbose configuration information
if cfg.Verbose {
fmt.Println("Configuration:")
fmt.Println(" Host:", cfg.Host)
fmt.Println(" Port:", cfg.Port)
if cfg.SingleUser != "" {
fmt.Println(" Username:", cfg.SingleUser)
} else {
fmt.Println(" Username list:", cfg.UserList)
}
if cfg.SinglePass != "" {
fmt.Println(" Password:", cfg.SinglePass)
} else if cfg.PassList != "" {
fmt.Println(" Password list:", cfg.PassList)
} else {
fmt.Println(" Testing with no password")
}
fmt.Println(" Workers:", cfg.Workers)
fmt.Println(" Execute command:", cfg.ExecCmd)
fmt.Println(" SSL enabled:", cfg.UseSSL)
fmt.Println(" SSL skipped:", cfg.SkipSSL)
fmt.Println(" First match only:", cfg.FirstOnly)
fmt.Println(" User-first strategy:", cfg.UserFirst)
fmt.Println(" Allow dangerous commands:", cfg.AllowDangerous)
fmt.Println(" Enumeration enabled:", cfg.Enum)
if cfg.EnumOutputFile != "" {
fmt.Println(" Enumeration output file:", cfg.EnumOutputFile)
}
if cfg.LogFile != "" {
fmt.Println(" Log file:", cfg.LogFile)
}
fmt.Println(" Interactive mode:", connectMode)
if cfg.Dump {
fmt.Println(" Database dump enabled:", cfg.Dump)
fmt.Println(" Dump directory:", cfg.DumpDir)
fmt.Println(" Quiet dump mode:", cfg.QuietDump)
fmt.Println(" Max rows per file:", cfg.MaxRowsPerFile)
}
fmt.Println("")
}
// Validate inputs
if cfg.Host == "" {
color.Red("Error: Hostname (-h) is required.")
showHelp()
os.Exit(1)
}
if cfg.SingleUser == "" && cfg.UserList == "" {
color.Red("Error: Either single username (-u) or username file (-U) must be specified.")
showHelp()
os.Exit(1)
}
if cfg.SingleUser != "" && cfg.UserList != "" {
color.Red("Error: -u and -U are mutually exclusive.")
showHelp()
os.Exit(1)
}
if cfg.UserList != "" && !fileExists(cfg.UserList) {
color.Red("Error: Username file '%s' not found", cfg.UserList)
os.Exit(1)
}
if cfg.PassList != "" && !fileExists(cfg.PassList) {
color.Red("Error: Password file '%s' not found", cfg.PassList)
os.Exit(1)
}
if connectMode {
if cfg.SingleUser == "" || cfg.SinglePass == "" {
color.Red("Error: --connect requires single username (-u) and password (-p).")
showHelp()
os.Exit(1)
}
if cfg.UserList != "" || cfg.PassList != "" {
color.Red("Error: --connect is not compatible with -U or -P flags.")
showHelp()
os.Exit(1)
}
}
if cfg.Dump {
if cfg.SingleUser == "" || cfg.SinglePass == "" {
color.Red("Error: --dump requires single username (-u) and password (-p).")
showHelp()
os.Exit(1)
}
if cfg.UserList != "" || cfg.PassList != "" {
color.Red("Error: --dump is not compatible with -U or -P flags.")
showHelp()
os.Exit(1)
}
}
fmt.Printf("Starting MySQL testing on %s:%d...\n", cfg.Host, cfg.Port)
// Set up logging
var logFile *os.File
if cfg.LogFile != "" {
verbosePrintln("Opening log file:", cfg.LogFile)
var err error
logFile, err = os.OpenFile(cfg.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
color.Red("Error opening log file: %v", err)
os.Exit(1)
}
defer logFile.Close()
verbosePrintln("Log file opened successfully")
}
// Perform the testing
performTesting(ctx, resume, logFile)
}
// sanitizeCommand ensures the SQL command is safe to execute
func sanitizeCommand(cmd string) string {
// Trim whitespace
cmd = strings.TrimSpace(cmd)
// Remove any trailing semicolons (MySQL will add them)
cmd = strings.TrimRight(cmd, ";")
// Add a single semicolon at the end
if cmd != "" && !strings.HasSuffix(cmd, ";") {
cmd += ";"
}
// If somehow the command is empty, use a safe default
if cmd == "" || cmd == ";" {
cmd = "SHOW DATABASES;"
}
return cmd
}
// displayBanner shows the program banner
func displayBanner() {
fmt.Println(`
█
█████
████████ ████
████████ ███████████ █████
███████████ █████ █████ █████
█████ █████ █████ █████ ██████ ███
█████ ████ █████ █████ █████ ██████████████████
██████ ██ █████ █████ █████ ██████████████████
███████ █████ ███████████ ██████████████████
███████ █████ █████ ████ ██ ████████████
███ ███████████ █████████████████ ██████████
████ ███████████████████ ███████████ █████
████ █████ ███████████ ██████ ████ ████ ██
█████ ██████ ███████████ ██ █████ ███ █████
███████████ █████████████ ███████ ██████████
█████ ████████ █████ ████████ ███████ ████████
█████████████ █████ ██ ██████ █████████ ████████
████████████████ ████ ████ ████ █████ ████████████ ██
████ █████ █████ █████ ████████ ████ ████ █████████ ███████ ███
█████ █████ █████ ████ █████████ ██████ █████ █████████ ███ ████████
████ █████ █████ ████ ███████████ ███████ ████ █████ ████ ███████
█████ ███████████ ████ ████ ████ ███ █████████████████████
████████████████ ████ █████ █████ ████ ███████████████████ █████████
███ ████████████ ████ █████ ████ ████████████████ ███████████████
████ █████████ ████████████████████ ██████████████
█████ ██████████████████████ █████████████████
████ ████████████ ████ ██████████████████
█████████████ █████████████████
████████████ ███████████████████
██████████ ███████████████████
█████████████████
███████
`)
fmt.Println("SQL Blaster - A MySQL Enumeration & Dumping Tool Written in Go!")
fmt.Println()
}
// performTesting coordinates the credential testing process
func performTesting(ctx context.Context, resume bool, logFile *os.File) {
verbosePrintln("Starting credential testing process")
if resume {
verbosePrintln("Resume mode is enabled, will attempt to continue from last state")
}
// Special handling for dump mode
if cfg.Dump {
verbosePrintln("Database dump mode enabled, directly testing credentials and performing dump")
result := testLogin(ctx, cfg.SingleUser, cfg.SinglePass, logFile)
if result != "" {
fmt.Println(result)
if logFile != nil {
logFile.WriteString(result + "\n")
}
return
}
return
}
// Prepare usernames
var userChan <-chan string
if cfg.SingleUser != "" {
verbosePrintln("Using single username:", cfg.SingleUser)
userChan = singleValueChannel(cfg.SingleUser)
} else {
if resume && fileExists("state.json") {
state := loadState()
verbosePrintln("Resuming from username:", state.LastUser)
userChan = resumeStreamFromFile(cfg.UserList, state.LastUser)
} else {
verbosePrintln("Loading usernames from file:", cfg.UserList)
userChan = streamLinesFromFile(cfg.UserList)
}
}
// Prepare passwords
var passChan <-chan string
if cfg.SinglePass != "" {
verbosePrintln("Using single password:", cfg.SinglePass)
passChan = singleValueChannel(cfg.SinglePass)
} else if cfg.PassList != "" {
if resume && fileExists("state.json") {
state := loadState()
verbosePrintln("Resuming from password:", state.LastPass)
passChan = resumeStreamFromFile(cfg.PassList, state.LastPass)
} else {
verbosePrintln("Loading passwords from file:", cfg.PassList)
passChan = streamLinesFromFile(cfg.PassList)
}
} else {
verbosePrintln("Testing with no password")
passChan = singleValueChannel("") // Test with no password
}
// Build credential pairs (based on user-first flag)
verbosePrintln("Building credential pairs with strategy:",
map[bool]string{true: "user-first", false: "password-first"}[cfg.UserFirst])
credChan := buildCredentialPairs(userChan, passChan, cfg.UserFirst)
// Count total credentials for progress bar (estimate if streaming)
var totalTests int
if cfg.SingleUser != "" {
if cfg.SinglePass != "" {
totalTests = 1
} else if cfg.PassList != "" {
totalTests = countLines(cfg.PassList)
} else {
totalTests = 1
}
} else if cfg.UserList != "" {
userCount := countLines(cfg.UserList)
if cfg.SinglePass != "" {
totalTests = userCount
} else if cfg.PassList != "" {
totalTests = userCount * countLines(cfg.PassList)
} else {
totalTests = userCount
}
}
verbosePrintln("Estimated total tests to perform:", totalTests)
// Set up progress bar
bar := progressbar.NewOptions(totalTests,
progressbar.OptionSetDescription("Testing credentials"),
progressbar.OptionSetWidth(30),
progressbar.OptionShowCount(),
progressbar.OptionShowIts(),
progressbar.OptionSetItsString("tests"),
)
// Channel to receive results
results := make(chan string, cfg.Workers*2)
var wg sync.WaitGroup
var mu sync.Mutex
successFound := false
// Create worker pool with semaphore
verbosePrintln("Setting up worker pool with", cfg.Workers, "concurrent workers")
semaphore := make(chan struct{}, cfg.Workers)
// Process credential pairs
go func() {
defer close(results)
var processed int
for cred := range credChan {
processed++
if processed%1000 == 0 {
verbosePrintf("\rProcessed %d credential pairs", processed)
}
select {
case <-ctx.Done():
verbosePrintln("\nContext cancelled, stopping credential processing")
return // Context cancelled, stop processing
case semaphore <- struct{}{}: // Acquire semaphore slot
wg.Add(1)
go func(user, pass string) {
defer wg.Done()
defer func() { <-semaphore }() // Release semaphore slot
// Check if we should stop (first success found)
if cfg.FirstOnly {
mu.Lock()
if successFound {
mu.Unlock()
return
}
mu.Unlock()
}
result := testLogin(ctx, user, pass, logFile)
if result != "" {
mu.Lock()
if cfg.FirstOnly && !successFound {
successFound = true
fmt.Println(result)
if logFile != nil {
logFile.WriteString(result + "\n")
}
verbosePrintln("First success found, cancelling remaining operations")
cancel := ctx.Value("cancelFunc").(context.CancelFunc)
cancel() // Cancel all operations
} else {
results <- result
}
mu.Unlock()
}
bar.Add(1)
// Save state after each test
saveState(user, pass)
}(cred.user, cred.pass)
}
}
verbosePrintln("\nAll credential pairs have been submitted to workers")
// Wait for all workers to finish
verbosePrintln("Waiting for all workers to complete")
wg.Wait()
verbosePrintln("All workers have completed")
}()
// Collect and display results
successCount := 0
verbosePrintln("Starting to collect results")
for {
select {
case <-ctx.Done():
verbosePrintln("Context cancelled, stopping result collection")
fmt.Println("\nTesting interrupted.")
verbosePrintf("Found %d successful logins\n", successCount)
return
case result, ok := <-results:
if !ok {
verbosePrintln("Result channel closed, all processing complete")
fmt.Println("\nTesting complete.")
verbosePrintf("Found %d successful logins\n", successCount)
return
}
successCount++
fmt.Println(result)
if logFile != nil {
logFile.WriteString(result + "\n")
}
}
}
}
// Credential represents a username/password pair
type Credential struct {
user string
pass string
}
// buildCredentialPairs creates credential pairs based on strategy
func buildCredentialPairs(userChan, passChan <-chan string, userFirst bool) <-chan Credential {
credChan := make(chan Credential)
go func() {
defer close(credChan)
verbosePrintln("Building credential pairs")
if userFirst {
// Collect all users and passwords
var users, passwords []string
verbosePrintln("Collecting all usernames")
for u := range userChan {
users = append(users, u)
}
verbosePrintf("Collected %d usernames\n", len(users))
verbosePrintln("Collecting all passwords")
for p := range passChan {
passwords = append(passwords, p)
}
verbosePrintf("Collected %d passwords\n", len(passwords))
// Loop users first, then passwords
verbosePrintln("Using user-first strategy to generate pairs")
for i, u := range users {
if i > 0 && i%1000 == 0 {
verbosePrintf("\rProcessed %d/%d users", i, len(users))
}
for _, p := range passwords {
credChan <- Credential{u, p}
}
}
if len(users) >= 1000 {
fmt.Println() // Add newline after progress output
}
} else {
// Direct pairing without storing all combinations
var users []string
verbosePrintln("Collecting all usernames")
for u := range userChan {
users = append(users, u)
}
verbosePrintf("Collected %d usernames\n", len(users))
// For each password, test all users
verbosePrintln("Using password-first strategy to generate pairs")
passwordCount := 0
for p := range passChan {
passwordCount++
if passwordCount%100 == 0 {
verbosePrintf("\rProcessed %d passwords", passwordCount)
}
for _, u := range users {
credChan <- Credential{u, p}
}
}
if passwordCount >= 100 {
fmt.Println() // Add newline after progress output
}
}
verbosePrintln("Finished building credential pairs")
}()
return credChan
}
// singleValueChannel returns a channel that yields a single value
func singleValueChannel(value string) <-chan string {
ch := make(chan string, 1)
ch <- value
close(ch)
return ch
}
// streamLinesFromFile reads lines from a file into a channel
func streamLinesFromFile(filename string) <-chan string {
ch := make(chan string)
go func() {
defer close(ch)
verbosePrintln("Reading lines from", filename)
file, err := os.Open(filename)
if err != nil {
color.Red("Error opening file: %v", err)
return
}
defer file.Close()
lineCount := 0
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line != "" {
ch <- line
lineCount++
if cfg.Verbose && lineCount%1000 == 0 {
fmt.Printf("\rRead %d lines from %s", lineCount, filename)
}
}
}
if cfg.Verbose && lineCount >= 1000 {
fmt.Println() // Add newline after progress output
}
verbosePrintln("Finished reading", lineCount, "lines from", filename)
if err := scanner.Err(); err != nil {
color.Red("Error reading file: %v", err)
}
}()
return ch
}
// resumeStreamFromFile continues reading from a file after lastValue
func resumeStreamFromFile(filename, lastValue string) <-chan string {
ch := make(chan string)
go func() {
defer close(ch)
verbosePrintf("Resuming file read from %s after value %s\n", filename, lastValue)
file, err := os.Open(filename)
if err != nil {
color.Red("Error opening file: %v", err)
return
}
defer file.Close()
foundLast := false
if lastValue == "" {
verbosePrintln("No last value specified, starting from beginning")
foundLast = true // No last value to find, start from beginning
}
lineCount := 0
resumedCount := 0
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
lineCount++
if line == "" {
continue
}
if foundLast {
ch <- line
resumedCount++
if cfg.Verbose && resumedCount%1000 == 0 {
fmt.Printf("\rResumed reading %d lines", resumedCount)
}
} else if line == lastValue {
verbosePrintf("Found last value '%s' at line %d\n", lastValue, lineCount)
foundLast = true
}
}
if cfg.Verbose && resumedCount >= 1000 {
fmt.Println() // Add newline after progress output
}
verbosePrintf("Resume complete: read %d total lines, resumed from line %d, processed %d lines\n",
lineCount, lineCount-resumedCount, resumedCount)
if err := scanner.Err(); err != nil {
color.Red("Error reading file: %v", err)
}
}()
return ch
}
// countLines returns the number of non-empty lines in a file
func countLines(filename string) int {
verbosePrintf("Counting lines in %s... ", filename)
file, err := os.Open(filename)
if err != nil {
verbosePrintln("error:", err)
return 0
}
defer file.Close()
count := 0
scanner := bufio.NewScanner(file)
for scanner.Scan() {
if strings.TrimSpace(scanner.Text()) != "" {
count++
}
}
verbosePrintln("found", count, "lines")
return count
}
// createSampleConfig generates a sample config.json file
func createSampleConfig() {
verbosePrintln("Creating sample configuration file")
sampleConfig := Config{
Host: "mysql.server.com",
Port: 3306,
SingleUser: "admin",
UserList: "users.txt",
SinglePass: "pass123",
PassList: "pass.txt",
Verbose: true,
FirstOnly: false,
UserFirst: false,
ExecCmd: "SHOW DATABASES;",
AllowDangerous: false,
LogFile: "results.log",
UseSSL: false,
Workers: 10,
Enum: false,
EnumOutputFile: "enum_results.txt",
Dump: false,
DumpDir: "mysql_dump",
QuietDump: false,
MaxRowsPerFile: 10000,
}
file, err := os.Create("config.json")
if err != nil {
color.Red("Error creating config file: %v", err)
os.Exit(1)
}
defer file.Close()
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
if err := encoder.Encode(sampleConfig); err != nil {
color.Red("Error encoding config file: %v", err)
os.Exit(1)
}
fmt.Println("Sample config file 'config.json' created. Please adjust the values and remove this message.")
verbosePrintln("Sample config file created successfully")
}
// loadState loads the testing state from the state file
func loadState() State {
var state State
verbosePrintln("Loading state from state.json")
stateFile, err := os.Open("state.json")
if err != nil {
color.Red("Error opening state file: %v", err)
return State{}
}
defer stateFile.Close()
decoder := json.NewDecoder(stateFile)
if err := decoder.Decode(&state); err != nil {
color.Red("Error decoding state file: %v", err)
return State{}
}
verbosePrintln("Loaded state - Last user:", state.LastUser, "Last pass:", state.LastPass)
return state
}
// saveState saves the current state to state.json
func saveState(user, pass string) {
state := State{LastUser: user, LastPass: pass}
file, err := os.Create("state.json")
if err != nil {
color.Red("Error creating state file: %v", err)
return
}
defer file.Close()
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
if err := encoder.Encode(state); err != nil {
color.Red("Error encoding state file: %v", err)
}
}
// loadConfig loads settings from a JSON file
func loadConfig(filename string) {
verbosePrintln("Loading configuration from file:", filename)
file, err := os.Open(filename)
if err != nil {
color.Red("Error opening config file: %v", err)
os.Exit(1)
}
defer file.Close()
var fileConfig map[string]interface{}
decoder := json.NewDecoder(file)
if err := decoder.Decode(&fileConfig); err != nil {
color.Red("Error decoding config file: %v", err)
os.Exit(1)
}
// Use mapstructure to convert map to struct
// Only overwrite values that aren't set by command line
var newCfg Config
if err := mapstructure.Decode(fileConfig, &newCfg); err != nil {
color.Red("Error mapping config values: %v", err)
os.Exit(1)
}
// Only apply values from config file that weren't set via command line
if cfg.Host == "" {
cfg.Host = newCfg.Host
verbosePrintln("Using host from config:", cfg.Host)
}
if cfg.Port == 3306 && newCfg.Port != 0 {
cfg.Port = newCfg.Port
verbosePrintln("Using port from config:", cfg.Port)
}
if cfg.SingleUser == "" && newCfg.SingleUser != "" {
cfg.SingleUser = newCfg.SingleUser
verbosePrintln("Using single user from config:", cfg.SingleUser)
}
if cfg.UserList == "" && newCfg.UserList != "" {
cfg.UserList = newCfg.UserList
verbosePrintln("Using user list from config:", cfg.UserList)
}
if cfg.SinglePass == "" && newCfg.SinglePass != "" {
cfg.SinglePass = newCfg.SinglePass
verbosePrintln("Using single password from config:", cfg.SinglePass)
}
if cfg.PassList == "" && newCfg.PassList != "" {
cfg.PassList = newCfg.PassList
verbosePrintln("Using password list from config:", cfg.PassList)
}
if !cfg.Verbose && newCfg.Verbose {
cfg.Verbose = newCfg.Verbose
verbosePrintln("Enabling verbose mode from config")
}
if !cfg.FirstOnly && newCfg.FirstOnly {
cfg.FirstOnly = newCfg.FirstOnly
verbosePrintln("Enabling first-only mode from config")
}
if !cfg.UserFirst && newCfg.UserFirst {
cfg.UserFirst = newCfg.UserFirst
verbosePrintln("Enabling user-first strategy from config")
}
if cfg.ExecCmd == "SHOW DATABASES;" && newCfg.ExecCmd != "" {
cfg.ExecCmd = sanitizeCommand(newCfg.ExecCmd)
verbosePrintln("Using command from config:", cfg.ExecCmd)
}
if !cfg.AllowDangerous && newCfg.AllowDangerous {
cfg.AllowDangerous = newCfg.AllowDangerous
verbosePrintln("Enabling dangerous command execution from config")
}
if cfg.LogFile == "" && newCfg.LogFile != "" {
cfg.LogFile = newCfg.LogFile
verbosePrintln("Using log file from config:", cfg.LogFile)
}
if !cfg.UseSSL && newCfg.UseSSL {
cfg.UseSSL = newCfg.UseSSL
verbosePrintln("Enabling SSL from config")
}
if !cfg.SkipSSL && newCfg.SkipSSL {
cfg.SkipSSL = newCfg.SkipSSL
verbosePrintln("Skipping SSL from config")
}
if cfg.Workers == 10 && newCfg.Workers != 0 {
cfg.Workers = newCfg.Workers
verbosePrintln("Using worker count from config:", cfg.Workers)
}
if !cfg.Enum && newCfg.Enum {
cfg.Enum = newCfg.Enum
verbosePrintln("Enabling enumeration from config")
}
if cfg.EnumOutputFile == "" && newCfg.EnumOutputFile != "" {
cfg.EnumOutputFile = newCfg.EnumOutputFile
verbosePrintln("Using enumeration output file from config:", cfg.EnumOutputFile)
}
if !cfg.Dump && newCfg.Dump {
cfg.Dump = newCfg.Dump
verbosePrintln("Enabling database dump from config")
}
if cfg.DumpDir == "mysql_dump" && newCfg.DumpDir != "" {
cfg.DumpDir = newCfg.DumpDir
verbosePrintln("Using dump directory from config:", cfg.DumpDir)
}
if !cfg.QuietDump && newCfg.QuietDump {
cfg.QuietDump = newCfg.QuietDump
verbosePrintln("Enabling quiet dump mode from config")
}
if cfg.MaxRowsPerFile == 10000 && newCfg.MaxRowsPerFile != 0 {
cfg.MaxRowsPerFile = newCfg.MaxRowsPerFile
verbosePrintln("Using max rows per file from config:", cfg.MaxRowsPerFile)
}
verbosePrintln("Configuration loaded successfully")
}
// fileExists checks if a file exists and is not a directory
func fileExists(filename string) bool {
verbosePrintf("Checking if file exists: %s... ", filename)
info, err := os.Stat(filename)
if os.IsNotExist(err) {
verbosePrintln("not found")
return false
}
isFile := !info.IsDir()
verbosePrintf("found, is file: %v\n", isFile)
return isFile
}
// getSqlVerb extracts the first SQL verb from a command
func getSqlVerb(cmd string) string {
cmd = strings.TrimSpace(cmd)
cmd = strings.Split(cmd, "--")[0] // Remove comments
cmd = strings.Split(cmd, "#")[0]
words := strings.Fields(cmd)
if len(words) > 0 {
return strings.ToUpper(words[0])
}
return ""
}
// isDangerous checks if a command starts with a dangerous verb or contains dangerous functions
func isDangerous(cmd string) bool {
// Normalize command for checking
cmdUpper := strings.ToUpper(strings.TrimSpace(cmd))
// Check for dangerous SQL verbs
verb := getSqlVerb(cmd)
verbosePrintln("Checking if SQL verb is dangerous:", verb)
dangerousVerbs := []string{"DROP", "DELETE", "TRUNCATE", "UPDATE", "INSERT", "ALTER", "GRANT", "REVOKE", "CREATE"}
for _, v := range dangerousVerbs {
if verb == v {
verbosePrintln("Command is dangerous (dangerous verb)")
return true
}
}
// Check for dangerous functions/operations
dangerousFunctions := []string{
"SYS_EXEC", "SYSTEM_EXEC", "SHELL", "OUTFILE", "DUMPFILE",
"BENCHMARK", "SLEEP", "LOAD_FILE", "INTO OUTFILE", "INTO DUMPFILE",
}
for _, df := range dangerousFunctions {
if strings.Contains(cmdUpper, df) {
verbosePrintln(fmt.Sprintf("Command is dangerous (contains %s)", df))
return true
}
}
verbosePrintln("Command is safe")
return false
}
// testLogin attempts to connect to MySQL and execute the command if successful
func testLogin(ctx context.Context, user, pass string, log *os.File) string {
if cfg.Verbose {
if pass != "" {
fmt.Printf("Testing username: %s with password: %s... ", user, pass)
} else {
fmt.Printf("Testing username: %s (no password)... ", user)
}
}
var dsn string
if cfg.SkipSSL {
// Skip SSL entirely by omitting the tls parameter
dsn = fmt.Sprintf("%s:%s@tcp(%s:%d)/", user, pass, cfg.Host, cfg.Port)
verbosePrintln("Using connection string without SSL")
} else {
tlsOption := "skip-verify" // Default: insecure TLS