Last updated at Wed, 07 Feb 2024 19:57:09 GMT

Metasploit provides many ways to simplify your life as a module developer. One of the less well-known of these is the presence of various hooks you can use for processing things at important stages of the module's lifetime. The basic one that anyone who has written an exploit will be familiar with is exploit, which is called when the user types the exploit command. That method is common to all exploit modules. Aux and post modules have an analogous run method. Common to all the runnable modules (aux, post, and exploit) are setup and cleanup, which are called at the beginning and end of a module run, respectively. Setup is meant as a place for modules to read in data files, start services, or any other task that needs to happen one time before running the main body of the module. Cleanup is designed to be run afterwards for restoring settings or for deallocating resources that the module used. For example, the cleanup method might be used to kill any background threads that the module spawned or to delete files dropped on the victim (but see the FileDropper mixin if you need to do that).

Some mixins add to the list of available hooks or override exploit to provide a different interface. The first I'd like to mention, and one of the most common, is HttpServer. Its exploit method sets up the server. All (well, almost all) browser exploits include this mixin and define the on_request_uricallback. What you may not know is that HttpServer inherits from TcpServer and therefore has all of these, as well:

  • on_client_connect
  • on_client_data
  • on_client_close

In addition, TcpServer has one more obscure hook: primer. For a client-side exploit (i.e., one that includes a server mixin of some sort), you generally define one of the on_* hooks to be called whenever a client event occurs and just let the exploit method start the server and begin dealing with requests from clients. But sometimes you need to do something to trigger that request. An example is a server that can be manipulated into downloading and executing something -- after setting up a server to provide the payload, you need to trigger the download with a request. That's where primer comes in.

Here's the relevant code from TcpServer:

#
# This mixin overrides the exploit method so that it can initiate the
# service that corresponds with what the client has requested.
#
def exploit

    start_service()
    print_status("Server started.")
    
    # Call the exploit primer
    primer
    
    # Wait on the service to stop
    self.service.wait
end 

This came up when discussing Juan's recent ibm_director_cim_dllinject module, but it is useful for any module that acts as both a server and a client.

If you'd like to dive into writing Metasploit modules, the documentation can help with the various APIs for protocols and exploit techniques: https://metasploit.help.rapid7.com