Started rewriting JSON task to custom binary structure. Parsed and serialized task object into seq[byte]

This commit is contained in:
Jakob Friedl
2025-07-18 14:24:07 +02:00
parent 310ad82cc5
commit 5825ec91a1
28 changed files with 926 additions and 732 deletions

View File

@@ -2,7 +2,7 @@ import terminal, strformat, strutils, sequtils, tables, json, times, base64, sys
import ../[utils, globals]
import ../db/database
import ../../types
import ../../common/types
# Utility functions
proc add*(cq: Conquest, agent: Agent) =
@@ -36,27 +36,27 @@ proc register*(agent: Agent): bool =
return true
proc getTasks*(listener, agent: string): JsonNode =
proc getTasks*(listener, agent: string): seq[seq[byte]] =
{.cast(gcsafe).}:
# Check if listener exists
if not cq.dbListenerExists(listener.toUpperAscii):
cq.writeLine(fgRed, styleBright, fmt"[-] Task-retrieval request made to non-existent listener: {listener}.", "\n")
return nil
raise newException(ValueError, "Invalid listener.")
# Check if agent exists
if not cq.dbAgentExists(agent.toUpperAscii):
cq.writeLine(fgRed, styleBright, fmt"[-] Task-retrieval request made to non-existent agent: {agent}.", "\n")
return nil
raise newException(ValueError, "Invalid agent.")
# Update the last check-in date for the accessed agent
cq.agents[agent.toUpperAscii].latestCheckin = now()
# if not cq.dbUpdateCheckin(agent.toUpperAscii, now().format("dd-MM-yyyy HH:mm:ss")):
# return nil
# Return tasks in JSON format
return %cq.agents[agent.toUpperAscii].tasks
# Return tasks
return cq.agents[agent.toUpperAscii].tasks
proc handleResult*(listener, agent, task: string, taskResult: TaskResult) =
@@ -64,31 +64,31 @@ proc handleResult*(listener, agent, task: string, taskResult: TaskResult) =
let date: string = now().format("dd-MM-yyyy HH:mm:ss")
if taskResult.status == Failed:
if taskResult.status == cast[uint8](STATUS_FAILED):
cq.writeLine(fgBlack, styleBright, fmt"[{date}]", fgRed, styleBright, " [-] ", resetStyle, fmt"Task {task} failed.")
if taskResult.data != "":
if taskResult.data.len != 0:
cq.writeLine(fgBlack, styleBright, fmt"[{date}]", fgRed, styleBright, " [-] ", resetStyle, "Output:")
# Split result string on newline to keep formatting
for line in decode(taskResult.data).split("\n"):
cq.writeLine(line)
# for line in decode(taskResult.data).split("\n"):
# cq.writeLine(line)
else:
cq.writeLine()
else:
cq.writeLine(fgBlack, styleBright, fmt"[{date}]", fgGreen, " [+] ", resetStyle, fmt"Task {task} finished.")
if taskResult.data != "":
if taskResult.data.len != 0:
cq.writeLine(fgBlack, styleBright, fmt"[{date}]", fgGreen, " [+] ", resetStyle, "Output:")
# Split result string on newline to keep formatting
for line in decode(taskResult.data).split("\n"):
cq.writeLine(line)
# for line in decode(taskResult.data).split("\n"):
# cq.writeLine(line)
else:
cq.writeLine()
# Update task queue to include all tasks, except the one that was just completed
cq.agents[agent].tasks = cq.agents[agent].tasks.filterIt(it.id != task)
# cq.agents[agent].tasks = cq.agents[agent].tasks.filterIt(it.id != task)
return

View File

@@ -3,7 +3,7 @@ import sequtils, strutils, times
import ./handlers
import ../utils
import ../../types
import ../../common/types
proc error404*(ctx: Context) {.async.} =
resp "", Http404
@@ -86,16 +86,13 @@ proc getTasks*(ctx: Context) {.async.} =
let
listener = ctx.getPathParams("listener")
agent = ctx.getPathParams("agent")
let tasksJson = getTasks(listener, agent)
# If agent/listener is invalid, return a 404 Not Found error code
if tasksJson == nil:
try:
let tasks = getTasks(listener, agent)
resp $tasks
except CatchableError:
resp "", Http404
# Return all currently active tasks as a JsonObject
resp jsonResponse(tasksJson)
#[
POST /{listener-uuid}/{agent-uuid}/{task-uuid}/results

