Showing posts with label technical. Show all posts
Showing posts with label technical. Show all posts

Tuesday, May 12, 2015

Security: Hacking Wordpress/PHP, Ruby Comparisons, and Lessons Learned

Another US Cert alert went out for Wordpress last week.  I'm not shocked.  I call Wordpress one of the biggest hacker honeypots around because it keeps popping up in cybersecurity news.  Yet, it's not fair to be subjective.   To be more objective, I'll take a look at verified  software vulnerabilities to assess what's happening under the hood.

Part 1: Lots of Vulnerabilities


I went back to MITRE's CVE database again (NIST's mirror isn't as user friendly) to compare how many vulnerabilities have been occurring in Wordpress and PHP -- the core language behind Wordpress -- versus another popular web development language, Ruby (and Ruby on Rails).  See my previous post on CVEs and preventing software vulnerabilities for using these databases.  Anyways, a simplistic comparison of all vulnerabilities found in Ruby versus PHP is staggering:

CVE Total Counts

$ curl -s https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=ruby | grep "CVE" | wc -l
288
$ curl -s https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=php | grep "CVE" | wc -l
5812

For the studious, since Ruby doesn't really have a good equivalent to Wordpress, it's fairer to see that Ruby on Rails CVE counts are not on the same scale as PHP.  Here's their CVE dumps of those too:

$ curl -s https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=rails | grep CVE | wc -l
122
$ curl -s https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=wordpress | grep CVE | wc -l
951

It should be noted -- especially for the skeptical -- that PHP and Ruby have some relevant differences.  PHP version 1.0 was released in June 1995 while Ruby 1.0 was released December 1996, but PHP is only slightly older than Ruby.  The CVE dumps above are for all known time, so I don't think their age explains the difference in quantity (and the CVE databases only go back to the early 2000s anyways).  I chose to compare these two languages instead of solutions built on top of them, like Wordpress, because they are both popular, both interpreted languages, and both end on the front line of cybersecurity -- running public websites.

Adoption and Presence


A coworker sent me over to BuiltWith for an unrelated comparison of website softwares so I thought it would be a good tool to dig deeper on the software adoption being related to quantities of vulnerabilities.  BuildWith is a service that scrapes online footprints to determine which softwares run public websites -- everything from operating systems to content management systems like Wordpress.  It's pretty nifty.  I asked BuildWith what the adoption rates look like for PHP and Ruby on Rails (there was no pure Ruby data, which makes sense for BuiltWith's purpose):

Framework Usage


Essentially, PHP pops up 30 more times in websites than Ruby but PHP usage is essentially stable while Ruby's is on the rise; so it's worth another look at whether the frequency of vulnerabilities is related to usage or adoption.  Here's vulnerabilities found over time and basic trends in each language:

CVE Counts per Year
Language2012201320142015 ForecastLinear Regress
PHP171127150128.3333333-10.5
Ruby33752739-3
* note Google Slide FORECAST uses a slightly different model than SLOPE, so calling that out.

Contrast the vulnerabilities trend in Ruby -- a decreasing rate of occurrence -- with the adoption rate of Ruby according to BuiltWith -- a ~33% annual growth.  Of course, there's many reasons for finding vulnerabilities, like a large adoption may mean more hackers want to target a larger victim population, or popularity could drive up the amount of bugs in an effort to meet many (possibly insecure) feature requests.  To play Devil's Advocate, PHP does indeed have a decreasing rate of vulnerabilities, but it isn't being adopted more than Ruby. So does a 20-fold difference in vulnerabilities between PHP and Ruby get explained away by their sheer online presence?

Part 2: Writing Bugs


Instances and rates of vulnerabilities don't capture the severity of each vulnerability, or the ease of a hacker exploiting the software, or the laziness of programmers.  (CVSS does focus our attention, though.)  Also, cybersecurity news only gives us superficial  recommendations like "security patch available, update now!" instead of digging deeper into buggy software.  At most, we may read that a "XSS" or "SQL injection" vulnerability was found -- as if those phrases invoke some kind of meaning into our decision to use one software over another.  I decided to dive deeper into one of these XSS & SQL injection Wordpress bugs, similar to one that caused the US Cert issued last week, and found some disturbing practices in PHP programming and some ignored best practices.

