metasploit-framework/lib/rex/powershell/obfu.rb

97 lines
2.2 KiB
Ruby
Raw Normal View History

# -*- coding: binary -*-
require 'rex/text'
module Rex
module Powershell
module Obfu
2014-07-20 20:00:34 +00:00
MULTI_LINE_COMMENTS_REGEX = Regexp.new(/<#(.*?)#>/m)
SINGLE_LINE_COMMENTS_REGEX = Regexp.new(/^\s*#(?!.*region)(.*$)/i)
WINDOWS_EOL_REGEX = Regexp.new(/[\r\n]+/)
UNIX_EOL_REGEX = Regexp.new(/[\n]+/)
WHITESPACE_REGEX = Regexp.new(/\s+/)
EMPTY_LINE_REGEX = Regexp.new(/^$|^\s+$/)
#
# Remove comments
#
2014-05-05 16:47:30 +00:00
# @return [String] code without comments
def strip_comments
# Multi line
2014-07-20 20:07:59 +00:00
code.gsub!(MULTI_LINE_COMMENTS_REGEX, '')
# Single line
2014-07-20 20:07:59 +00:00
code.gsub!(SINGLE_LINE_COMMENTS_REGEX, '')
2014-05-05 17:38:48 +00:00
code
end
#
# Remove empty lines
#
2014-05-05 16:47:30 +00:00
# @return [String] code without empty lines
def strip_empty_lines
# Windows EOL
2014-07-20 20:07:59 +00:00
code.gsub!(WINDOWS_EOL_REGEX, "\r\n")
# UNIX EOL
2014-07-20 20:07:59 +00:00
code.gsub!(UNIX_EOL_REGEX, "\n")
2014-05-05 17:38:48 +00:00
code
end
#
# Remove whitespace
# This can break some codes using inline .NET
#
2014-05-05 16:47:30 +00:00
# @return [String] code with whitespace stripped
def strip_whitespace
2014-07-20 20:07:59 +00:00
code.gsub!(WHITESPACE_REGEX, ' ')
2014-05-05 17:38:48 +00:00
code
end
#
# Identify variables and replace them
#
2014-05-05 16:47:30 +00:00
# @return [String] code with variable names replaced with unique values
def sub_vars
# Get list of variables, remove reserved
2014-07-20 20:07:59 +00:00
get_var_names.each do |var, _sub|
2014-05-05 17:38:48 +00:00
code.gsub!(var, "$#{@rig.init_var(var)}")
end
2014-05-05 17:38:48 +00:00
code
end
#
# Identify function names and replace them
#
2014-05-05 16:47:30 +00:00
# @return [String] code with function names replaced with unique
# values
def sub_funcs
# Find out function names, make map
2014-07-20 20:07:59 +00:00
get_func_names.each do |var, _sub|
2014-05-05 17:38:48 +00:00
code.gsub!(var, @rig.init_var(var))
end
2014-05-05 17:38:48 +00:00
code
end
#
# Perform standard substitutions
#
2014-05-05 16:47:30 +00:00
# @return [String] code with standard substitution methods applied
2014-07-20 20:07:59 +00:00
def standard_subs(subs = %w(strip_comments strip_whitespace sub_funcs sub_vars))
# Save us the trouble of breaking injected .NET and such
2014-05-05 17:38:48 +00:00
subs.delete('strip_whitespace') unless get_string_literals.empty?
# Run selected modifiers
subs.each do |modifier|
2014-07-20 20:07:59 +00:00
send(modifier)
end
2014-07-20 20:07:59 +00:00
code.gsub!(EMPTY_LINE_REGEX, '')
2014-05-05 16:47:30 +00:00
code
end
end # Obfu
end
end