This repository has been archived by the owner on May 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
3099 lines (3052 loc) · 112 KB
/
main.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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @author: its_a_feature_
// This code is to administer Mythic 2.2.4+ configurations
package main
import (
"bufio"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/binary"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"log"
"math/big"
"net"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"text/tabwriter"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/spf13/viper"
"github.com/streadway/amqp"
)
var mythicServices = []string{
"mythic_postgres",
"mythic_react",
"mythic_server",
"mythic_redis",
"mythic_nginx",
"mythic_rabbitmq",
"mythic_graphql",
"mythic_documentation",
"mythic_sync",
}
var mythicEnv = viper.New()
var mythicCliVersion = "0.0.8"
var buildArguments = []string{}
func stringInSlice(value string, list []string) bool {
for _, e := range list {
if e == value {
return true
}
}
return false
}
func removeExclusionsFromSlice(group string, suppliedList []string) []string {
// use the EXCLUDED_C2_PROFILES and EXCLUDED_PAYLOAD_TYPES variables to limit what we start
var exclusion_list []string
if group == "c2" {
exclusion_list = strings.Split(mythicEnv.GetString("EXCLUDED_C2_PROFILES"), ",")
} else if group == "payload" {
exclusion_list = strings.Split(mythicEnv.GetString("EXCLUDED_PAYLOAD_TYPES"), ",")
}
var final_list []string
for _, element := range suppliedList {
if !stringInSlice(element, exclusion_list) {
final_list = append(final_list, element)
} else {
fmt.Printf("[*] Skipping %s because it's in an exclusion list\n", element)
}
}
return final_list
}
func updateEnvironmentVariables(originalList []string, updates []string) []string {
var finalList []string
for _, entry := range originalList {
entryPieces := strings.Split(entry, "=")
found := false
for _, update := range updates {
updatePieces := strings.Split(update, "=")
if updatePieces[0] == entryPieces[0] {
// the current env vars has a key that we want to update, so don't include the old version
found = true
}
}
if !found {
finalList = append(finalList, entry)
}
}
for _, update := range updates {
finalList = append(finalList, update)
}
return finalList
}
func displayHelp() {
fmt.Println("mythic-cli usage ( v", mythicCliVersion, "):")
fmt.Println("*************************************************************")
fmt.Println("*** source code: https://github.com/MythicMeta/Mythic_CLI ***")
fmt.Println("*************************************************************")
fmt.Println(" help")
fmt.Println(" mythic {start|stop} [service name...]")
fmt.Println(" start | restart")
fmt.Println(" Stops and Starts all of Mythic - alias for 'mythic start'")
fmt.Println(" stop")
fmt.Println(" Stop all of Mythic - alias for 'mythic stop'")
fmt.Println(" c2 {start|stop|add|remove|list} [c2profile ...]")
fmt.Println(" The add/remove subcommands adjust the docker-compose file, not manipulate files on disk")
fmt.Println(" to manipulate files on disk, use 'install' and 'uninstall' commands")
fmt.Println(" payload {start|stop|add|remove|list} [payloadtype ...]")
fmt.Println(" The add/remove subcommands adjust the docker-compose file, not manipulate files on disk")
fmt.Println(" to manipulate files on disk, use 'install' and 'uninstall' commands")
fmt.Println(" config")
fmt.Println(" *no parameters will dump the entire config*")
fmt.Println(" get [varname ...]")
fmt.Println(" set <var name> <var value>")
fmt.Println(" payload (dump out remote payload configuration variables)")
fmt.Println(" c2 (dump out remote c2 configuration variables)")
fmt.Println(" database reset")
fmt.Println(" install ")
fmt.Println(" github <url> [branch name] [-f]")
fmt.Println(" folder <path to folder> [-f]")
fmt.Println(" -f forces the removal of the currently installed version and overwrites with the new, otherwise will prompt you")
fmt.Println(" * this command will manipulate files on disk and update docker-compose")
fmt.Println(" uninstall {name1 name2 name2 ...}")
fmt.Println(" (this command removes the payload or c2 profile from disk and updates docker-compose)")
fmt.Println(" status")
fmt.Println(" logs <container name>")
fmt.Println(" mythic_sync")
fmt.Println(" install github [url] [branch name]")
fmt.Println(" * if no url is provided, https://github.com/GhostManager/mythic_sync will be used")
fmt.Println(" install folder <path to folder>")
fmt.Println(" uninstall")
fmt.Println(" version")
fmt.Println(" test")
fmt.Println(" test connectivity to RabbitMQ and the Mythic UI")
}
func generateRandomPassword(pw_length int) string {
chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
var b strings.Builder
for i := 0; i < pw_length; i++ {
nBig, err := rand.Int(rand.Reader, big.NewInt(int64(len(chars))))
if err != nil {
log.Fatalf("[-] Failed to generate random number for password generation\n")
}
b.WriteRune(chars[nBig.Int64()])
}
return b.String()
}
func setMythicConfigDefaultValues() {
// nginx configuration
mythicEnv.SetDefault("nginx_port", 7443)
mythicEnv.SetDefault("nginx_host", "mythic_nginx")
mythicEnv.SetDefault("nginx_bind_localhost_only", false)
mythicEnv.SetDefault("nginx_use_ssl", true)
// mythic react UI configuration
mythicEnv.SetDefault("mythic_react_host", "mythic_react")
mythicEnv.SetDefault("mythic_react_port", 3000)
mythicEnv.SetDefault("mythic_react_bind_localhost_only", true)
// mythic server configuration
mythicEnv.SetDefault("documentation_host", "mythic_documentation")
mythicEnv.SetDefault("documentation_port", 8090)
mythicEnv.SetDefault("documentation_bind_localhost_only", true)
mythicEnv.SetDefault("mythic_debug", false)
mythicEnv.SetDefault("mythic_server_port", 17443)
mythicEnv.SetDefault("mythic_server_host", "mythic_server")
mythicEnv.SetDefault("mythic_server_bind_localhost_only", true)
mythicEnv.SetDefault("mythic_server_dynamic_ports", "7000-7010")
// postgres configuration
mythicEnv.SetDefault("postgres_host", "mythic_postgres")
mythicEnv.SetDefault("postgres_port", 5432)
mythicEnv.SetDefault("postgres_bind_localhost_only", true)
mythicEnv.SetDefault("postgres_db", "mythic_db")
mythicEnv.SetDefault("postgres_user", "mythic_user")
mythicEnv.SetDefault("postgres_password", generateRandomPassword(30))
// rabbitmq configuration
mythicEnv.SetDefault("rabbitmq_host", "mythic_rabbitmq")
mythicEnv.SetDefault("rabbitmq_port", 5672)
mythicEnv.SetDefault("rabbitmq_bind_localhost_only", true)
mythicEnv.SetDefault("rabbitmq_user", "mythic_user")
mythicEnv.SetDefault("rabbitmq_password", generateRandomPassword(30))
mythicEnv.SetDefault("rabbitmq_vhost", "mythic_vhost")
// jwt configuration
mythicEnv.SetDefault("jwt_secret", generateRandomPassword(30))
// hasura configuration
mythicEnv.SetDefault("hasura_host", "mythic_graphql")
mythicEnv.SetDefault("hasura_port", 8080)
mythicEnv.SetDefault("hasura_bind_localhost_only", true)
mythicEnv.SetDefault("hasura_secret", generateRandomPassword(30))
// redis configuration
mythicEnv.SetDefault("redis_port", 6379)
mythicEnv.SetDefault("redis_host", "mythic_redis")
mythicEnv.SetDefault("redis_bind_localhost_only", true)
// docker-compose configuration
mythicEnv.SetDefault("COMPOSE_PROJECT_NAME", "mythic")
mythicEnv.SetDefault("REBUILD_ON_START", true)
// Mythic instance configuration
mythicEnv.SetDefault("mythic_admin_user", "mythic_admin")
mythicEnv.SetDefault("mythic_admin_password", generateRandomPassword(30))
mythicEnv.SetDefault("default_operation_name", "Operation Chimera")
mythicEnv.SetDefault("allowed_ip_blocks", "0.0.0.0/0")
mythicEnv.SetDefault("server_header", "nginx 1.2")
mythicEnv.SetDefault("web_log_size", 1024000)
mythicEnv.SetDefault("web_keep_logs", false)
mythicEnv.SetDefault("siem_log_name", "")
mythicEnv.SetDefault("excluded_payload_types", "")
mythicEnv.SetDefault("excluded_c2_profiles", "")
// PayloadType / C2 / Translator configuration
mythicEnv.SetDefault("mythic_environment", "production")
}
func parseMythicEnvironmentVariables() {
setMythicConfigDefaultValues()
mythicEnv.SetConfigName(".env")
mythicEnv.SetConfigType("env")
mythicEnv.AddConfigPath(getCwdFromExe())
mythicEnv.AutomaticEnv()
if !fileExists(filepath.Join(getCwdFromExe(), ".env")) {
_, err := os.Create(filepath.Join(getCwdFromExe(), ".env"))
if err != nil {
log.Fatalf("[-] .env doesn't exist and couldn't be created")
}
}
if err := mythicEnv.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Fatalf("[-] Error while reading in .env file: %s", err)
} else {
log.Fatalf("[-]Error while parsing .env file: %s", err)
}
}
portChecks := map[string][]string{
"MYTHIC_SERVER_HOST": {
"MYTHIC_SERVER_PORT",
"mythic_server",
},
"POSTGRES_HOST": {
"POSTGRES_PORT",
"mythic_postgres",
},
"HASURA_HOST": {
"HASURA_PORT",
"mythic_graphql",
},
"RABBITMQ_HOST": {
"RABBITMQ_PORT",
"mythic_rabbitmq",
},
"DOCUMENTATION_HOST": {
"DOCUMENTATION_PORT",
"mythic_documentation",
},
"NGINX_HOST": {
"NGINX_PORT",
"mythic_nginx",
},
"REDIS_HOST": {
"REDIS_PORT",
"mythic_redis",
},
"MYTHIC_REACT_HOST": {
"MYTHIC_REACT_PORT",
"mythic_react",
},
}
for key, val := range portChecks {
if mythicEnv.GetString(key) == "127.0.0.1" {
mythicEnv.Set(key, val[1])
}
}
writeMythicEnvironmentVariables()
}
func writeMythicEnvironmentVariables() {
c := mythicEnv.AllSettings()
// to make it easier to read and look at, get all the keys, sort them, and display variables in order
keys := make([]string, 0, len(c))
for k := range c {
keys = append(keys, k)
}
sort.Strings(keys)
f, err := os.Create(filepath.Join(getCwdFromExe(), ".env"))
if err != nil {
log.Fatalf("[-] Error writing out environment!\n%v", err)
}
defer f.Close()
for _, key := range keys {
if len(mythicEnv.GetString(key)) == 0 {
_, err = f.WriteString(fmt.Sprintf("%s=\n", strings.ToUpper(key)))
} else {
_, err = f.WriteString(fmt.Sprintf("%s=\"%s\"\n", strings.ToUpper(key), mythicEnv.GetString(key)))
}
if err != nil {
log.Fatalf("[-] Failed to write out environment!\n%v", err)
}
}
return
}
func printShellCommands(variables map[string]string) {
fmt.Printf("\n[*] Shell commands for Linux\n")
for key, value := range variables {
fmt.Printf("export %s=\"%s\"\n", strings.ToUpper(key), value)
}
fmt.Printf("export MYTHIC_NAME=\"agent name here\"\n")
fmt.Printf("\n[*] Shell commands for Linux on one line\n")
var output []string
for key, value := range variables {
output = append(output, fmt.Sprintf("export %s=\"%s\"", strings.ToUpper(key), value))
}
output = append(output, fmt.Sprintf("export MYTHIC_NAME=\"agent name here\""))
fmt.Printf(strings.Join(output[:], "; "))
fmt.Printf("\n\n[*] PowerShell commands for Windows\n")
for key, value := range variables {
fmt.Printf("$env:%s=\"%s\"\n", strings.ToUpper(key), value)
}
fmt.Printf("$env:MYTHIC_NAME=\"agent name here\"\n")
var winPowerShellOutput []string
fmt.Printf("\n[*] PowerShell commands for Windows on one line\n")
for key, value := range variables {
winPowerShellOutput = append(winPowerShellOutput, fmt.Sprintf("$env:%s=\"%s\"", strings.ToUpper(key), value))
}
winPowerShellOutput = append(winPowerShellOutput, fmt.Sprintf("$env:MYTHIC_NAME=\"agent name here\""))
fmt.Printf(strings.Join(winPowerShellOutput[:], " && "))
fmt.Printf("\n\n[*] CMD commands for Windows\n")
for key, value := range variables {
fmt.Printf("SET %s=\"%s\"\n", strings.ToUpper(key), value)
}
fmt.Printf("SET MYTHIC_NAME=\"agent name here\"\n")
var winOutput []string
fmt.Printf("\n[*] Shell commands for Windows on one line\n")
for key, value := range variables {
winOutput = append(winOutput, fmt.Sprintf("SET %s=\"%s\"", strings.ToUpper(key), value))
}
winOutput = append(winOutput, fmt.Sprintf("SET MYTHIC_NAME=\"agent name here\""))
fmt.Printf(strings.Join(winOutput[:], " && "))
fmt.Printf("\n\n")
}
func env(args []string) {
if len(args) == 0 {
// we want to just get all of the environment variables that mythic uses
c := mythicEnv.AllSettings()
// to make it easier to read and look at, get all the keys, sort them, and display variables in order
keys := make([]string, 0, len(c))
for k := range c {
keys = append(keys, k)
}
sort.Strings(keys)
for _, key := range keys {
fmt.Println(strings.ToUpper(key), "=", mythicEnv.Get(key))
}
return
}
switch args[0] {
case "get":
if len(args) == 1 {
log.Fatal("[-] Must specify name of variable to get")
}
for i := 1; i < len(args[1:])+1; i++ {
val := mythicEnv.Get(args[i])
fmt.Println(strings.ToUpper(args[i]), "=", val)
}
case "set":
if len(args) != 3 {
log.Fatalf("[-] Must supply config name and config value")
}
if strings.ToLower(args[2]) == "true" {
mythicEnv.Set(args[1], true)
} else if strings.ToLower(args[2]) == "false" {
mythicEnv.Set(args[1], false)
} else {
mythicEnv.Set(args[1], args[2])
}
mythicEnv.Get(args[1])
writeMythicEnvironmentVariables()
fmt.Printf("[+] Successfully updated configuration in .env\n")
case "payload":
fixRabbitMqLocalHost := false
// get all of the configuration variables for a remote payload type
fmt.Printf("\n[*] When using a Payload Type that runs outside of this Mythic instance (i.e. remote Computer, remote VM, etc), you need to pass in configuration information\n")
fmt.Printf(" Use these environment variables for your remote Payload Type to make sure it can properly connect to Mythic\n")
variables := map[string]string{
"MYTHIC_USERNAME": mythicEnv.GetString("RABBITMQ_USER"),
"MYTHIC_PASSWORD": mythicEnv.GetString("RABBITMQ_PASSWORD"),
"MYTHIC_VIRTUAL_HOST": mythicEnv.GetString("RABBITMQ_VHOST"),
"MYTHIC_HOST": mythicEnv.GetString("RABBITMQ_HOST"),
"MYTHIC_PORT": mythicEnv.GetString("RABBITMQ_PORT"),
}
printShellCommands(variables)
if mythicEnv.GetString("RABBITMQ_HOST") == "mythic_rabbitmq" || mythicEnv.GetString("RABBITMQ_HOST") == "127.0.0.1" {
if !mythicEnv.GetBool("rabbitmq_bind_localhost_only") {
fmt.Printf("[-] Environment variable, MYTHIC_HOST, is not set to a public ip\n")
fmt.Printf(" Make sure to update it to the correct routable IP address or add an appropriate hostname to your DNS in your remote configuration\n")
}
}
if mythicEnv.GetBool("rabbitmq_bind_localhost_only") {
fmt.Printf("[-] Service, mythic_rabbitmq, is currently bound to 127.0.0.1, so a remote agent will be unable to connect to it\n")
fmt.Printf(" To fix this, set the \"RABBITMQ_BIND_LOCALHOST_ONLY\" variable to \"false\" and restart mythic\n")
fixRabbitMqLocalHost = true
}
if fixRabbitMqLocalHost {
autoFix := askConfirm("\nDo you want the service to be externally available and Mythic restarted?")
if autoFix {
mythicEnv.Set("rabbitmq_bind_localhost_only", false)
writeMythicEnvironmentVariables()
startStop("start", "mythic", []string{})
env(args)
}
}
case "c2":
fmt.Printf("\n[*] When using a C2 Profile that runs outside of this Mythic instance (i.e. remote Computer, remote VM, etc), you need to pass in configuration information\n")
fmt.Printf(" Use these environment variables for your remote C2 Profile to make sure it can properly connect to Mythic\n")
fixRabbitMqLocalHost := false
fixMythicServerLocalHost := false
variables := map[string]string{
"MYTHIC_USERNAME": mythicEnv.GetString("RABBITMQ_USER"),
"MYTHIC_PASSWORD": mythicEnv.GetString("RABBITMQ_PASSWORD"),
"MYTHIC_VIRTUAL_HOST": mythicEnv.GetString("RABBITMQ_VHOST"),
"MYTHIC_HOST": mythicEnv.GetString("RABBITMQ_HOST"),
"MYTHIC_PORT": mythicEnv.GetString("RABBITMQ_PORT"),
"MYTHIC_ADDRESS": "http://" + mythicEnv.GetString("MYTHIC_SERVER_HOST") + ":" + mythicEnv.GetString("MYTHIC_SERVER_PORT") + "/api/v1.4/agent_message",
"MYTHIC_WEBSOCKET": "ws://" + mythicEnv.GetString("MYTHIC_SERVER_HOST") + ":" + mythicEnv.GetString("MYTHIC_SERVER_PORT") + "/ws/agent_message",
}
printShellCommands(variables)
if mythicEnv.GetString("RABBITMQ_HOST") == "mythic_rabbitmq" || mythicEnv.GetString("RABBITMQ_HOST") == "127.0.0.1" {
if !mythicEnv.GetBool("rabbitmq_bind_localhost_only") {
fmt.Printf("[-] Environment variable, MYTHIC_HOST, is not set to a public ip\n")
fmt.Printf(" Make sure to update it to the correct routable IP address or add an appropriate hostname to your DNS in your remote configuration\n")
}
}
if mythicEnv.GetString("MYTHIC_SERVER_HOST") == "mythic_server" || mythicEnv.GetString("MYTHIC_SERVER_HOST") == "127.0.0.1" {
if !mythicEnv.GetBool("mythic_server_bind_localhost_only") {
fmt.Printf("[-] Environment variables, MYTHIC_ADDRESS and MYTHIC_WEBSOCKET, do not include public IP addresses\n")
fmt.Printf(" Make sure to update it to the correct routable IP address or add an appropriate hostname to your DNS in your remote configuration\n")
}
}
if mythicEnv.GetBool("rabbitmq_bind_localhost_only") {
fmt.Printf("[-] Service, mythic_rabbitmq, is currently listening on 127.0.0.1, so a remote agent will be unable to connect to it\n")
fmt.Printf(" To fix this, set the \"RABBITMQ_BIND_LOCALHOST_ONLY\" variable to \"false\" and restart mythic\n")
fixRabbitMqLocalHost = true
}
if mythicEnv.GetBool("mythic_server_bind_localhost_only") {
fmt.Printf("[-] Service, mythic_server, is currently listening on 127.0.0.1, so a remote agent will be unable to connect to it to send C2 traffic\n")
fmt.Printf(" To fix this, set the \"MYTHIC_SERVER_BIND_LOCALHOST_ONLY\" variable to \"false\" and restart mythic\n")
fixMythicServerLocalHost = true
}
if fixRabbitMqLocalHost || fixMythicServerLocalHost {
autoFix := askConfirm("\nDo you want service to be externally available and Mythic restarted?")
if autoFix {
mythicEnv.Set("rabbitmq_bind_localhost_only", false)
mythicEnv.Set("mythic_server_bind_localhost_only", false)
writeMythicEnvironmentVariables()
startStop("start", "mythic", []string{})
env(args)
}
}
default:
fmt.Println("[-] Unknown env subcommand:", args[0])
}
}
func isServiceRunning(service string) bool {
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
log.Fatalf("[-] Failed to get client connection to Docker: %v", err)
}
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{
All: true,
})
if err != nil {
log.Fatalf("[-] Failed to get container list from Docker: %v", err)
}
if len(containers) > 0 {
for _, container := range containers {
if container.Labels["name"] == strings.ToLower(service) {
return true
}
}
}
return false
}
func getElementsOnDisk(group string) []string {
var path string
if group == "payload" {
path = "Payload_Types"
} else if group == "c2" {
path = "C2_Profiles"
} else {
log.Fatalf("[-] Unknown group category: %s\n", group)
}
files, err := ioutil.ReadDir(filepath.Join(getCwdFromExe(), path))
if err != nil {
log.Fatalf("[-] Failed to list contents of %s folder\n", path)
}
var agentsOnDisk []string
for _, f := range files {
if f.IsDir() {
agentsOnDisk = append(agentsOnDisk, f.Name())
}
}
return agentsOnDisk
}
func status() {
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
log.Fatalf("[-] Failed to get client in status check: %v", err)
}
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{
All: true,
})
if err != nil {
log.Fatalf("[-] Failed to get container list: %v", err)
}
printMythicConnectionInfo()
if len(containers) > 0 {
w := new(tabwriter.Writer)
w.Init(os.Stdout, 0, 8, 2, '\t', 0)
mythic_services := []string{}
c2_services := []string{}
payload_services := []string{}
for _, container := range containers {
if container.Labels["name"] == "" {
continue
}
portRanges := []uint16{}
portRangeMaps := []string{}
info := fmt.Sprintf("%s\t%s\t%s\t", container.Labels["name"], container.State, container.Status)
if len(container.Ports) > 0 {
for _, port := range container.Ports {
if port.PublicPort > 0 {
if port.PrivatePort == port.PublicPort && port.IP == "0.0.0.0" {
portRanges = append(portRanges, port.PrivatePort)
} else {
portRangeMaps = append(portRangeMaps, fmt.Sprintf("%d/%s -> %s:%d", port.PrivatePort, port.Type, port.IP, port.PublicPort))
}
}
}
if len(portRanges) > 0 {
sort.Slice(portRanges, func(i, j int) bool { return portRanges[i] < portRanges[j] })
}
portString := strings.Join(portRangeMaps[:], ", ")
var stringPortRanges []string
for _, val := range portRanges {
stringPortRanges = append(stringPortRanges, fmt.Sprintf("%d", val))
}
if len(stringPortRanges) > 0 && len(portString) > 0 {
portString = portString + ", "
}
portString = portString + strings.Join(stringPortRanges[:], ", ")
info = info + portString
}
if stringInSlice(container.Image, mythicServices) {
mythic_services = append(mythic_services, info)
} else {
payloadAbsPath, err := filepath.Abs(filepath.Join(getCwdFromExe(), "Payload_Types"))
if err != nil {
fmt.Printf("[-] failed to get the absolute path to the Payload_Types folder")
continue
}
c2AbsPath, err := filepath.Abs(filepath.Join(getCwdFromExe(), "C2_Profiles"))
if err != nil {
fmt.Printf("[-] failed to get the absolute path to the Payload_Types folder")
continue
}
for _, mnt := range container.Mounts {
if strings.HasPrefix(mnt.Source, payloadAbsPath) {
payload_services = append(payload_services, info)
} else if strings.HasPrefix(mnt.Source, c2AbsPath) {
c2_services = append(c2_services, info)
}
}
}
}
fmt.Printf("Mythic Main Services:\n")
fmt.Fprintln(w, "NAME\tSTATE\tSTATUS\tPORTS")
for _, line := range mythic_services {
fmt.Fprintln(w, line)
}
w.Flush()
fmt.Printf("\nPayload Type Services:\n")
fmt.Fprintln(w, "NAME\tSTATE\tSTATUS\tPORTS")
for _, line := range payload_services {
fmt.Fprintln(w, line)
}
w.Flush()
if len(payload_services) == 0 {
containerList, err := getAllGroupNames("payload")
if err != nil {
log.Fatalf("[-] Failed to get all payload services: %v\n", err)
}
if len(containerList) > 0 {
// there are c2 containers in the docker file
containerTaskedToRunList := removeExclusionsFromSlice("payload", containerList)
if len(containerTaskedToRunList) > 0 {
// no containers are running, but there are ones that should be
fmt.Printf("[-] No Payload Type containers are running, but the following should be running:\n %v\n", containerTaskedToRunList)
fmt.Printf(" Check the container status with \"sudo ./mythic-cli logs [container name]\" to check for errors\n")
fmt.Printf(" To list all available C2_Profiles on disk and in docker-compose, run \"sudo ./mythic-cli c2 list\"\n")
} else {
// no containers are running and all available ones within the docker-compose file are excluded
fmt.Printf("[*] All available Payload Type containers are included in an exclusion list!\n")
}
} else {
// no containers are running and there are none in the docker-compose file
files, err := ioutil.ReadDir(filepath.Join(getCwdFromExe(), "Payload_Types"))
if err != nil {
log.Fatalf("[-] Failed to list contents of %s folder\n", "Payload_Types")
}
var agentsOnDisk []string
for _, f := range files {
if f.IsDir() {
agentsOnDisk = append(agentsOnDisk, f.Name())
}
}
if len(agentsOnDisk) > 0 {
fmt.Printf("[*] There are no Payload Type containers installed; however, some do exist in the Payload_Types folder\n")
fmt.Printf(" To install from the Payload_Types folder, run \"sudo ./mythic-cli payload add [agent name]\"\n")
fmt.Printf(" To list all available Payload_Types on disk and in docker-compose, run \"sudo ./mythic-cli payload list\"\n")
} else {
fmt.Printf("[*] There are no Payload Type containers installed\n")
fmt.Printf(" To install one, use \"sudo ./mythic-cli install github <url>\"\n")
fmt.Printf(" Agents can be found at: https://github.com/MythicAgents\n")
}
}
}
fmt.Printf("\nC2 Profile Services:\n")
fmt.Fprintln(w, "NAME\tSTATE\tSTATUS\tPORTS")
for _, line := range c2_services {
fmt.Fprintln(w, line)
}
w.Flush()
if len(c2_services) == 0 {
// no c2 containers are running, check to see if any are even installed
containerList, err := getAllGroupNames("c2")
if err != nil {
log.Fatalf("[-] Failed to get all c2 services: %v\n", err)
}
if len(containerList) > 0 {
// there are c2 containers in the docker file
containerTaskedToRunList := removeExclusionsFromSlice("c2", containerList)
if len(containerTaskedToRunList) > 0 {
// no containers are running, but there are ones that should be
fmt.Printf("[-] No C2 Profile containers are running, but the following should be running:\n %v\n", containerTaskedToRunList)
fmt.Printf(" Check the container status with \"sudo ./mythic-cli logs [container name]\" to check for errors\n")
} else {
// no containers are running and all available ones within the docker-compose file are excluded
fmt.Printf("[*] All available C2 Profile containers are included in an exclusion list!\n")
}
} else {
// no containers are running and there are none in the docker-compose file
files, err := ioutil.ReadDir(filepath.Join(getCwdFromExe(), "C2_Profiles"))
if err != nil {
log.Fatalf("[-] Failed to list contents of %s folder\n", "C2_Profiles")
}
var agentsOnDisk []string
for _, f := range files {
if f.IsDir() {
agentsOnDisk = append(agentsOnDisk, f.Name())
}
}
if len(agentsOnDisk) > 0 {
fmt.Printf("[*] There are no C2 Profile containers installed; however, some do exist in the C2_Profiles folder\n")
fmt.Printf(" To install from the C2_Profiles folder, run \"sudo ./mythic-cli c2 add [profile name]\"\n")
} else {
fmt.Printf("[*] There are no C2 Profile containers installed\n")
fmt.Printf(" To install one, use \"sudo ./mythic-cli install github <url>\"\n")
fmt.Printf(" C2 Profiles can be found at: https://github.com/MythicC2Profiles\n")
}
}
}
} else {
fmt.Println("There are no containers running")
}
if mythicEnv.GetString("RABBITMQ_HOST") == "mythic_rabbitmq" && mythicEnv.GetBool("rabbitmq_bind_localhost_only") {
fmt.Printf("\n[*] RabbitMQ is currently listening on localhost. If you have a remote PayloadType or C2Profile, they will be unable to connect")
fmt.Printf("\n Use 'sudo ./mythic-cli config set rabbitmq_bind_localhost_only false' and restart mythic ('sudo ./mythic-cli mythic start') to change this\n")
}
fmt.Printf("[*] If you are using a remote PayloadType or C2Profile, they will need certain environment variables to properly connect to Mythic.\n")
fmt.Printf(" Use 'sudo ./mythic-cli config payload' or 'sudo ./mythic-cli config c2' for easy-to-use configs for these services.\n")
}
func logs(containerName string) {
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
log.Fatalf("Failed to get client in logs: %v", err)
}
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
if err != nil {
log.Fatalf("Failed to get container list: %v", err)
}
if len(containers) > 0 {
for _, container := range containers {
if container.Labels["name"] == containerName {
reader, err := cli.ContainerLogs(context.Background(), container.ID, types.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
Tail: "500",
})
if err != nil {
log.Fatalf("Failed to get container logs: %v", err)
}
defer reader.Close()
// awesome post about the leading 8 payload/header bytes: https://medium.com/@dhanushgopinath/reading-docker-container-logs-with-golang-docker-engine-api-702233fac044
p := make([]byte, 8)
_, err = reader.Read(p)
for err == nil {
content := make([]byte, binary.BigEndian.Uint32(p[4:]))
reader.Read(content)
fmt.Printf("%s", content)
_, err = reader.Read(p)
}
}
}
} else {
fmt.Println("Failed to find that container")
}
}
func getMythicEnvList() []string {
env := mythicEnv.AllSettings()
var envList []string
for key := range env {
val := mythicEnv.GetString(key)
if val != "" {
// prevent trying to append arrays or dictionaries to our environment list
//fmt.Println(strings.ToUpper(key), val)
envList = append(envList, strings.ToUpper(key)+"="+val)
}
}
envList = append(envList, os.Environ()...)
return envList
}
func runDockerCompose(args []string) error {
path, err := exec.LookPath("docker-compose")
if err != nil {
path, err = exec.LookPath("docker")
if err != nil {
log.Fatalf("[-] docker-compose and docker are not installed or available in the current PATH")
} else {
// adjust the current args for docker compose subcommand
args = append([]string{"compose"}, args...)
}
}
exe, err := os.Executable()
if err != nil {
log.Fatalf("[-] Failed to get path to current executable")
}
exePath := filepath.Dir(exe)
command := exec.Command(path, args...)
command.Dir = exePath
command.Env = getMythicEnvList()
stdout, err := command.StdoutPipe()
if err != nil {
log.Fatalf("[-] Failed to get stdout pipe for running docker-compose")
}
stderr, err := command.StderrPipe()
if err != nil {
log.Fatalf("[-] Failed to get stderr pipe for running docker-compose")
}
stdoutScanner := bufio.NewScanner(stdout)
stderrScanner := bufio.NewScanner(stderr)
go func() {
for stdoutScanner.Scan() {
fmt.Printf("%s\n", stdoutScanner.Text())
}
}()
go func() {
for stderrScanner.Scan() {
fmt.Printf("%s\n", stderrScanner.Text())
}
}()
err = command.Start()
if err != nil {
log.Fatalf("[-] Error trying to start docker-compose: %v\n", err)
}
err = command.Wait()
if err != nil {
fmt.Printf("[-] Error from docker-compose: %v\n", err)
return err
}
return nil
}
func getCwdFromExe() string {
exe, err := os.Executable()
if err != nil {
log.Fatalf("[-] Failed to get path to current executable")
}
return filepath.Dir(exe)
}
func runGitClone(args []string) error {
path, err := exec.LookPath("git")
if err != nil {
fmt.Printf("[-] git is not installed or not available in the current PATH variable")
return err
}
exe, err := os.Executable()
if err != nil {
fmt.Printf("[-] Failed to get path to current executable")
return err
}
exePath := filepath.Dir(exe)
// git -c http.sslVerify=false clone --recurse-submodules --single-branch --branch $2 $1 temp
command := exec.Command(path, args...)
command.Dir = exePath
command.Env = getMythicEnvList()
stdout, err := command.StdoutPipe()
if err != nil {
fmt.Printf("[-] Failed to get stdout pipe for running git")
return err
}
stderr, err := command.StderrPipe()
if err != nil {
fmt.Printf("[-] Failed to get stderr pipe for running git")
return err
}
stdoutScanner := bufio.NewScanner(stdout)
stderrScanner := bufio.NewScanner(stderr)
go func() {
for stdoutScanner.Scan() {
fmt.Printf("%s\n", stdoutScanner.Text())
}
}()
go func() {
for stderrScanner.Scan() {
fmt.Printf("%s\n", stderrScanner.Text())
}
}()
err = command.Start()
if err != nil {
fmt.Printf("[-] Error trying to start git: %v\n", err)
return err
}
err = command.Wait()
if err != nil {
fmt.Printf("[-] Error trying to run git: %v\n", err)
return err
}
return nil
}
func getAllGroupNames(group string) ([]string, error) {
// given a group of {c2|payload}, get all of them that exist within the loaded config
groupNameConfig := viper.New()
groupNameConfig.SetConfigName("docker-compose")
groupNameConfig.SetConfigType("yaml")
groupNameConfig.AddConfigPath(getCwdFromExe())
if err := groupNameConfig.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
fmt.Printf("[-] Error while reading in docker-compose file: %s", err)
return []string{}, err
} else {
fmt.Printf("[-] Error while parsing docker-compose file: %s", err)
return []string{}, err
}
}
servicesSub := groupNameConfig.Sub("services")
services := servicesSub.AllSettings()
var absPath string
var err error
if group == "c2" {
absPath, err = filepath.Abs(filepath.Join(getCwdFromExe(), "C2_Profiles"))
if err != nil {
fmt.Printf("[-] failed to get the absolute path to the C2_Profiles folder")
return []string{}, err
}
} else if group == "payload" {
absPath, err = filepath.Abs(filepath.Join(getCwdFromExe(), "Payload_Types"))
if err != nil {
fmt.Printf("[-] failed to get the absolute path to the C2_Profiles folder")
return []string{}, err
}
}
var containerList []string
for container := range services {
build := servicesSub.GetString(container + ".build.context")
if build == "" {
build = servicesSub.GetString(container + ".build")
if build == "" {
log.Fatalf("[-] Failed to find the build path for %s\n", container)
}
}
buildAbsPath, err := filepath.Abs(build)
if err != nil {
fmt.Printf("[-] failed to get the absolute path to the container's docker file")
continue
}
if group == "mythic" {
if stringInSlice(container, mythicServices) {
containerList = append(containerList, container)
}
} else {
if strings.HasPrefix(buildAbsPath, absPath) {
// the service we're looking at has a build path that's a child of our folder, it should be a service
containerList = append(containerList, container)
}
}
}
if group == "mythic" {
// need to see about adding services back in if they were for remote hosts before
for _, service := range mythicServices {
if !stringInSlice(service, containerList) {
// service is a mythic service, but it's not in our current container list (i.e. not in docker-compose)
switch service {
case "mythic_react":
if mythicEnv.GetString("MYTHIC_REACT_HOST") == "127.0.0.1" || mythicEnv.GetString("MYTHIC_REACT_HOST") == "mythic_react" {
containerList = append(containerList, service)
}
case "mythic_nginx":
if mythicEnv.GetString("MYTHIC_NGINX_HOST") == "127.0.0.1" || mythicEnv.GetString("MYTHIC_NGINX_HOST") == "mythic_nginx" {
containerList = append(containerList, service)
}
case "mythic_rabbitmq":
if mythicEnv.GetString("RABBITMQ_HOST") == "127.0.0.1" || mythicEnv.GetString("RABBITMQ_HOST") == "mythic_rabbitmq" {
containerList = append(containerList, service)
}
case "mythic_redis":
if mythicEnv.GetString("REDIS_HOST") == "127.0.0.1" || mythicEnv.GetString("REDIS_HOST") == "mythic_redis" {
containerList = append(containerList, service)
}
case "mythic_server":
if mythicEnv.GetString("MYTHIC_SERVER_HOST") == "127.0.0.1" || mythicEnv.GetString("MYTHIC_SERVER_HOST") == "mythic_server" {
containerList = append(containerList, service)
}
case "mythic_postgres":
if mythicEnv.GetString("POSTGRES_HOST") == "127.0.0.1" || mythicEnv.GetString("POSTGRES_HOST") == "mythic_postgres" {
containerList = append(containerList, service)
}
}
}
}
}
return containerList, nil
}
func imageExists(containerName string) bool {
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
log.Fatalf("Failed to get client in logs: %v", err)
}
desiredImage := fmt.Sprintf("%v:latest", strings.ToLower(containerName))
images, err := cli.ImageList(context.Background(), types.ImageListOptions{All: true})
if err != nil {
log.Fatalf("Failed to get container list: %v", err)
}
for _, image := range images {
for _, name := range image.RepoTags {
if name == desiredImage {
return true
}
}
}
return false
}
func startStop(action string, group string, containerNameOriginals []string) error {
// group is ["c2", "payload", "mythic"]
// contianerName is a specific container or empty for all within a group
containerNames := make([]string, 0)
for _, val := range containerNameOriginals {
containerNames = append(containerNames, strings.ToLower(val))
}
switch group {
case "mythic":
// we're looking at the main mythic services here
if action == "start" {
writeMythicEnvironmentVariables()
fmt.Printf("[+] Successfully updated configuration in .env\n")
if len(containerNames) == 0 {
if mythicEnv.GetBool("REBUILD_ON_START") {
runDockerCompose([]string{"down", "--volumes", "--remove-orphans"})
} else {
runDockerCompose([]string{"down", "--volumes"})
}
err := checkPorts()
if err != nil {
return err
}
c2ContainerList, err := getAllGroupNames("c2")
if err != nil {
fmt.Printf("[-] Failed to get all c2 services: %v\n", err)
return err
}
payloadContainerList, err := getAllGroupNames("payload")
if err != nil {
fmt.Printf("[-] Failed to get all payload services: %v\n", err)
return err
}
mythicContainerList, err := getAllGroupNames("mythic")
if err != nil {
fmt.Printf("[-] Failed to enumerate Mythic services: %v\n", err)
return err
}
addRemoveDockerComposeEntries("add", "c2", c2ContainerList, make(map[string]interface{}), false, true)