One recent vulnerability in Wordpress came down to programmers being too lazy to scrub data input.  Something as seemingly benign as a Wordpress forum was exploited by submitting HTML into the comment field; and because Javascript can be embedded into any valid HTML data stream, the PHP server parsed and rendered back to the web browser client whatever had been submitted as a comment.  The marvel of this hack is that Wordpress comment moderators are often Wordpress administrators who have logged in with unlimited access to the site, so malicious Javascript embedded in a comment field on their web browsers would gain unauthorized, elevated privileges to execute against the entire website.  The studious guy who found this vulnerability made a horrific demo of Javascript uploading content to the PHP server without the moderator's/administrator's knowledge.  That demo leverages cross-site scripting (XSS) to upload the content but it could have injected malicious SQL into Wordpress.

I've respected the programmer's motto of being lazy and keeping things simple but after seeing this hack I wonder: have we become too lazy?  Apparently the Wordpress comment functionality above wasn't unknown to developers.  Wordpress designed the comment form this way as a feature -- Wordpress users wanted to "texturize" comments with options like italicized fonts, embedded hyperlinks, etc. so Wordpress developers enabled HTML parsing of comments by the PHP engine.  They were actually doing a kind of data filtering of the comment field but did not thoroughly sanitize it!

In the first chapter of his concise work PHP Security, Shiflett's rationale for bringing up thorough data scrubbing at the very start of his book harkens back to the CVE reports I've cited before:

The vast majority of security vulnerabilities in popular PHP applications can be traced to a failure to filter input. (pg. 21)

A bit of Googling on problems with PHP programmers filtering data returned some disturbing practices.  For example, PHP had come up with a global requirement for quoted data to be escaped to prevent SQL injections but Shiflett notes that in reality this caused complications that encouraged programmers to fall back to merely stripping data of quotes or slashes instead of checking for valid data.  When this global quoting requirement troubled one PHP programmer, not a single suggestion included either checking for valid data or using best practices in filtering data.  Shiflett suggests using standard data sanitation functions in PHP, including htmlentities() for interacting with front-end data (and its exhaustive ENT_QUOTES parameter), mysql_real_escape_string() for back-end data, etc.  Why were these functions not included in answers for the PHP programmer having issues with quoted data?

To go back to the above case of the Wordpress vulnerability, what constitutes "thorough" data sanitization?  In the most strict sense, the Wordpress fix required not allowing HTML input from the user that hadn't been predefined. To keep that feature in tact, Wordpress developers had done data filtering that only allowed a subset of HTML to be valid input, but that kind of sanitation was undermined by forgetting another data sanitization process: not checking for valid data size.  The hack demo'ed above, after all, leveraged a very lengthy comment field.  So the vulnerability was incomplete or superficial data sanitation.  If I extrapolate these mishaps to web application security for Ruby, then there isn't a magic pill.  Ruby or Rails might have more programmatic means for data sanitation but the same fundamental process applies.  (I'll leave Ruby data sanitization for a follow-up blog.)  Generally speaking then, I don't buy the excuse that vulnerabilities are merely a lack of forethought.  It gets back to how we program.

Preventing Bugs


One of my coworkers boiled this entire blog down to "bad coding" but I think that is laziness itself speaking on our behalves.  The takeaway I got from writing about this XSS and SQL injection bug is the latent, perennial problem of feature requests over best practices.  Allowing texturized comments was valued more than allowing thorough data sanitization.  In the PHP / Wordpress examples above, data sanitation was needed for:

  1. String fields of maximum length
  2. String data input of only predefined HTML tags

More generally, the development lifecycle would include systematic means for exhausting the scrubbing of data input and output.

Programmers have a means for various testing, and can include a good kind of testing in-flight with unit tests.  For every input or output operation, we should iterate over data that abuses the interface to determine whether more data sanitation is needed.  This leads to one characteristic of Ruby and PHP where the languages differ.  Ruby includes a standard, unit test out-of-the-box whereas PHP programmers must choose and install one of many frameworks to start doing them.

These lessons learned aren't news.  Even good Ruby web applications will need to be written with the idea of systematically preventing bugs and weaknesses by exhaustively testing data sanitation.  MITRE's common weaknesses database is blatantly sarcastic about their best practices being ignored by programmers, as attested by their reports.  (See CWE-79, and CWE-434).  To be fair, MITRE's recommendations can be harsh, like not trusting any input, even a PNG sourced by HTML, so some of the lessons boil down to classic security debates about functionality.  And to be honest, I haven't typically tested for unexpected data, have only done the minimum in leveraging programmatic data filtering, and I've never included unit tests in my own programs.  These are all recommendations I make knowing that being lazy isn't an excuse.  What is left unknown is whether PHP programmers are more lazy than Ruby programmers.  :)