View File

@@ -1,9 +1,9 @@
import terminal, strformat, strutils, tables, times, system, osproc, streams
import ../utils
import ../task/handler
import ../task/dispatcher
import ../db/database
import ../../types
import ../../common/types
# Utility functions
proc addMultiple*(cq: Conquest, agents: seq[Agent]) =

View File

@@ -4,7 +4,7 @@ import prologue
import ../utils
import ../api/routes
import ../db/database
import ../../types
import ../../common/types
# Utility functions
proc delListener(cq: Conquest, listenerName: string) =

View File

@@ -4,7 +4,7 @@ import strutils, strformat, times, system, tables
import ./[agent, listener]
import ../[globals, utils]
import ../db/database
import ../../types
import ../../common/types
#[
Argument parsing

View File

@@ -2,7 +2,7 @@ import system, terminal, tiny_sqlite
import ./[dbAgent, dbListener]
import ../utils
import ../../types
import ../../common/types
# Export functions so that only ./db/database is required to be imported
export dbAgent, dbListener

View File

@@ -1,7 +1,7 @@
import system, terminal, tiny_sqlite, times
import ../utils
import ../../types
import ../../common/types
#[
Agent database functions

View File

@@ -1,7 +1,7 @@
import system, terminal, tiny_sqlite
import ../utils
import ../../types
import ../../common/types
# Utility functions
proc stringToProtocol*(protocol: string): Protocol =

View File

@@ -1,4 +1,4 @@
import ../types
import ../common/types
# Global variable for handling listeners, agents and console output
var cq*: Conquest

View File

@@ -1,5 +1,6 @@
import random
import core/server
import strutils
# Conquest framework entry point
when isMainModule:

View File

