covertutils.handlers package

Submodules

covertutils.handlers.basehandler module

class covertutils.handlers.basehandler.BaseHandler(recv, send, orchestrator, **kw)[source]

Bases: object

Subclassing this class and overriding its methods automatically creates a threaded handler.

Defaults = {'start': True}
__init__(recv, send, orchestrator, **kw)[source]
Parameters:
  • recv (function) – A blocking function that returns every time a chunk is received. The return type must be raw data, directly fetched from the channel.
  • send (function) – A function that takes raw data as argument and sends it across the channel.
  • orchestrator (orchestration.SimpleOrchestrator) – An Object that is used to translate raw data to (stream, message) tuples.
addStream(stream)[source]
getOrchestrator()[source]
Return type:Orchestrator
Returns:Returns the Orchestrator object used to create this Handler instance.
onChunk(stream, message)[source]

AbstractMethod

This method runs whenever a new recognised chunk is consumed.

Parameters:
  • stream (str) – The recognised stream that this chunk belongs.
  • message (str) – The message that is contained in this chunk. Empty string if the chunk is not the last of a reassembled message.

This method will run even to for chunks that will trigger the onMessage() method. To stop that you need to add the above code in the beginning.

if message != '' :      # meaning that the message is assembled, so onMessage() will run
        return
onMessage(stream, message)[source]

AbstractMethod

This method runs whenever a new message is assembled.

Parameters:
  • stream (str) – The recognised stream that this chunk belongs.
  • message (str) – The message that is contained in this chunk.
onNotRecognised()[source]

AbstractMethod

This method runs whenever a chunk is not recognised.

Return type:None
queueSend(message, stream=None)[source]
Parameters:
  • message (str) – The message that will be stored for sending upon request.
  • stream (str) – The stream where the message will be sent.
readifyQueue()[source]
reset()[source]
sendAdHoc(message, stream=None, assert_len=0)[source]

This method uses the object’s SimpleOrchestrator instance to send raw data to the other side, throught the specified Stream. If stream is None, the default Orchestrator’s stream will be used.

Parameters:
  • message (str) – The message send to the other side.
  • stream (str) – The stream name that will tag the data.
  • assert_len (int) – Do not send if the chunked message exceeds assert_len chunks.
Return type:

bool

True is returned when the message is sent, False otherwise.

start()[source]

Starts the thread that consumes data and enables the on* callback methods.

stop()[source]

Stops the handler thread making the data consumer to return (if not blocked).

covertutils.handlers.buffering module

class covertutils.handlers.buffering.BufferingHandler(recv, send, orchestrator, **kw)[source]

Bases: covertutils.handlers.basehandler.BaseHandler

Subclassing this class ensures that all Messages received will be available through a blocking get() method, the same way a queue.Queue object provides access to its contents.

__init__(recv, send, orchestrator, **kw)[source]
static bufferize_handler(handler_class)[source]

Pairs a class with BufferingHandler class to create a child class, inheriting from both the passed handler_class and BufferingHandler class.

static bufferize_handler_obj(handler_obj)[source]

Migrate an existing object inheriting from BaseHandler to be an effective child of BufferingHandler.

Attaches the BufferingHandler as a parent class in __class__ object field and runs the specialized __init__ for BufferingHandler inside the objects context. BufferingHandler.__init__ has to run in the object in order to initiate the buffering process of BufferingHandler.

empty()[source]
get()[source]

Blocking call that wraps the internal buffer’s get() function

getCondition()[source]
onMessage(stream, message)[source]

covertutils.handlers.dateable module

class covertutils.handlers.dateable.DateableHandler(recv, send, orchestrator, **kw)[source]

Bases: covertutils.handlers.basehandler.BaseHandler

Defaults = {'workinghours': ((9, 0), (17, 0)), 'easter': {'after': 2, 'before': 2}, 'weekends': [5, 6], 'holidays': [(1, 1), (25, 12)]}
__init__(recv, send, orchestrator, **kw)[source]
mustNotRespond(fixed_date=None)[source]
queueSend(message, stream=None)[source]
sendAdHoc(message, stream=None)[source]
covertutils.handlers.dateable.calc_easter(year)[source]

returns the date of Easter Sunday of the given yyyy year

