-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmain.go
More file actions
360 lines (318 loc) · 10.5 KB
/
main.go
File metadata and controls
360 lines (318 loc) · 10.5 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
package main
import (
"context"
"crypto/tls"
"flag"
"fmt"
"net/http"
"net/url"
"os"
"time"
"github.com/xenov-x/csbot/config"
"github.com/xenov-x/csbot/logger"
"github.com/xenov-x/csbot/output"
"github.com/xenov-x/csbot/selector"
"github.com/xenov-x/csbot/workflow"
csclient "github.com/xenov-x/csrest"
)
func main() {
var (
workflowFile = flag.String("workflow", "workflow.yaml", "Path to workflow YAML file")
configFile = flag.String("config", "", "Path to configuration YAML file (optional)")
host = flag.String("host", "", "Cobalt Strike host (overrides config)")
port = flag.Int("port", 0, "Cobalt Strike API port (overrides config)")
username = flag.String("username", "", "Username for authentication (overrides config)")
password = flag.String("password", "", "Password for authentication (overrides config)")
insecure = flag.Bool("insecure", false, "Skip TLS verification (overrides config)")
logLevel = flag.String("log-level", "", "Log level: debug, info, warn, error (overrides config)")
outputFormat = flag.String("output", "text", "Output format: text, json, or csv")
outputFile = flag.String("output-file", "", "Write output to file instead of stdout")
dryRun = flag.Bool("dry-run", false, "Validate and show what would execute without running")
listBeacons = flag.Bool("list-beacons", false, "List all beacons and exit")
// Beacon list filters (only applicable with -list-beacons)
listBeaconsUser = flag.String("list-beacons-user", "", "Filter by username (partial match, requires -list-beacons)")
listBeaconsHostname = flag.String("list-beacons-hostname", "", "Filter by hostname (partial match, requires -list-beacons)")
listBeaconsAdmin = flag.Bool("list-beacons-admin", false, "Only show admin beacons (requires -list-beacons)")
listBeaconsAlive = flag.Bool("list-beacons-alive", false, "Only show alive beacons (requires -list-beacons)")
listBeaconsMinutes = flag.Int("list-beacons-minutes", 0, "Only show beacons checked in within last N minutes (requires -list-beacons)")
)
flag.Parse()
// Load configuration
cfg, err := config.LoadConfig(*configFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to load configuration: %v\n", err)
os.Exit(1)
}
// CLI flags override config file and environment variables
if *host != "" {
cfg.Server.Host = *host
}
if *port != 0 {
cfg.Server.Port = *port
}
if *username != "" {
cfg.Server.Username = *username
}
if *password != "" {
cfg.Server.Password = *password
}
if *insecure {
cfg.Server.Insecure = *insecure
}
if *logLevel != "" {
cfg.Logging.Level = *logLevel
}
// Validate configuration
if err := cfg.Validate(); err != nil {
fmt.Fprintf(os.Stderr, "Invalid configuration: %v\n", err)
os.Exit(1)
}
// Initialize logger
log, err := logger.New(cfg.Logging.Level, cfg.Logging.JSONFormat, cfg.Logging.File)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to initialize logger: %v\n", err)
os.Exit(1)
}
log.Info("Starting Cobalt Strike automation bot")
// Handle list-beacons flag early, before workflow loading
if *listBeacons {
log.Info("Listing beacons...")
// Create custom HTTP client with TLS config
transport := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: cfg.Server.Insecure,
},
}
// Configure proxy if specified
if cfg.Server.Proxy != "" {
proxyURL, err := url.Parse(cfg.Server.Proxy)
if err != nil {
log.Error("Invalid proxy URL: %v", err)
os.Exit(1)
}
transport.Proxy = http.ProxyURL(proxyURL)
log.Info("Using proxy: %s", cfg.Server.Proxy)
}
httpClient := &http.Client{
Timeout: time.Duration(cfg.Timeouts.HTTPTimeout) * time.Second,
Transport: transport,
}
// Create API client
client := csclient.NewClient(cfg.Server.Host, cfg.Server.Port)
client.SetHTTPClient(httpClient)
ctx := context.Background()
// Authenticate
log.Info("Authenticating as %s...", cfg.Server.Username)
_, err = client.Login(ctx, cfg.Server.Username, cfg.Server.Password, 3600000)
if err != nil {
log.Error("Authentication failed: %v", err)
os.Exit(1)
}
log.Info("Authentication successful")
// Build filter from flags
var filter *selector.BeaconFilter
if *listBeaconsUser != "" || *listBeaconsHostname != "" || *listBeaconsAdmin || *listBeaconsAlive || *listBeaconsMinutes > 0 {
filter = &selector.BeaconFilter{
User: *listBeaconsUser,
Hostname: *listBeaconsHostname,
AdminOnly: *listBeaconsAdmin,
AliveOnly: *listBeaconsAlive,
MinutesAgo: *listBeaconsMinutes,
}
}
// List beacons and exit
if err := selector.ListBeacons(ctx, client, filter); err != nil {
log.Error("Failed to list beacons: %v", err)
os.Exit(1)
}
os.Exit(0)
}
// Read workflow configuration
wf, err := workflow.LoadWorkflow(*workflowFile)
if err != nil {
log.Error("Failed to load workflow: %v", err)
os.Exit(1)
}
log.Info("Loaded workflow: %s", wf.Name)
// Create custom HTTP client with TLS config
transport := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: cfg.Server.Insecure,
},
}
// Configure proxy if specified
if cfg.Server.Proxy != "" {
proxyURL, err := url.Parse(cfg.Server.Proxy)
if err != nil {
log.Error("Invalid proxy URL: %v", err)
os.Exit(1)
}
transport.Proxy = http.ProxyURL(proxyURL)
log.Info("Using proxy: %s", cfg.Server.Proxy)
}
httpClient := &http.Client{
Timeout: time.Duration(cfg.Timeouts.HTTPTimeout) * time.Second,
Transport: transport,
}
// Create API client for authentication and beacon selection
client := csclient.NewClient(cfg.Server.Host, cfg.Server.Port)
client.SetHTTPClient(httpClient)
ctx := context.Background()
// Skip authentication in dry-run mode
if !*dryRun {
// Authenticate
log.Info("Authenticating as %s...", cfg.Server.Username)
_, err = client.Login(ctx, cfg.Server.Username, cfg.Server.Password, 3600000) // 1 hour
if err != nil {
log.Error("Authentication failed: %v", err)
os.Exit(1)
}
log.Info("Authentication successful")
} else {
log.Info("Skipping authentication in dry-run mode")
}
// Validate workflow (skip beacon check in dry-run mode)
log.Info("Validating workflow...")
var validatorClient *csclient.Client
if !*dryRun {
validatorClient = client
}
validator := workflow.NewValidator(validatorClient)
validationErrors := validator.Validate(ctx, wf)
hasErrors := false
for _, valErr := range validationErrors {
if valErr.Severity == "warning" {
log.Warn("[%s] %s", valErr.Type, valErr.Message)
} else {
log.Error("[%s] %s", valErr.Type, valErr.Message)
hasErrors = true
}
}
if hasErrors {
log.Error("Workflow validation failed with errors")
os.Exit(1)
}
if len(validationErrors) == 0 {
log.Info("Workflow validation passed")
} else {
log.Info("Workflow validation passed with warnings")
}
// If dry-run mode, show what would execute and exit
if *dryRun {
log.Info("=== DRY RUN MODE ===")
log.Info("Workflow would execute the following actions:")
fmt.Println()
for i, action := range wf.Actions {
fmt.Printf("[%d] %s (%s)\n", i+1, action.Name, action.Type)
if len(action.Parameters) > 0 {
fmt.Println(" Parameters:")
for key, val := range action.Parameters {
fmt.Printf(" - %s: %v\n", key, val)
}
}
if len(action.Conditions) > 0 {
fmt.Println(" Conditions:")
for _, cond := range action.Conditions {
fmt.Printf(" - %s %s '%s'\n", cond.Source, cond.Operator, cond.Value)
}
}
if len(action.OnSuccess) > 0 {
fmt.Printf(" On Success: %d actions\n", len(action.OnSuccess))
}
if len(action.OnFailure) > 0 {
fmt.Printf(" On Failure: %d actions\n", len(action.OnFailure))
}
fmt.Println()
}
if wf.Parallel {
log.Info("NOTE: Actions would execute in PARALLEL mode")
} else {
log.Info("NOTE: Actions would execute SEQUENTIALLY")
}
log.Info("Dry run complete. No actions were executed.")
os.Exit(0)
}
// If no beacon ID specified in workflow, check if one is needed
if wf.BeaconID == "" {
if workflow.WorkflowRequiresBeacon(wf) {
log.Info("No beacon ID specified in workflow, prompting for selection...")
beaconID, err := selector.SelectBeacon(ctx, client)
if err != nil {
log.Error("Beacon selection failed: %v", err)
os.Exit(1)
}
wf.BeaconID = beaconID
// Display beacon details
if err := selector.DisplayBeaconDetails(ctx, client, beaconID); err != nil {
log.Warn("Could not display beacon details: %v", err)
}
} else {
log.Info("Workflow contains only server-level actions, no beacon required")
}
} else {
log.Info("Using beacon ID from workflow: %s", wf.BeaconID)
}
// Create workflow executor
executor := workflow.NewExecutor(cfg.Server.Host, cfg.Server.Port, httpClient)
executor.SetLogger(log)
executor.SetTaskTimeout(time.Duration(cfg.Timeouts.TaskTimeout) * time.Second)
// Track execution time
workflowStartTime := time.Now()
// Execute workflow (pass already authenticated credentials)
err = executor.Execute(ctx, wf, cfg.Server.Username, cfg.Server.Password)
workflowEndTime := time.Now()
// Prepare output
var outputWriter *os.File
if *outputFile != "" {
outputWriter, err = os.Create(*outputFile)
if err != nil {
log.Error("Failed to create output file: %v", err)
os.Exit(1)
}
defer outputWriter.Close()
}
// Format and write output
var formatter *output.Formatter
if outputWriter != nil {
formatter = output.NewFormatter(output.Format(*outputFormat), outputWriter)
} else {
formatter = output.NewFormatter(output.Format(*outputFormat), os.Stdout)
}
// Convert executor results to output results
executorResults := executor.GetResults()
outputActions := make([]output.ActionResult, len(executorResults))
for i, r := range executorResults {
outputActions[i] = output.ActionResult{
Name: r.Name,
Type: r.Type,
StartTime: r.StartTime,
EndTime: r.EndTime,
Duration: r.Duration,
Success: r.Success,
Output: r.Output,
Error: r.Error,
}
}
result := &output.Result{
WorkflowName: wf.Name,
BeaconID: wf.BeaconID,
StartTime: workflowStartTime,
EndTime: workflowEndTime,
Duration: workflowEndTime.Sub(workflowStartTime),
Success: err == nil,
Actions: outputActions,
}
if err != nil {
result.Error = err.Error()
log.Error("Workflow execution failed: %v", err)
} else {
log.Info("Workflow completed successfully")
}
// Write formatted output
if fmtErr := formatter.WriteResult(result); fmtErr != nil {
log.Error("Failed to write output: %v", fmtErr)
}
if err != nil {
os.Exit(1)
}
}