@@ -1,16 +1,188 @@
import argparse, times, strformat, terminal, sequtils
import ../../types
import times, strformat, terminal, tables, json, sequtils, strutils
import ./[parser, packer]
import ../utils
import ../../common/types
proc createTask*(cq: Conquest, command: CommandType, args: string, message: string) =
let
date = now().format("dd-MM-yyyy HH:mm:ss")
task = Task(
id: generateUUID(),
agent: cq.interactAgent.name,
command: command,
args: args,
)
proc initAgentCommands*(): Table[string, Command] =
var commands = initTable[string, Command]()
commands["shell"] = Command(
name: "shell",
commandType: CMD_SHELL,
description: "Execute a shell command and retrieve the output.",
example: "shell whoami /all",
arguments: @[
Argument(name: "command", description: "Command to be executed.", argumentType: STRING, isRequired: true),
Argument(name: "arguments", description: "Arguments to be passed to the command.", argumentType: STRING, isRequired: false)
]
)
commands["sleep"] = Command(
name: "sleep",
commandType: CMD_SLEEP,
description: "Update sleep delay configuration.",
example: "sleep 5",
arguments: @[
Argument(name: "delay", description: "Delay in seconds.", argumentType: INT, isRequired: true)
]
)
commands["pwd"] = Command(
name: "pwd",
commandType: CMD_PWD,
description: "Retrieve current working directory.",
example: "pwd",
arguments: @[]
)
commands["cd"] = Command(
name: "cd",
commandType: CMD_CD,
description: "Change current working directory.",
example: "cd C:\\Windows\\Tasks",
arguments: @[
Argument(name: "directory", description: "Relative or absolute path of the directory to change to.", argumentType: STRING, isRequired: true)
]
)
commands["ls"] = Command(
name: "ls",
commandType: CMD_LS,
description: "List files and directories.",
example: "ls C:\\Users\\Administrator\\Desktop",
arguments: @[
Argument(name: "directory", description: "Relative or absolute path. Default: current working directory.", argumentType: STRING, isRequired: false)
]
)
commands["rm"] = Command(
name: "rm",
commandType: CMD_RM,
description: "Remove a file.",
example: "rm C:\\Windows\\Tasks\\payload.exe",
arguments: @[
Argument(name: "file", description: "Relative or absolute path to the file to delete.", argumentType: STRING, isRequired: true)
]
)
commands["rmdir"] = Command(
name: "rmdir",
commandType: CMD_RMDIR,
description: "Remove a directory.",
example: "rm C:\\Payloads",
arguments: @[
Argument(name: "directory", description: "Relative or absolute path to the directory to delete.", argumentType: STRING, isRequired: true)
]
)
commands["move"] = Command(
name: "move",
commandType: CMD_MOVE,
description: "Move a file or directory.",
example: "move source.exe C:\\Windows\\Tasks\\destination.exe",
arguments: @[
Argument(name: "source", description: "Source file path.", argumentType: STRING, isRequired: true),
Argument(name: "destination", description: "Destination file path.", argumentType: STRING, isRequired: true)
]
)
commands["copy"] = Command(
name: "copy",
commandType: CMD_COPY,
description: "Copy a file or directory.",
example: "copy source.exe C:\\Windows\\Tasks\\destination.exe",
arguments: @[
Argument(name: "source", description: "Source file path.", argumentType: STRING, isRequired: true),
Argument(name: "destination", description: "Destination file path.", argumentType: STRING, isRequired: true)
]
)
return commands
let commands = initAgentCommands()
proc getCommandFromTable(input: string, commands: Table[string, Command]): Command =
try:
let command = commands[input]
return command
except ValueError:
raise newException(ValueError, fmt"The command '{input}' does not exist.")
proc displayHelp(cq: Conquest, commands: Table[string, Command]) =
cq.writeLine("Available commands:")
cq.writeLine(" * back")
for key, cmd in commands:
cq.writeLine(fmt" * {cmd.name:<15}{cmd.description}")
cq.writeLine()
proc displayCommandHelp(cq: Conquest, command: Command) =
var usage = command.name & " " & command.arguments.mapIt(
if it.isRequired: fmt"<{it.name}>" else: fmt"[{it.name}]"
).join(" ")
if command.example != "":
usage &= "\nExample : " & command.example
cq.writeLine(fmt"""
{command.description}
Usage : {usage}
""")
if command.arguments.len > 0:
cq.writeLine("Arguments:\n")
let header = @["Name", "Type", "Required", "Description"]
cq.writeLine(fmt" {header[0]:<15} {header[1]:<6} {header[2]:<8} {header[3]}")
cq.writeLine(fmt" {'-'.repeat(15)} {'-'.repeat(6)} {'-'.repeat(8)} {'-'.repeat(20)}")
for arg in command.arguments:
let isRequired = if arg.isRequired: "YES" else: "NO"
cq.writeLine(fmt" * {arg.name:<15} {($arg.argumentType).toUpperAscii():<6} {isRequired:>8} {arg.description}")
cq.writeLine()
proc handleHelp(cq: Conquest, parsed: seq[string], commands: Table[string, Command]) =
try:
# Try parsing the first argument passed to 'help' as a command
cq.displayCommandHelp(getCommandFromTable(parsed[1], commands))
except IndexDefect:
# 'help' command is called without additional parameters
cq.displayHelp(commands)
except ValueError:
# Command was not found
cq.writeLine(fgRed, styleBright, fmt"[-] The command '{parsed[1]}' does not exist." & '\n')
proc handleAgentCommand*(cq: Conquest, input: string) =
# Return if no command (or just whitespace) is entered
if input.replace(" ", "").len == 0: return
let date: string = now().format("dd-MM-yyyy HH:mm:ss")
cq.writeLine(fgBlue, styleBright, fmt"[{date}] ", fgYellow, fmt"[{cq.interactAgent.name}] ", resetStyle, styleBright, input)
# Convert user input into sequence of string arguments
let parsedArgs = parseInput(input)
cq.interactAgent.tasks.add(task)
cq.writeLine(fgBlack, styleBright, fmt"[{date}] [*] ", resetStyle, message)
# Handle 'back' command
if parsedArgs[0] == "back":
return
# Handle 'help' command
if parsedArgs[0] == "help":
cq.handleHelp(parsedArgs, commands)
return
# Handle commands with actions on the agent
try:
let
command = getCommandFromTable(parsedArgs[0], commands)
task = cq.parseTask(command, parsedArgs[1..^1])
taskData: seq[byte] = cq.serializeTask(task)
# Add task to queue
cq.interactAgent.tasks.add(taskData)
cq.writeLine(fgBlack, styleBright, fmt"[{date}] [*] ", resetStyle, fmt"Tasked agent to {command.description.toLowerAscii()}")
except CatchableError:
cq.writeLine(fgRed, styleBright, fmt"[-] {getCurrentExceptionMsg()}" & "\n")
return