covertutils.handlers.dateable.getDay(inp)[source]

covertutils.handlers.functiondict module

class covertutils.handlers.functiondict.FunctionDictHandler(recv, send, orchestrator, **kw)[source]

Bases: covertutils.handlers.basehandler.BaseHandler

This class provides a per-stream function dict. If a message is received from a stream, a function corresponding to this particular stream will be executed with single argument the received message. The function’s return value will be sent across that stream to the message’s sender.

Ideal for simple remote shell implementation.

The FunctionDictHandler class implements the onMessage() function of the BaseHandler class. The function_dict passed to this class __init__() must have the above format:

def os_echo( message ) :
        from os import popen
        resp = popen( "echo %s" % 'message' ).read()
        return resp

function_dict = { 'echo' : os_echo }

Note: The functions must be absolutely self contained. In the above example the popen() function is imported inside the os_echo. This is to ensure that popen() will be available, as there is no way to tell if it will be imported from the handler’s environment.

Well defined functions for that purpose can be found in covertutils.payloads. Also usable for the StageableHandler class

from covertutils.payloads import GenericStages
pprint( GenericStages )
{'shell': {'function': <function __system_shell at 0x7fc347472320>,
           'marshal': 'c\x01\x00\x00\x00\x03\x00\x00\x00\x02\x00\x00\x00C\x00\x00\x00s&\x00\x00\x00d\x01\x00d\x02\x00l\x00\x00m\x01\x00}\x01\x00\x01|\x01\x00|\x00\x00\x83\x01\x00j\x02\x00\x83\x00\x00}\x02\x00|\x02\x00S(\x03\x00\x00\x00Ni\xff\xff\xff\xff(\x01\x00\x00\x00t\x05\x00\x00\x00popen(\x03\x00\x00\x00t\x02\x00\x00\x00osR\x00\x00\x00\x00t\x04\x00\x00\x00read(\x03\x00\x00\x00t\x07\x00\x00\x00messageR\x00\x00\x00\x00t\x06\x00\x00\x00result(\x00\x00\x00\x00(\x00\x00\x00\x00s\x15\x00\x00\x00covertutils/Stages.pyt\x0e\x00\x00\x00__system_shell\x04\x00\x00\x00s\x06\x00\x00\x00\x00\x01\x10\x01\x12\x01'}}
__init__(recv, send, orchestrator, **kw)[source]
Parameters:function_dict (dict) – A dict containing (stream_name, function) tuples. Every time a message is received from stream_name, function(message) will be automatically executed.
addStage(stream, stage_obj)[source]
getStage(stage_obj)[source]
onChunk(stream, message)[source]
onMessage(stream, message)[source]
Raises:NoFunctionAvailableException
onNotRecognised()[source]
stageWorker(init, worker, storage)[source]

covertutils.handlers.interrogating module

class covertutils.handlers.interrogating.InterrogatingHandler(recv, send, orchestrator, **kw)[source]

Bases: covertutils.handlers.basehandler.BaseHandler

This handler has a beaconing behavior, repeatedly querring the channel for messages. This behavior is useful on agents that need to have a client-oriented traffic. HTTP/S agents (meterpreter HTTP/S) use this approach, issueing HTTP (GET/POST) requests to the channel and executing messages found in HTTP responses. This behavior can simulate Web Browsing, ICMP Ping, DNS traffic schemes.

This handler can be nicely coupled with covertutils.handlers.ResponseOnlyHandler for a Server-Client approach.

Defaults = {'request_data': 'X', 'fetch_stream': 'control', 'delay_between': (1.0, 2.0)}
__init__(recv, send, orchestrator, **kw)[source]
Parameters:
  • request_data (str) – The actual payload that is used in messages thet request data.
  • delay_between (tuple) – A tuple containing 2 floats or ints. The beaconing intervals will be calculated randomly between these 2 numbers.
  • fetch_stream (str) – The stream where all the beaconing will be tagged with.

covertutils.handlers.responseonly module

class covertutils.handlers.responseonly.ResponseOnlyHandler(recv, send, orchestrator, **kw)[source]

Bases: covertutils.handlers.basehandler.BaseHandler

This handler doesn’t send messages with the sendAdHoc method. It implements a method queueSend to queue messages, and send them only if it is queried with a request_data message.

