-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathconfig.go
976 lines (816 loc) · 30.8 KB
/
config.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
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
package config
import (
"bufio"
"context"
"flag"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
"github.com/jedib0t/go-pretty/v6/text"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
"github.com/klouddb/klouddbshield/model"
"github.com/klouddb/klouddbshield/pkg/backuphistory"
cons "github.com/klouddb/klouddbshield/pkg/const"
"github.com/klouddb/klouddbshield/pkg/piiscanner"
"github.com/klouddb/klouddbshield/pkg/postgresdb"
"github.com/klouddb/klouddbshield/pkg/utils"
)
type Config struct {
MySQL *MySQL `toml:"mysql"`
Postgres *postgresdb.Postgres `toml:"postgres"`
App App `toml:"app"`
CustomTemplate string `toml:"customTemplate"`
PostgresCheckSet utils.Set[string]
LogParser *LogParser
LogParserConfigErr error
GeneratePassword *GeneratePassword `toml:"generatePassword"`
Crons []Cron `toml:"crons"`
RunCrons bool `toml:"-"`
Email *AuthConfig `toml:"email"`
PiiScannerConfig *piiscanner.Config `toml:"-"`
OutputType string `toml:"outputType"`
CreatePostgresConfig bool `toml:"-"`
ConfigAudit bool `toml:"-"`
SSLCheck bool `toml:"-"`
// CompareConfig is an array of connection strings for multiple PostgreSQL servers
CompareConfig []string `toml:"compare-config"`
CompareConfigBaseServer string `toml:"compare-config-base-server"`
// BackupPath is the path to the backup directory which we will use to
// understand if we are taking backup on daily basis or not
BackupHistoryInput backuphistory.BackupHistoryInput `toml:"-"`
}
func NewPiiInteractiveMode(pgConfig *postgresdb.Postgres, printAll, spacyOnly, summary bool) (*piiscanner.Config, error) {
if pgConfig == nil {
return nil, fmt.Errorf(cons.Err_PostgresConfig_Missing)
}
var readOption string
if !spacyOnly {
readOption = strings.TrimSpace(ReadInput("Please enter run option", piiscanner.RunOption_DataScan_String))
_, ok := piiscanner.RunOptionMap[readOption]
if !ok {
return nil, fmt.Errorf("invalid run option %s, valid options are %s", readOption, strings.Join(piiscanner.RunOptionSlice(), ", "))
}
}
readExcludeTable := strings.TrimSpace(ReadInput("Please enter exclude tables ( e.g table1,table2,table3 )", ""))
readIncludeTable := strings.TrimSpace(ReadInput("Please enter include tables ( e.g table1,table2,table3 )", ""))
readDatabase := strings.TrimSpace(ReadInput("Please enter database name", pgConfig.DBName))
readSchema := strings.TrimSpace(ReadInput("Please enter schema name", "public"))
fmt.Println()
return piiscanner.NewConfig(pgConfig, readOption, readExcludeTable,
readIncludeTable, readDatabase, readSchema, printAll, spacyOnly, summary)
}
type AuthConfig struct {
Host string `toml:"host"`
Port int `toml:"port"`
Username string `toml:"username"`
Password string `toml:"password"`
}
type LogParser struct {
Commands []string
PgSettings *model.PgSettings
Begin time.Time
End time.Time
LogFiles []string
// IpFilePath string
HbaConfFile string
}
func NewLogParser(logParser string, beginTime, endTime, prefix, logfile, hbaConfigFile string) (*LogParser, error) {
commands := []string{logParser}
if logParser == "all" {
commands = []string{}
for _, cmd := range cons.LogParserChoiseMapping {
if cmd == cons.LogParserCMD_All {
continue
}
commands = append(commands, cmd)
}
// added sorting to make sure the order is same in output
sort.StringSlice(commands).Sort()
}
prefix = strings.TrimSpace(prefix)
logfile = strings.TrimSpace(logfile)
// ipfile = strings.TrimSpace(ipfile)
beginTime = strings.TrimSpace(beginTime)
endTime = strings.TrimSpace(endTime)
hbaConfigFile = strings.TrimSpace(hbaConfigFile)
// Valid Command map
validCommands := utils.NewSet[string]()
for _, command := range cons.LogParserChoiseMapping {
validCommands.Add(command)
}
for _, command := range commands {
if !validCommands.Contains(command) {
return nil, fmt.Errorf("invalid command %s, Valid Commands are %s.", command, strings.Join(validCommands.Slice(), " , "))
}
}
if prefix == "" {
return nil, fmt.Errorf("log line prefix is required")
}
var begin, end time.Time
var err error
if beginTime != "" {
begin, err = time.Parse("2006-01-02 15:04:05", beginTime)
if err != nil {
return nil, fmt.Errorf("error while parsing begin time: %v", err)
}
}
if endTime != "" {
end, err = time.Parse("2006-01-02 15:04:05", endTime)
if err != nil {
return nil, fmt.Errorf("error while parsing end time: %v", err)
}
}
// Get the list of files that match the pattern.
files, err := filepath.Glob(logfile)
if err != nil {
return nil, fmt.Errorf("error while validating log file name %s (%v)", logfile, err)
}
if len(files) == 0 {
return nil, fmt.Errorf("no file found for given pattern %s", logfile)
}
// if utils.NewSetFromSlice(commands).IsAvailable(cons.LogParserCMD_MismatchIPs) {
// if ipfile == "" {
// return nil, fmt.Errorf("ip file path is required for mismatch_ips command")
// }
// if _, err := os.Stat(ipfile); err != nil {
// return nil, fmt.Errorf("error while validating ip file name %s (%v)", ipfile, err)
// }
// }
return &LogParser{
Commands: commands,
PgSettings: &model.PgSettings{
LogLinePrefix: prefix,
},
Begin: begin,
End: end,
LogFiles: files,
// IpFilePath: ipfile,
HbaConfFile: hbaConfigFile,
}, nil
}
// IsValidTime checks if given time is between begin and end time
func (a *LogParser) IsValidTime(t time.Time) bool {
// if begin and end time is not zero then check if t is between begin and end time
if !a.Begin.IsZero() && a.Begin.After(t) {
return false
}
if !a.End.IsZero() && a.End.Before(t) {
return false
}
// if begin time or end time is not set then return true
return true
}
type MySQL struct {
Host string `toml:"host"`
Port string `toml:"port"`
User string `toml:"user"`
Password string `toml:"password"`
PingCheck bool `toml:"pingCheck"`
// DBName string `toml:"dbname"`
// SSLmode string `toml:"sslmode"`
MaxIdleConn int `toml:"maxIdleConn"`
MaxOpenConn int `toml:"maxOpenConn"`
}
func (p *MySQL) HtmlReportName() string {
return fmt.Sprintf("mysql_%s:%s", p.Host, p.Port)
}
type GeneratePassword struct {
Length int `toml:"length"`
NumberCount int `toml:"numberCount"`
NumUppercase int `toml:"numUppercase"`
SpecialCharCount int `toml:"specialCharCount"`
}
type App struct {
Debug bool `toml:"debug"`
Hostname string `toml:"hostname"`
Run bool
RunPostgres bool
RunMySql bool
RunRds bool
Verbose bool
Control string
VerboseRDS bool
VerboseMySQL bool
VerbosePostgres bool
HBASacanner bool
VerboseHBASacanner bool
RunMysqlConnTest bool
RunPostgresConnTest bool
RunGeneratePassword bool
RunGenerateEncryptedPassword bool
RunPwnedUsers bool
RunPwnedPasswords bool
InputDirectory string
UseDefaults bool
ThrottlerLIMIT int
PrintSummaryOnly bool
TransactionWraparound bool
PrintProcessTime bool
}
var Version = "dev"
func NewConfig() (*Config, error) {
var verbose bool
var version bool
var help bool
var run bool
flag.BoolVar(&run, "r", run, "Run")
var runPostgres bool
flag.BoolVar(&runPostgres, "run-postgres", runPostgres, "Run Postgres")
var runMySql bool
flag.BoolVar(&runMySql, "run-mysql", runMySql, "Run MySQL")
var runRds bool
flag.BoolVar(&runRds, "run-rds", runRds, "Run AWS RDS")
flag.BoolVar(&runRds, "run-aurora", runRds, "Run AWS Aurora")
var hbaScanner bool
flag.BoolVar(&hbaScanner, "hba-scanner", hbaScanner, "Run HBA Scanner")
var runPostgresConnTest, runGeneratePassword, runGenerateEncryptedPassword, runPwnedUsers, runPwnedPassword bool
flag.BoolVar(&runPostgresConnTest, "run-password-attack-simulator", runPostgresConnTest, "Run Postgres Connection Test")
flag.BoolVar(&runGeneratePassword, "run-password-generator", runGeneratePassword, "Run Generate Password")
flag.BoolVar(&runGenerateEncryptedPassword, "run-encrypt-password", runGenerateEncryptedPassword, "Run Generate Encrypted Password")
flag.BoolVar(&runPwnedUsers, "run-pwned-users", runPwnedUsers, "Run Pwned Users")
flag.BoolVar(&runPwnedPassword, "run-pwned-password", runPwnedPassword, "Run Pwned Password")
var control string
var userDefaults bool
var printSummaryReport bool
var inputDirectory string
var allchecks bool
var setupCron bool
var printProcessTime bool
flag.BoolVar(&verbose, "verbose", verbose, "As of today verbose only works for a specific control. Ex ciscollector -r --verbose --control 6.7")
flag.StringVar(&control, "control", control, "Check verbose detail for individual control.\nMake sure to use this with --verbose option.\nEx: ciscollector -r --verbose --control 6.7")
flag.BoolVar(&allchecks, "allchecks", allchecks, "Run all checks")
flag.BoolVar(&setupCron, "setup-cron", setupCron, "Setup cron for ciscollector")
flag.BoolVar(&printProcessTime, "process-time", printProcessTime, "Print process time")
var customTemplatePath string
flag.StringVar(&customTemplatePath, "custom-template", customTemplatePath, "Custom template path for postgres checks")
// flags related to log parsing
var logParser string
var logfile string
flag.StringVar(&logParser, "logparser", logParser, `To run logparse using with flags. for more details use ciscollector --help`)
flag.StringVar(&logfile, "file-path", "", "File path e.g /location/to/log/file.log. required for all commands in log parser. for more details use ciscollector --help")
var beginTime, endTime string
// read begin time
flag.StringVar(&beginTime, "begin-time", "", "Begin time for log filtering. format supported [2006-01-02 15:04:05]. optional flag for log parser. for more details use ciscollector --help")
// read end time
flag.StringVar(&endTime, "end-time", "", "End time for log filtering. format supported [2006-01-02 15:04:05]. optional flag for log parser. for more details use ciscollector --help")
var prefix string
flag.StringVar(&prefix, "prefix", "", "Log line prefix for offline parsing. required for all commands in log parser")
// var ipFilePath string
// flag.StringVar(&ipFilePath, "ip-file-path", "", "File path for ip list. requered for mismatch_ips command in log parser") // TODO removed because we are not using missing_ip command
var hbaConfigFile string
flag.StringVar(&hbaConfigFile, "hba-file", "", "file path for pg_hba.conf. for unused_lines command in log parser")
var outputType string
flag.StringVar(&outputType, "output-type", "", "Output type for log parser. supported types are json, csv, table")
var cpuLimit int
flag.IntVar(&cpuLimit, "cpu-limit", cpuLimit, "CPU limit for log parser. default is 0")
flag.BoolVar(&userDefaults, "y", run, "Use default options")
flag.StringVar(&inputDirectory, "dir", "", "Directory")
// flag.BoolVar(&hbaSacanner, "r", run, "Run")
// flag.BoolVar(&runMySql, "run-mysql", runMySql, "Run MySQL")
// flag.BoolVar(&runPostgres, "run-postgres", runPostgres, "Run Postgres")
// flag.BoolVar(&runRds, "run-rds", runRds, "Run AWS RDS")
// flag.BoolVar(&verbose, "v", verbose, "Verbose")
flag.BoolVar(&version, "version", version, "Print version")
flag.BoolVar(&help, "help", help, "Print help")
flag.BoolVar(&help, "h", help, "Print help")
var piiscannerRunOption, excludeTable, includeTable, database, schema string
var printAllResults, spacyOnly, printSummaryOnly bool
flag.StringVar(&piiscannerRunOption, "piiscanner", "", "Run pii scanner")
flag.StringVar(&excludeTable, "exclude-table", "", "Exclude table for pii scanner")
flag.StringVar(&includeTable, "include-table", "", "Include table for pii scanner")
flag.StringVar(&database, "database", "", "Database name for pii scanner")
flag.StringVar(&schema, "schema", "public", "Schema name for pii scanner")
flag.BoolVar(&printAllResults, "print-all", false, "Print all results for pii scanner")
flag.BoolVar(&spacyOnly, "spacy-only", false, "Run spacy only for pii scanner")
flag.BoolVar(&printSummaryOnly, "print-summary", false, "Print summary only for pii scanner")
var config string
flag.StringVar(&config, "config", "/etc/klouddbshield", "Config file path")
var transactionWraparound bool
flag.BoolVar(&transactionWraparound, "transaction-wraparound", transactionWraparound, "Generate transaction wraparound report")
var createPostgresConfig bool
flag.BoolVar(&createPostgresConfig, "create-postgres-config", false, "Create postgres config")
var configAudit bool
flag.BoolVar(&configAudit, "config-audit", configAudit, "Config audit")
var sslCheck bool
flag.BoolVar(&sslCheck, "ssl-check", sslCheck, "SSL check")
var backupHistoryInput backuphistory.BackupHistoryInput
flag.StringVar(&backupHistoryInput.BackupPath, "backup-path", "", "Backup path")
flag.StringVar(&backupHistoryInput.BackupTool, "backup-tool", "", "Backup tool")
flag.StringVar(&backupHistoryInput.BackupFrequency, "backup-frequency", "", "Backup frequency")
var compareConfig compareConfigFlag
flag.Var(&compareConfig, "compare-config", "Connection strings for multiple PostgreSQL servers to compare (can be specified multiple times)")
var compareConfigBaseServer string
flag.StringVar(&compareConfigBaseServer, "compare-config-base-server", "", "Base server for comparison")
flag.Parse()
if cpuLimit != 0 {
runtime.GOMAXPROCS(cpuLimit)
}
if setupCron {
c, err := LoadConfig(config)
if err != nil {
return nil, err
}
c.RunCrons = true
return c, nil
}
if version {
log.Debug().Str("version", Version).Send()
os.Exit(0)
}
if help {
PrintHelp()
os.Exit(0)
}
if !run && !verbose && !allchecks && logParser == "" && piiscannerRunOption == "" &&
!spacyOnly && !configAudit && !sslCheck && !transactionWraparound &&
!runPostgres && !runMySql && !runRds && !hbaScanner &&
!runPostgresConnTest && !runGeneratePassword && !runGenerateEncryptedPassword &&
!runPwnedUsers && !runPwnedPassword && backupHistoryInput.BackupTool == "" &&
!createPostgresConfig && len(compareConfig) == 0 {
fmt.Println("> For Help: " + text.FgGreen.Sprint("ciscollector --help"))
os.Exit(0)
}
c := &Config{}
if !runRds {
var err error
c, err = LoadConfig(config)
if err != nil && logParser == "" {
return nil, fmt.Errorf("loading config: %v", err)
}
}
c.App.PrintProcessTime = printProcessTime
c.OutputType = outputType
var piiConfig *piiscanner.Config
if piiscannerRunOption != "" || (spacyOnly && !run) {
var err error
piiConfig, err = piiscanner.NewConfig(c.Postgres, piiscannerRunOption, excludeTable,
includeTable, database, schema, printAllResults, spacyOnly, printSummaryOnly)
if err != nil {
fmt.Println("Error in creating pii scanner config: ", text.FgHiRed.Sprint(err))
os.Exit(1)
}
}
// if controlVerbose != "" {
// fmt.Print(controlVerbose)
// }
if allchecks {
runPostgres = true
hbaScanner = true
logParser = cons.LogParserCMD_All
runPwnedUsers = true
printSummaryReport = true
transactionWraparound = true
sslCheck = true
} else if run && !verbose {
if customTemplatePath != "" {
fmt.Print(cons.MSG_ChoiseCustomTemplate)
} else {
fmt.Print(cons.MSG_Choise)
}
choice := 0
fmt.Scanln(&choice) //nolint:errcheck
switch choice {
case cons.SelectionIndex_AllCommands: // All Postgres checks(Recommended)
runPostgres = true
hbaScanner = true
logParser = cons.LogParserCMD_All
runPwnedUsers = true
printSummaryReport = true
transactionWraparound = true
sslCheck = true
case cons.SelectionIndex_PostgresChecks: // Postgres CIS and User Security checks
runPostgres = true
response := "N"
fmt.Print("Do you also want to run HBA Scanner?(y/N):")
fmt.Scanln(&response) //nolint:errcheck
if strings.ToLower(response) == "y" || strings.ToLower(response) == "yes" {
hbaScanner = true
}
case cons.SelectionIndex_HBAScanner: // HBA Scanner
hbaScanner = true
case cons.SelectionIndex_PIIScanner: // PII Db Scanner
var err error
piiConfig, err = NewPiiInteractiveMode(c.Postgres, printAllResults, spacyOnly, printSummaryOnly)
if err != nil {
fmt.Println("Error in creating pii scanner config: ", text.FgHiRed.Sprint(err))
os.Exit(1)
}
case cons.SelectionIndex_InactiveUsers: // Inactive user report
logParser = cons.LogParserCMD_InactiveUser
case cons.SelectionIndex_UniqueIPs: // Client ip report
logParser = cons.LogParserCMD_UniqueIPs
case cons.SelectionIndex_HBAUnusedLines: // HBA unused lines report
logParser = cons.LogParserCMD_HBAUnusedLines
case cons.SelectionIndex_PasswordManager: // Password Manager
fmt.Println("1. Password attack simulator")
fmt.Println("2. Password generator")
fmt.Println("3. Encrypt a password(scram-sha-256)")
fmt.Println("4. Match common usernames")
fmt.Println("5. Pawned password detector")
fmt.Printf("Enter your choice to execute(1/2/3/4/5):")
choice := 0
fmt.Scanln(&choice) //nolint:errcheck
switch choice {
case 1:
runPostgresConnTest = true
case 2:
runGeneratePassword = true
case 3:
runGenerateEncryptedPassword = true
case 4:
runPwnedUsers = true
case 5:
runPwnedPassword = true
default:
fmt.Println("Invalid Choice, Please Try Again.")
os.Exit(1)
}
case cons.SelectionIndex_PasswordLeakScanner: // Password leak scanner
logParser = cons.LogParserCMD_PasswordLeakScanner
case cons.SelectionIndex_AWSRDS: // AWS RDS Sec Report
runRds = true
case cons.SelectionIndex_AWSAurora: // AWS Aurora Sec Report
runRds = true
case cons.SelectionIndex_MySQL: // MySQL Report
runMySql = true
case cons.SelectionIndex_TransactionWraparound: // Transaction Wraparound
transactionWraparound = true
case cons.SelectionIndex_Exit: // Exit
os.Exit(0)
case cons.SelectionIndex_CreatePostgresConfig:
createPostgresConfig = true
case cons.SelectionIndex_ConfigAuditing:
configAudit = true
case cons.SelectionIndex_CompareConfig:
compareConfigBaseServer = ReadInput("Enter the base server for comparison", "")
if compareConfigBaseServer == "" {
fmt.Println("Base server is required")
os.Exit(1)
}
configs := ReadInput("Enter the connection strings for the servers to compare (can be specified comma separated)", "")
if configs == "" {
fmt.Println("No connection strings provided")
os.Exit(1)
}
for _, config := range strings.Split(configs, ",") {
config = strings.TrimSpace(config)
if config == "" {
continue
}
compareConfig = append(compareConfig, config)
}
if len(compareConfig) == 0 {
fmt.Println("No connection strings provided")
os.Exit(1)
}
fmt.Println(compareConfig)
case cons.SelectionIndex_SSLCheck:
sslCheck = true
case cons.SelectionIndex_BackupAuditTool:
backupHistoryInput.BackupTool = ReadInput("Enter the backup tool (e.g pg_dump, pg_basebackup, pgbackrest)", "pg_dump")
if backupHistoryInput.BackupTool != "pgbackrest" {
backupHistoryInput.BackupPath = ReadInput("Enter the backup path (e.g /path/to/backup)", "")
}
backupHistoryInput.BackupFrequency = ReadInput("Enter the backup frequency (e.g daily, weekly, monthly)", "")
if backupHistoryInput.BackupTool == "" || backupHistoryInput.BackupFrequency == "" {
fmt.Println("Backup tool and frequency are required")
os.Exit(1)
}
if backupHistoryInput.BackupTool != "pgbackrest" && backupHistoryInput.BackupTool != "pg_dump" && backupHistoryInput.BackupTool != "pg_dumpall" && backupHistoryInput.BackupTool != "pg_basebackup" {
fmt.Println("Invalid backup tool. Supported tools are pg_dump, pg_dumpall, pg_basebackup")
os.Exit(1)
}
if backupHistoryInput.BackupTool != "pgbackrest" && backupHistoryInput.BackupPath == "" {
fmt.Println("Backup path is required for " + backupHistoryInput.BackupTool)
os.Exit(1)
}
default:
fmt.Println("Invalid Choice, Please Try Again.")
os.Exit(1)
}
}
c.PiiScannerConfig = piiConfig
c.PostgresCheckSet = utils.NewDummyContainsAllSet[string]()
c.BackupHistoryInput = backupHistoryInput
c.CreatePostgresConfig = createPostgresConfig
c.ConfigAudit = configAudit
c.SSLCheck = sslCheck
if c.CustomTemplate != "" {
var checkNumbers []string
var err error
if strings.HasSuffix(c.CustomTemplate, ".json") {
checkNumbers, err = utils.LoadJsonTemplate(c.CustomTemplate)
} else if strings.HasSuffix(c.CustomTemplate, ".csv") {
checkNumbers, err = utils.LoadCSVTemplate(c.CustomTemplate)
} else {
return nil, fmt.Errorf("Invalid file format. Supported formats are json and csv")
}
if err != nil {
return nil, fmt.Errorf("loading custom template: %v", err)
}
c.PostgresCheckSet = utils.NewSetFromSlice(checkNumbers)
}
c.App.Run = run
c.App.RunMySql = runMySql
c.App.RunPostgres = runPostgres
c.App.RunRds = runRds
c.App.Verbose = verbose
c.App.Control = control
c.App.HBASacanner = hbaScanner
c.App.RunPostgresConnTest = runPostgresConnTest
c.App.RunPwnedUsers = runPwnedUsers
c.App.RunPwnedPasswords = runPwnedPassword
c.App.RunGeneratePassword = runGeneratePassword
c.App.RunGenerateEncryptedPassword = runGenerateEncryptedPassword
c.App.UseDefaults = userDefaults
c.App.InputDirectory = inputDirectory
c.App.PrintSummaryOnly = printSummaryReport
c.App.TransactionWraparound = transactionWraparound
c.PiiScannerConfig = piiConfig
if customTemplatePath != "" {
c.CustomTemplate = customTemplatePath
}
if run && verbose {
if customTemplatePath != "" {
fmt.Print(cons.MSG_ChoiseCustomTemplate)
} else {
fmt.Print(cons.MSG_Choise)
}
choice := 0
fmt.Scanln(&choice) //nolint:errcheck
switch choice {
case cons.SelectionIndex_AllCommands: // All Postgres checks(Recommended)
if c.App.Verbose && c.Postgres != nil {
c.App.VerbosePostgres = true
} else {
fmt.Println(cons.Err_PostgresConfig_Missing)
os.Exit(1)
}
if c.App.Verbose && c.Postgres != nil {
c.App.VerboseHBASacanner = true
} else {
fmt.Println(cons.Err_PostgresConfig_Missing)
os.Exit(1)
}
c.App.PrintSummaryOnly = true
logParser = cons.LogParserCMD_All
c.App.RunPwnedUsers = true
c.App.TransactionWraparound = true
case cons.SelectionIndex_PostgresChecks: // Postgres checks
if c.App.Verbose && c.Postgres != nil {
c.App.VerbosePostgres = true
} else {
fmt.Println(cons.Err_PostgresConfig_Missing)
os.Exit(1)
}
case cons.SelectionIndex_HBAScanner: // HBA Scanner
if c.App.Verbose && c.Postgres != nil {
c.App.VerboseHBASacanner = true
} else {
fmt.Println(cons.Err_PostgresConfig_Missing)
os.Exit(1)
}
case cons.SelectionIndex_PIIScanner: // PII DB Scanner
fmt.Println("Verbose feature is not available for PII DB Scanner yet .. Will be added in future releases")
case cons.SelectionIndex_InactiveUsers: // Inactive user report
fmt.Println("Verbose feature is not available for Inactive user yet .. Will be added in future releases")
os.Exit(1)
case cons.SelectionIndex_UniqueIPs: // Client ip report
fmt.Println("Verbose feature is not available for Client IP user yet .. Will be added in future releases")
os.Exit(1)
case cons.SelectionIndex_HBAUnusedLines: // HBA unused lines report
fmt.Println("Verbose feature is not available for HBA Unused lines yet .. Will be added in future releases")
os.Exit(1)
case cons.SelectionIndex_PasswordManager: // Password Manager
fmt.Println("1. Password attack simulator")
fmt.Println("2. Password generator")
fmt.Println("3. Encrypt a password(scram-sha-256)")
fmt.Println("4. Match common usernames")
fmt.Println("5. Pawned password detector")
fmt.Printf("Enter your choice to execute(1/2/3/4/5):")
choice := 0
fmt.Scanln(&choice) //nolint:errcheck
switch choice {
case 1:
c.App.RunPostgresConnTest = true
case 2:
c.App.RunGeneratePassword = true
case 3:
c.App.RunGenerateEncryptedPassword = true
case 4:
c.App.RunPwnedUsers = true
case 5:
c.App.RunPwnedPasswords = true
default:
fmt.Println("Invalid Choice, Please Try Again.")
os.Exit(1)
}
case cons.SelectionIndex_PasswordLeakScanner: // Password leak scanner
fmt.Println("Verbose feature is not available for Password Leak lines yet .. Will be added in future releases")
os.Exit(1)
case cons.SelectionIndex_AWSRDS: // AWS RDS Sec Report
fmt.Println("Verbose feature is not available for MySQL and RDS yet .. Will be added in future releases")
os.Exit(1)
case cons.SelectionIndex_AWSAurora: // AWS Aurora Sec Report
fmt.Println("Verbose feature is not available for MySQL and RDS yet .. Will be added in future releases")
os.Exit(1)
case cons.SelectionIndex_MySQL: // MySQL Report
fmt.Println("Verbose feature is not available for MySQL and RDS yet .. Will be added in future releases")
os.Exit(1)
case cons.SelectionIndex_TransactionWraparound: // Transaction Wraparound
fmt.Println("Verbose feature is not available for Transactions yet .. Will be added in future releases")
os.Exit(1)
case cons.SelectionIndex_Exit:
os.Exit(0)
case cons.SelectionIndex_CreatePostgresConfig:
createPostgresConfig = true
case cons.SelectionIndex_ConfigAuditing:
c.ConfigAudit = true
case cons.SelectionIndex_CompareConfig:
fmt.Println("Verbose feature is not available for Compare Config yet .. Will be added in future releases")
os.Exit(1)
case cons.SelectionIndex_SSLCheck:
fmt.Println("Verbose feature is not available for SSL Check yet .. Will be added in future releases")
os.Exit(1)
default:
fmt.Println("Invalid Choice, Please Try Again.")
os.Exit(1)
}
}
var err error
if c.App.Hostname == "" {
c.App.Hostname, err = os.Hostname()
if err != nil {
return nil, fmt.Errorf("getting hostname: %v", err)
}
}
if c.MySQL == nil && c.Postgres == nil && !runRds && c.LogParser == nil && c.BackupHistoryInput.BackupTool == "" {
return nil, fmt.Errorf(cons.Err_PostgresConfig_Missing)
}
if c.MySQL != nil && c.Postgres != nil && !runRds {
return nil, fmt.Errorf(cons.Err_MysqlConfig_Missing)
}
if c.MySQL == nil && runMySql {
return nil, fmt.Errorf(cons.Err_OldversionSuggestion_Postgres)
}
postgresConfigNeeded := runPostgres || c.App.HBASacanner || c.PiiScannerConfig != nil || c.App.TransactionWraparound || c.SSLCheck
if c.Postgres == nil && postgresConfigNeeded {
return nil, fmt.Errorf(cons.Err_OldversionSuggestion_Mysql)
}
if c.MySQL != nil && c.MySQL.User == "" && runMySql {
fmt.Printf("Enter Your MySQL DB User: ")
fmt.Scanln(&c.MySQL.User) //nolint:errcheck
}
if c.MySQL != nil && c.MySQL.Password == "" && runMySql {
fmt.Printf("Enter Your DB MySQL Password for %s: ", c.MySQL.User)
fmt.Scanln(&c.MySQL.Password) //nolint:errcheck
}
if c.Postgres != nil && c.Postgres.User == "" && postgresConfigNeeded {
fmt.Printf("Enter Your Postgres DB User: ")
fmt.Scanln(&c.Postgres.User) //nolint:errcheck
}
if c.Postgres != nil && c.Postgres.Password == "" && postgresConfigNeeded {
fmt.Printf("Enter Your DB Postgres Password for %s: ", c.Postgres.User)
fmt.Scanln(&c.Postgres.Password) //nolint:errcheck
}
if c.GeneratePassword == nil {
c.GeneratePassword = &GeneratePassword{
Length: 20,
NumberCount: 2,
NumUppercase: 2,
SpecialCharCount: 2,
}
}
if logParser != "" {
if run || (allchecks && prefix == "") {
c.LogParser, c.LogParserConfigErr = getLogParserInputs(c.Postgres, logParser)
} else {
var err error
c.LogParser, err = NewLogParser(logParser, beginTime, endTime, prefix, logfile, hbaConfigFile)
if err != nil {
c.LogParserConfigErr = fmt.Errorf("Invalid input for logparser: %v", err)
}
}
}
c.CompareConfig = compareConfig
c.CompareConfigBaseServer = compareConfigBaseServer
if c.CompareConfigBaseServer != "" && len(c.CompareConfig) == 0 {
return nil, fmt.Errorf("with base server, at least one connection string is required")
}
return c, nil
}
func LoadConfig(configPath string) (*Config, error) {
v := viper.New()
v.SetConfigType("toml")
v.SetConfigName("kshieldconfig")
if configPath == "" {
configPath = "."
}
v.AddConfigPath(configPath)
c := &Config{}
err := v.ReadInConfig()
if err != nil {
return c, fmt.Errorf("fatal error config file: %v", err)
}
err = v.Unmarshal(c)
if err != nil {
return c, fmt.Errorf("unmarshal: %v", err)
}
return c, nil
}
func ReadInput(msg, detault string) string {
reader := bufio.NewReader(os.Stdin)
fmt.Print("> " + msg)
if detault != "" {
fmt.Print(" [" + detault + "]")
}
fmt.Print(": ")
input, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Invalid input for logparser:", err)
os.Exit(1)
}
input = strings.TrimSuffix(input, "\n")
input = strings.Trim(input, `"`)
input = strings.Trim(input, "'")
if input == "" {
return detault
}
return input
}
func getLogParserInputs(postgresConf *postgresdb.Postgres, command string) (*LogParser, error) {
if command == "" {
return nil, fmt.Errorf("Invalid Choice, Please Try Again.")
}
hbaConfigSuggestion := ""
prefixSuggestion := ""
logfileSuggestion := ""
if postgresConf != nil {
store, _, err := postgresdb.Open(*postgresConf)
if err == nil {
defer store.Close()
prefixSuggestion, _ = utils.GetLoglinePrefix(context.Background(), store)
dataDir, _ := utils.GetDataDirectory(context.Background(), store)
if dataDir != "" {
logfileSuggestion = dataDir + "/log/*.log"
}
if command == cons.LogParserCMD_HBAUnusedLines || command == cons.LogParserCMD_All {
hbaConfigSuggestion, _ = utils.GetHBAFilePath(context.Background(), store)
if _, err := os.Stat(hbaConfigSuggestion); err != nil {
hbaConfigSuggestion = ""
}
}
}
}
prefix := ReadInput("Enter Log Line Prefix", prefixSuggestion)
logfile := ReadInput("Enter Log File Path", logfileSuggestion)
beginTime := ReadInput("Enter Begin Time (format: 2006-01-02 15:04:05) [optional]", "")
endTime := ReadInput("Enter End Time (format: 2006-01-02 15:04:05) [optional]", "")
// var ipfile string
// if command == cons.LogParserCMD_MismatchIPs {
// ipfile = reader.Read("Enter IP File Path: ")
// }
var hbaConfigFile string
if command == cons.LogParserCMD_HBAUnusedLines || command == cons.LogParserCMD_All {
hbaConfigFile = ReadInput("Enter pg_hba.conf File Path", hbaConfigSuggestion)
}
l, err := NewLogParser(command, beginTime, endTime, prefix, logfile, hbaConfigFile)
if err != nil {
return nil, fmt.Errorf("Invalid input for logparser: %v", err)
}
return l, nil
}
func MustNewConfig() *Config {
config, err := NewConfig()
if err != nil {
fmt.Println("Can't create config")
fmt.Println(err)
os.Exit(1)
}
return config
}
// Add this helper type and methods for handling multiple string flags
type compareConfigFlag []string
func (s *compareConfigFlag) String() string {
return fmt.Sprintf("%v", *s)
}
func (s *compareConfigFlag) Set(value string) error {
if s == nil {
return fmt.Errorf("compareConfigFlag is nil")
}
if value == "" {
return fmt.Errorf("empty string is not allowed")
}
for _, v := range *s {
if v == value {
return fmt.Errorf("duplicate connection string: %s", value)
}
}
*s = append(*s, value)
return nil
}