View File

@@ -1,185 +0,0 @@
import times, strformat, terminal, tables, json, sequtils, strutils
import ./[parser, packer, dispatcher]
import ../utils
import ../../types
proc initAgentCommands*(): Table[CommandType, Command] =
var commands = initTable[CommandType, Command]()
commands[ExecuteShell] = Command(
name: "shell",
commandType: ExecuteShell,
description: "Execute a shell command and retrieve the output.",
example: "shell whoami /all",
arguments: @[
Argument(name: "command", description: "Command to be executed.", argumentType: String, isRequired: true),
Argument(name: "arguments", description: "Arguments to be passed to the command.", argumentType: String, isRequired: false)
]
)
commands[Sleep] = Command(
name: "sleep",
commandType: Sleep,
description: "Update sleep delay configuration.",
example: "sleep 5",
arguments: @[
Argument(name: "delay", description: "Delay in seconds.", argumentType: Int, isRequired: true)
]
)
commands[GetWorkingDirectory] = Command(
name: "pwd",
commandType: GetWorkingDirectory,
description: "Retrieve current working directory.",
example: "pwd",
arguments: @[]
)
commands[SetWorkingDirectory] = Command(
name: "cd",
commandType: SetWorkingDirectory,
description: "Change current working directory.",
example: "cd C:\\Windows\\Tasks",
arguments: @[
Argument(name: "directory", description: "Relative or absolute path of the directory to change to.", argumentType: String, isRequired: true)
]
)
commands[ListDirectory] = Command(
name: "ls",
commandType: ListDirectory,
description: "List files and directories.",
example: "ls C:\\Users\\Administrator\\Desktop",
arguments: @[
Argument(name: "directory", description: "Relative or absolute path. Default: current working directory.", argumentType: String, isRequired: false)
]
)
commands[RemoveFile] = Command(
name: "rm",
commandType: RemoveFile,
description: "Remove a file.",
example: "rm C:\\Windows\\Tasks\\payload.exe",
arguments: @[
Argument(name: "file", description: "Relative or absolute path to the file to delete.", argumentType: String, isRequired: true)
]
)
commands[RemoveDirectory] = Command(
name: "rmdir",
commandType: RemoveDirectory,
description: "Remove a directory.",
example: "rm C:\\Payloads",
arguments: @[
Argument(name: "directory", description: "Relative or absolute path to the directory to delete.", argumentType: String, isRequired: true)
]
)
commands[Move] = Command(
name: "move",
commandType: Move,
description: "Move a file or directory.",
example: "move source.exe C:\\Windows\\Tasks\\destination.exe",
arguments: @[
Argument(name: "source", description: "Source file path.", argumentType: String, isRequired: true),
Argument(name: "destination", description: "Destination file path.", argumentType: String, isRequired: true)
]
)
commands[Copy] = Command(
name: "copy",
commandType: Copy,
description: "Copy a file or directory.",
example: "copy source.exe C:\\Windows\\Tasks\\destination.exe",
arguments: @[
Argument(name: "source", description: "Source file path.", argumentType: String, isRequired: true),
Argument(name: "destination", description: "Destination file path.", argumentType: String, isRequired: true)
]
)
return commands
let commands = initAgentCommands()
proc getCommandFromTable(cmd: string, commands: Table[CommandType, Command]): (CommandType, Command) =
try:
let commandType = parseEnum[CommandType](cmd.toLowerAscii())
let command = commands[commandType]
return (commandType, command)
except ValueError:
raise newException(ValueError, fmt"The command '{cmd}' does not exist.")
proc displayHelp(cq: Conquest, commands: Table[CommandType, Command]) =
cq.writeLine("Available commands:")
cq.writeLine(" * back")
for key, cmd in commands:
cq.writeLine(fmt" * {cmd.name:<15}{cmd.description}")
cq.writeLine()
proc displayCommandHelp(cq: Conquest, command: Command) =
var usage = command.name & " " & command.arguments.mapIt(
if it.isRequired: fmt"<{it.name}>" else: fmt"[{it.name}]"
).join(" ")
if command.example != "":
usage &= "\nExample : " & command.example
cq.writeLine(fmt"""
{command.description}
Usage : {usage}
""")
if command.arguments.len > 0:
cq.writeLine("Arguments:\n")
let header = @["Name", "Type", "", "Description"]
cq.writeLine(fmt" {header[0]:<15} {header[1]:<8}{header[2]:<10} {header[3]}")
cq.writeLine(fmt" {'-'.repeat(15)} {'-'.repeat(18)} {'-'.repeat(20)}")
for arg in command.arguments:
let requirement = if arg.isRequired: "(REQUIRED)" else: "(OPTIONAL)"
cq.writeLine(fmt" * {arg.name:<15} {($arg.argumentType).toUpperAscii():<8}{requirement:<10} {arg.description}")
cq.writeLine()
proc handleHelp(cq: Conquest, parsed: seq[string], commands: Table[CommandType, Command]) =
try:
# Try parsing the first argument passed to 'help' as a command
let (commandType, command) = getCommandFromTable(parsed[1], commands)
cq.displayCommandHelp(command)
except IndexDefect:
# 'help' command is called without additional parameters
cq.displayHelp(commands)
except ValueError:
# Command was not found
cq.writeLine(fgRed, styleBright, fmt"[-] The command '{parsed[1]}' does not exist." & '\n')
proc handleAgentCommand*(cq: Conquest, input: string) =
# Return if no command (or just whitespace) is entered
if input.replace(" ", "").len == 0: return
let date: string = now().format("dd-MM-yyyy HH:mm:ss")
cq.writeLine(fgBlue, styleBright, fmt"[{date}] ", fgYellow, fmt"[{cq.interactAgent.name}] ", resetStyle, styleBright, input)
let parsedArgs = parseAgentCommand(input)
# Handle 'back' command
if parsedArgs[0] == "back":
return
# Handle 'help' command
if parsedArgs[0] == "help":
cq.handleHelp(parsedArgs, commands)
return
# Handle commands with actions on the agent
try:
let
(commandType, command) = getCommandFromTable(parsedArgs[0], commands)
payload = cq.packageArguments(command, parsedArgs)
cq.createTask(commandType, $payload, fmt"Tasked agent to {command.description.toLowerAscii()}")
except CatchableError:
cq.writeLine(fgRed, styleBright, fmt"[-] {getCurrentExceptionMsg()}" & "\n")
return