Tuesday, December 16, 2014

Security: IT's Chronic Disease

Technology has a chronic disease.  If IT were a patient, it would be covered in lesions and leaking out of every orifice.  This disease is how your credit cards are stolen, your private pictures are proliferated, your favorite website taken down -- by hackers using malicious software (malware) that's crippled IT.  These tidbits aren't newsworthy if you're a cynic because they've been plaguing us for decades.  I'm an optimistic technologist who thinks being more forthcoming the diagnosis and treatment of IT security will reveal -- not a cure -- a healthier.

Immune System

Technologists do have systems for diagnosing and treating software "diseases" at a global scale.  I'm not talking about installing anti-virus on your laptop.  I mean something on par with the WHO or CDC for computers.  There are technical institutions that take the lead in identifying, squelching, fixing, and tracking software vulnerabilities.  The most notable institutions are the MITRE quasi-government corporation and the SANS Institute, the infamous Open Software Foundation (OSF); yet the public's probably heard of none of these institutions.  (See IEEE resources on cybersecurity).  The public only hears about are the hacks themselves, and the typical mantra of "change your password" and "install anti-virus"!  Technologists should be our own advocates when it comes to best practices in actually securing legitimat, online use.  MITRE, for example, maintains the list of known malware but has only a limited capacity for informing the mass public about avoidance measures.  Technologists merely use their "disease coding" system (called CVE) much like doctors and insurers use to identify and catalog malware.  Technology can have more "doctors" and "vaccinations" for these malwares and we've made progress on getting cures out to prevent computer infections, such as integrating automated update and patching solutions.  The biggest producers of consumer software -- Microsoft, Apple, and Google -- (can) push these vaccinations to our laptops, smartphones, and tablets.

What technologists do not have is a computer immune system.  This is a critical need because anything online is under constant attack.  Securing technology has shifted from reactive to proactive because of the increased risks with the Internet of Things (IoT).  We seldom implement automated security systems that are on par with our more robust, biological immune systems.  Technologists might install some "skin" in the form of a firewall that protects the outer shell of technology, and we probably install a baby's "newborn white cells" in the form of immature anti-virus scanners, and hopefully we will throw in a basic "diary" that logs a glimpse of what computers are exposed to, but we don't implement mature, robust IT security.  This immature, computer immune bandaid is the reason websites are still hacked, your pictures stolen, and fraudulent purchases appear on your credits cards.  Technologists, however, have the potential to be more effective than human doctors in treating this disease.

Security (Mis)persception

As constant consumers of technology, we can be more informed and educated about modern IT security needs.  IT security had been, in my experience, the purview of computer networking teams instead of application or DevOps teams.  The upside to a preoccupation with network security is a relatively better defense at the lower levels of the OSI model, including the risks from physical access and operation.  The immunity gap is at the upper OSI layers where online applications sit.  I've been watching the MITRE/SANS reports on software security, in addition to the OSVDB (Open Software Vulnerability DataBase) and noticed these reports mimic some of the headlines of hacks.  Dangerous file uploads, session hijackings, SQL injection -- these headlines are in the top computer software "diseases".  OSVDB's trends upto 2014 give a quick view of vulnerabilities that mimic those listed in the MITRE/SANs report of 2011 (which itself changed little from the 2010 and 2009 reports).  This indicates to me that application vulnerabilities are a primary culprit in modern, IT insecurity.  Also, an analysis of software libraries in 2012 indicated that the increasing dependency on programming frameworks further exacerbates the "infection" beyond your own code or operating container.  When I subscribe to a security fix mailing list for one those big producers of consumer software, I notice a lot of libraries showing up that are dependencies of services and application containers.  So the elephant in the room is technologist's and consumer's (mis)perception of what is most at risk for modern technology.