Can be nicely paired with covertutils.handlers.InterrogatingHandler for a Client-Server approach.

Defaults = {'request_data': 'X'}
__init__(recv, send, orchestrator, **kw)[source]
Parameters:request_data (str) – The data that, when received as message, a stored chunk will be sent.
onMessage(stream, message)[source]

covertutils.handlers.stageable module

class covertutils.handlers.stageable.StageableHandler(recv, send, orchestrator, **kw)[source]

Bases: covertutils.handlers.functiondict.FunctionDictHandler

The StageableHandler is a covertutils.handlers.FunctionDictHandler that can load payloads (stages) during execution. Additional functions can be sent in a serialized form (ready stages can be found in covertutils.payloads). The stage function have to be implemented according to covertutils.handlers.FunctionDictHandler documentation.

To running StageableHandler`s, additional functions can be packed with the :func:covertutils.handlers.`StageableHandler.createStageMessage and sent like normal messages with a sendAdHoc call.

Add_Action = 'A'
Defaults = {'stage_stream': 'stage'}
Delete_Action = 'D'
Delimiter = ':'
Replace_Action = 'R'
__init__(recv, send, orchestrator, **kw)[source]
Parameters:stage_stream (str) – The stream where all stages will be received.
static createStageMessage(stream, stage_obj, replace=True)[source]
Parameters:
  • stream (str) – The stream where the new stage will receive messages from.
  • serialized_function (str) – The stage-function serialized with the marshal build-in package.
  • replace (bool) – If True the stage that currently listens to the given stream will be replaced.
onMessage(stream, message)[source]
covertutils.handlers.stageable.stager_worker(storage, message)[source]

Module contents

This module provides a template for Automatic protocol creation. The base class covertutils.handlers.BaseHandler provide an API with methods:

  • onChunk()
  • onMessage()
  • onNotRecognized()

Subclassing the BaseHandler class needs an implementation of the above methods.

from covertutils.handlers import BaseHandler

class MyHandler( BaseHandler ) :

        def onMessage( self, stream, message ) :
                print "Got Message '%s' from Stream %s" % ( stream, message )

        def onChunk( self, stream, message ) :
                print "Got Chunk from Stream %s" % ( stream, message )
                if message != '' :
                        print "This was the last chunk of a message"

        def onNotRecognised( self ) :
                print "Got Garbage Data"

Creating a MyHandler Object needs 2 wrapper functions for raw data sending and receiving. The receiving function needs to be blocking, just like socket.socket.recv() Also a covertutils.orchestration.SimpleOrchestrator object is required to handle data chunking, compression and encryption.

passphrase = "Th1s1sMyS3cr3t"
orch = SimpleOrchestrator( passphrase, tag_length = 2, out_length = 50, in_length = 50 )

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect( addr )

def recv () :
        return s.recv(50)

def send( raw ) :
        return s.send( raw )

handler_obj = MyHandler( recv, send, orch )

Then it is possible to send messages to other Handler instances using the sendAdHoc() method.

handler_obj.sendAdHoc( "Hello from me" )

Everytime a message is received, the overriden onMessage() method will run.

For the Handler at the other side of the channel, to properly decrypt and handle the binary sent by handler_obj it is needed to be instantiated with the covertutils.orchestration.SimpleOrchestrator.__init__() argument “”reverse = True”“

passphrase = "Th1s1sMyS3cr3t"
orch2 = SimpleOrchestrator( passphrase, tag_length = 2, out_length = 50, in_length = 50, reverse = True )

handler_obj2 = MyHandler( recv2, send2, orch2 )

The Handler Classes are designed for Multiple Inheritance for further flexibility. For instance a Querying, Stageable agent can be implemented like below:

from covertutils.handlers import InterrogatingHandler, StageableHandler

class MyHandler2( InterrogatingHandler, StageableHandler ) :

        def __init__( self, recv, send, orch, **kw ) :
                super( MyHandler, self ).__init__( recv, send, orch, **kw )

        def onChunk( self, stream, message ) :pass
        def onNotRecognised( self ) :pass

Now, creating a MyHandler2 object needs the 3 standard arguments (inherited from covertutils.handlers.BaseHandler.__init__()), and all optional arguments that are needed by the provided Parent Classes.