View File

@@ -1,34 +1,40 @@
import strutils, json
import ../../types
import strutils, strformat, streams
import ../utils
import ../../common/types
import ../../common/serialize
proc packageArguments*(cq: Conquest, command: Command, arguments: seq[string]): JsonNode =
proc serializeTask*(cq: Conquest, task: Task): seq[byte] =
# Construct a JSON payload with argument names and values
result = newJObject()
let parsedArgs = if arguments.len > 1: arguments[1..^1] else: @[] # Remove first element from sequence to only handle arguments
var packer = initTaskPacker()
for i, argument in command.arguments:
# Argument provided - convert to the corresponding data type
if i < parsedArgs.len:
case argument.argumentType:
of Int:
result[argument.name] = %parseUInt(parsedArgs[i])
of Binary:
# Read file into memory and convert it into a base64 string
result[argument.name] = %""
else:
# The last optional argument is joined together
# This is required for non-quoted input with infinite length, such as `shell mv arg1 arg2`
if i == command.arguments.len - 1 and not argument.isRequired:
result[argument.name] = %parsedArgs[i..^1].join(" ")
else:
result[argument.name] = %parsedArgs[i]
# Argument not provided - set to empty string for optional args
else:
# If a required argument is not provided, display the help text
if argument.isRequired:
raise newException(ValueError, "Missing required arguments.")
else:
result[argument.name] = %""
# Serialize payload
packer
.addToPayload(task.taskId)
.addToPayload(task.agentId)
.addToPayload(task.listenerId)
.addToPayload(task.timestamp)
.addToPayload(task.command)
.addToPayload(task.argCount)
for arg in task.args:
packer.addArgument(arg)
let payload = packer.packPayload()
# TODO: Encrypt payload body
# Serialize header
packer
.addToHeader(task.header.magic)
.addToHeader(task.header.version)
.addToHeader(task.header.packetType)
.addToHeader(task.header.flags)
.addToHeader(task.header.seqNr)
.addToHeader(cast[uint32](payload.len))
.addDataToHeader(task.header.hmac)
let header = packer.packHeader()
# TODO: Calculate and patch HMAC
return header & payload