I went back to the catalog of software vulnerabilities and reduced the CVE type lists to just the Top 10 "Cures" that will change our perceptions of security risks.  The list is devoid of what technologists typically discuss during security debates: denying remote access (via network firewalls), difficult passwords that rotate (via password policies), anti-virus scanning, etc.  Nada.  Instead, these vulnerabilities are found in higher layers of the OSI model, like the application itself or application server:
  1. use DB frameworks and static queries, do not make direct SQL calls or dynamic queries
  2. use jailboxes and programmatic interfaces, do not call the system directly
  3. validate all data input and verify buffers at build time, do not assume you'll get normal stuff
  4. do force document encoding and compliance, do not assume you'll get normal documents
  5. use authentication and authorization frameworks including roles, do not flatten or hard code credentials
  6. same as #5; mandatory access controls that deny everything by default are tedious and the most secure
  7. same as #6, do not embed passwords in code or configuration
  8. do use data encryption libraries, do not assume authentication or authorization will secure privacy
  9. same as #3 including file MIME type too, do not assume you'll get a normal file 
  10. do favor stateless sessions and verify state changes, do not trust stateful user sessions
To detect these top vulnerabilities in applications already running, proactive testing of the operating environment from which applications are running is needed.  In other words, we need more White Hats.  To prevent these vulnerabilities from appearing _before_ applications are brought online, we need due diligence during development.

Behavior Change

As I release my next application, I'm going to try a White Hat approach with due diligence.  Some tools to use during development are cross-referencing MITRE's mitigations and the above guideline Cures to see how often these vulnerabilities appear while I'm coding.  Here's the full MITRE/SANS List 2014:

RankScoreIDName
[1]93.8CWE-89Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
[2]83.3CWE-78Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
[3]79.0CWE-120Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
[4]77.7CWE-79Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
[5]76.9CWE-306Missing Authentication for Critical Function
[6]76.8CWE-862Missing Authorization
[7]75.0CWE-798Use of Hard-coded Credentials
[8]75.0CWE-311Missing Encryption of Sensitive Data
[9]74.0CWE-434Unrestricted Upload of File with Dangerous Type
[10]73.8CWE-807Reliance on Untrusted Inputs in a Security Decision
[11]73.1CWE-250Execution with Unnecessary Privileges
[12]70.1CWE-352Cross-Site Request Forgery (CSRF)
[13]69.3CWE-22Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
[14]68.5CWE-494Download of Code Without Integrity Check
[15]67.8CWE-863Incorrect Authorization
[16]66.0CWE-829Inclusion of Functionality from Untrusted Control Sphere
[17]65.5CWE-732Incorrect Permission Assignment for Critical Resource
[18]64.6CWE-676Use of Potentially Dangerous Function
[19]64.1CWE-327Use of a Broken or Risky Cryptographic Algorithm
[20]62.4CWE-131Incorrect Calculation of Buffer Size
[21]61.5CWE-307Improper Restriction of Excessive Authentication Attempts
[22]61.1CWE-601URL Redirection to Untrusted Site ('Open Redirect')
[23]61.0CWE-134Uncontrolled Format String
[24]60.3CWE-190Integer Overflow or Wraparound
[25]59.9CWE-759Use of a One-Way Hash without a Salt

Wednesday, December 3, 2014

Security: Validating Your Nightmare

When I take a trip on the Way, Way Back Machine, one tool that impressed me was validation of old school websites.  It was the W3C validator that gave me a point of reference to make improvements and ensure browser support.  The differentiator for this tool was the full weight of the Consortium behind it -- the institution that standardizes many web technologies -- and of course the tool was free.  This tool is still maintained though I seldom see new, hip "web designers" putting it on their pages.

Fast forward to the 21st century and there's a new(er) tool for security that I just bumped into.  CIS-CAT is a security validation tool that is backed by the Center for Information Security (CIS).  CIS gets a stamp from other organizations, like famous mainstay The SANS Institute.  Sadly their automated validator requires buying a hefty membership.  Evidently CIS hasn't gotten on board the Freemium bandwagon!

To their credit, CIS does release both the audit checklists and technical steps for verifying security compliance.  They call these security documents "Benchmarks" and these are *far* more valuable to the techie than abstract drivel that's usually posted online. I just downloaded a few CIS Benchmarks based on platform for free and am thinking it will be trivial to script these.

BTW: this Blogger page fails 4 W3C compliance checks :)


Google Freebie: PageSpeed

Google knows we've all shook a fist waiting for an awfully sluggish webpage to load in our browser despite a fast connection.  They've got this cool, free extension to Chrome called PageSpeed for web designers and developers.  The extension is a handy tool for easily fixing sluggishness that we've all encountered.

PageSpeed pointed against some webpage I loaded:


The extension is on the Google Store and details are at Google Developer's Speed site.

Google Analytics will track real time data of client requests against a website, given that their analytics are embedded.