View File

@@ -1,6 +1,8 @@
import ../../types
import strutils, strformat, times
import ../utils
import ../../common/types
proc parseAgentCommand*(input: string): seq[string] =
proc parseInput*(input: string): seq[string] =
var i = 0
while i < input.len:
@@ -30,3 +32,83 @@ proc parseAgentCommand*(input: string): seq[string] =
# Add argument to returned result
if arg.len > 0: result.add(arg)
proc parseArgument*(argument: Argument, value: string): TaskArg =
var result: TaskArg
result.argType = cast[uint8](argument.argumentType)
case argument.argumentType:
of INT:
# Length: 4 bytes
let intValue = cast[uint32](parseUInt(value))
result.data = @[byte(intValue and 0xFF), byte((intValue shr 8) and 0xFF), byte((intValue shr 16) and 0xFF), byte((intValue shr 24) and 0xFF)]
of LONG:
# Length: 8 bytes
var data = newSeq[byte](8)
let intValue = cast[uint64](parseUInt(value))
for i in 0..7:
data[i] = byte((intValue shr (i * 8)) and 0xFF)
result.data = data
of BOOL:
# Length: 1 byte
if value == "true":
result.data = @[1'u8]
elif value == "false":
result.data = @[0'u8]
else:
raise newException(ValueError, "Invalid value for boolean argument.")
of STRING:
result.data = cast[seq[byte]](value)
of BINARY:
# Read file as binary stream
discard
return result
proc parseTask*(cq: Conquest, command: Command, arguments: seq[string]): Task =
# Construct the task payload prefix
var task: Task
task.taskId = uuidToUint32(generateUUID())
task.agentId = uuidToUint32(cq.interactAgent.name)
task.listenerId = uuidToUint32(cq.interactAgent.listener)
task.timestamp = uint32(now().toTime().toUnix())
task.command = cast[uint16](command.commandType)
task.argCount = uint8(arguments.len)
var taskArgs: seq[TaskArg]
# Add the task arguments
for i, arg in command.arguments:
if i < arguments.len:
taskArgs.add(parseArgument(arg, arguments[i]))
else:
if arg.isRequired:
raise newException(ValueError, "Missing required argument.")
else:
# Handle optional argument
taskArgs.add(parseArgument(arg, ""))
task.args = taskArgs
# Construct the header
var taskHeader: Header
taskHeader.magic = MAGIC
taskHeader.version = VERSION
taskHeader.packetType = cast[uint8](MSG_TASK)
taskHeader.flags = cast[uint16](FLAG_PLAINTEXT)
taskHeader.seqNr = 1'u32 # TODO: Implement sequence tracking
taskHeader.size = 0'u32
taskHeader.hmac = default(array[16, byte])
task.header = taskHeader
# Return the task object for serialization
return task

View File

@@ -1,7 +1,7 @@
import strutils, terminal, tables, sequtils, times, strformat, random, prompt
import std/wordwrap
import ../types
import ../common/types
# Utility functions
proc parseOctets*(ip: string): tuple[first, second, third, fourth: int] =
@@ -20,6 +20,21 @@ proc generateUUID*(): string =
# Create a 4-byte HEX UUID string (8 characters)
(0..<4).mapIt(rand(255)).mapIt(fmt"{it:02X}").join()
proc uuidToUint32*(uuid: string): uint32 =
return fromHex[uint32](uuid)
proc uuidToString*(uuid: uint32): string =
return uuid.toHex(8)
proc toHexDump*(data: seq[byte]): string =
for i, b in data:
result.add(b.toHex(2))
if i < data.len - 1:
if (i + 1) mod 4 == 0:
result.add(" | ") # Add | every 4 bytes
else:
result.add(" ") # Regular space
# Function templates and overwrites
template writeLine*(cq: Conquest, args: varargs[untyped]) =
cq.prompt.writeLine(args)