HKBU IS WEEK–PROTECT YOUR WEBSITE AGAINST HACKINGDr. Ricci IEONG, CISSP, CISA, CISM, CEH, CCSK, CCSP, CCFP, ACE, GPEN, GIAC Advisory Board, ISSAP, ISSMP, ISO 27001LA, STAR Auditor
Principal Consultant, eWalker Consulting (HK) Ltd
Agenda• World of Web Applications• Threats to the World• Common Web Security Attack• OWASP Top 10 Attacks • Web Securing Best Practices
Web Applications in University• Web information environment• Mobile information environment• eLearning platforms (Moodle and Blackboard) • Student records and registration systems• University e-Library system• Email System• Web and file sharing servers• Assignment collection system• Research supporting systems• Students managed systems• …
Characteristics of Hacker-like Environment• Openness• Massive number of computer across the network• No-monitoring• Fast Internet connections• 24x7 available
World’s Biggest Data Breaches (Jan 2017)
http://www.informationisbeautiful.net/visualizations/worlds-biggest-data-breaches-hacks/
Attacks from Web Application varies• Threat action categories over time by percent of breaches and
percent of records
Source: Verizon “2014 Data Breach Investigations Report” and “2015 Data Breach Investigations Report”
2014 breaches, n=1598
Web Threats information from Symantec Vol 20 2015 report
• Other than seasonal type of web attacks, 6 out of Top 10 vulnerabilities were found to be related to SSL related vulnerabilities
• Others are• PHP information
disclosure vulnerability• XSS attack
• NB. Year 2014 records
Top 5 Zero-Day Vulnerabilities
Recently Published or Announced Vulnerabilities (in 2016 from McAfee)
Security Trend in HK (2016Q4)
Security Trend in HK (2016Q4)
Server related security events (Q4, 2016)• The number of server related security events increased from
4,139 to 9,025(increased by 118%) this quarter.• The domain that hosted the largest number of malware was
btjykjj.com. It hosted 543 or 11% of all malware hosting events. • WHOIS history showed that a year ago the domain was owned
by an organization called “Bao Tou Shi Jiu Yuan Qu Ke Xue Ji Shu Ju” which is the Chinese pinyin roughly translated to The Science and Technology Bureau of Jiu Yuen District, Bao TouCity (a city in inner Mongolia, China), which is a unit in the Chinese Government.
• It was discovered that the IP address resolved by this domain was responsible for six more malware hosting events. Among which, at least two of them were suspected to be expired legitimate domains.
Security Breach Affects Math Students in Purdue in 2010
List of data breaches and cyber attacks in January 2017
University Healthcare information breach (2017)• 7,445 patients notified of University Healthcare
information breach• University Healthcare officials became aware Jan. 17, of
an FBI and local law enforcement investigation into the unauthorized access, use and disclosure of personal information contained on the electronic systems of University Healthcare by an employee of Berkeley Medical Center in Martinsburg.
Princeton University becomes victim of MongoDB ransom attacks (2017)
Hilliard Bradley High School hacked, students’ information exposed (2017)
• Court documents state that a student at Hilliard Bradley High School hacked into a school computer and stole other students’ login information.
• In November, a staff member at Hilliard Bradley High School informed a school resource officer that a student hacked a school computer.
• The student was able to capture the private information and sent it to a Google Drive account using a program placed on a computer in the high school’s media center
University of Greenwich Hacked and Breached Again (2017)• The University of Greenwich has suffered its second data
breach of the year after students’ personal details were leaked online by a hacker, according to reports.
• The black hat appears to have compromised the university’s website and database via a simple SQL injection attack, Oren Yaakobi from security vendor Hacked-DB told the Evening Standard.
• This apparently enabled him to deface a web page and insert a link to the compromised data, hosted on the dark web.
• Yaakobi told the paper that over 21,000 email accounts and log-ins had been exposed, as well as personal information including full names and contact details, information on students with disabilities, and even a spreadsheet containing details of medical problems pertaining to some staff.
Universities: Prime Breach Targets (2015)
Feb 3, 2015
The types of breaches academic institutions are experiencing include hacker attacks utilizing malware, webcrawlers unintentionally accessing sensitive information, insiders leaking data and even the theft of computers.
SNHU still investigating database leak exposing over 140,000 records (2016)• Southern New Hampshire University (SNHU) says they're
still investigating how a database containing some student and class information was exposed to the public. The database was discovered by researcher Chris Vickery shortly before Christmas
• SNHU says the database was exposed by a third-party vendor (configuration errors), but they wouldn't name the vendor in question.
OWASP TOP 10 ISSUES
Distribution of web hacking categories• Web Hacking Incident Database for 2011 (WHID)
OWASP Top 10 Web Application Security Risk (2013 version)• Top 10 Web Application Security Risk 2013 version:
• A1: Injection• A2: Broken Authentication and Session Management• A3: Cross-site Scripting (XSS)• A4: Insecure Direct Object References• A5: Secure Misconfiguration• A6: Sensitive Data Exposure• A7: Missing Function Level Access Control• A8: Cross-site Request Forgery (CSRF)• A9: Using Components with Known Vulnerabilities• A10: Unvalidated Redirects and Forwards
Source: https://www.owasp.org/index.php/Top_10_2013
OWASP Top 10 Web Application Security Risk (Trend)
2007 versionA1 – Cross Site Scripting (XSS)
A2 – Injection Flaws
A3 – Malicious File Execution
A4 – Insecure Direct Object Reference
A5 – Cross Site Request Forgery (CSRF)
A6 – Information Leakage and Improper Error Handling
A7 – Broken Authenticationand Session Management
A8 – Insecure Cryptographic Storage
A9 – Insecure Communications
A10 – Failure to Restrict URL Access
2010 version
A1 – Injection
A2 – Cross Site Scripting
A3 – Broken Authentication and Session Management
A4 – Insecure Direct Object References
A5 – Cross Site Request Forgery (CSRF)
A6 – SecurityMisconfiguration
A7 – Insecure CryptographicStorage
A8 – Failure to Restrict URL Access
A9 – Insufficient Transport Layer Protection
A10 - Unvalidated Redirects and Forwards
New
2013 version
A1 – Injection
A2 – Broken Authentication and Session Management
A3 – Cross Site Scripting
A4 – Insecure Direct Object References
A5 – SecurityMisconfiguration
A6 – Sensitive Data Exposure
A7 – Missing Function Level Access Control
A8 – Cross Site Request Forgery (CSRF)
A9 – Using Components with Known Vulnerabilities
A10 - Unvalidated Redirects and Forwards
New
New
A2: Broken Authentication and Session Management
(Source: OWASP)
A4: Insecure Direct Object References
(Source: OWASP)
A9: Using Components with Known Vulnerabilities
(Source: OWASP)
A10: Unvalidated Redirects and Forwards
(Source: OWASP)
OWASP TOP 10 & COUNTERMEASURESA1 – Injection
A1: Injection
(Source: OWASP)
SQL Injection 101- However, external parties (attacker and black box pen
tester) may not know the exact SQL statement used in the application
- Question: How to find out a “correct” injection to the SQL statement?
- Possibilities:1. Trial and error!2. Testing some “magic” strings that usually works
• ‘ or ‘’=‘’; --• or 1=1;--• etc
3. By observing error messages returned by the applications
How to prevent?1. Hide the error message!
• Yes it may make the attack harder to perform à “delay” control• However, it is not impossible à blind SQL injection
2. Sanitizing user provided content• Filter out / escape special characters like single quotes, and etc, at
server side• You need to know the exact set of characters to be filtered out J• Whitelist approach is always better than blacklist approach
3. Parameterized SQL statement• Pre-build the SQL statement semantic structure before evaluating
the variables
Strategies for Validating User Input in PHP• Secure PHP’s Inputs by Turning Off Global Variables• Declare Variables• Allow Only Expected Input• Check Input Type, Length, and Format• Abstracting Type, Length, and Format Validation with PHP• Sanitize Values Passed to Other Systems (such as File
Paths, Names and URIs)• Testing the Input Validation
Strategies for handling SQL Injection in PHP• Do not trust input from client side• Do not connect to the database as superuser or as
database owner• Use always customized users with very limited privileges• Use prepared statements with bound variables• Use input validating functions in PHP such as character
type functions, settype, ctype_digit()• Use addslashes or other functions to filter out non
numeric user supplied value• Do not print out any database specific information• Use stored procedures or previously defined cursors to
abstract data access
Sanitize user input for MySQL (Example)• IMPORTANT NOTES: Use prepared statement whenever possible.• mysql_real_escape_string() prepends backslashes to the following
characters: \x00, \n, \r, \, ', " and \x1a, does not escape % and _.• deprecated as of PHP 5.5.0
• $user = mysql_fix_string($_POST['user']);$pass = mysql_fix_string($_POST['pass']);$query = "SELECT * FROM users WHERE user='$user' AND pass='$pass'";
• function mysql_fix_string($string) • {
• if (get_magic_quotes_gpc()) $string = stripslashes($string); • return mysql_real_escape_string($string);
• }
Preventing SQL injection attacks• Use database library such as PDO_MySQL or MySQLi to
prebuild statement structure.• $statement = $db->prepare("INSERT• INTO users (username, password)• VALUES (:username, :password)");• $statement->bindParam(':username', $clean['username']);• $statement->bindParam(':password', $clean['password']);• $statement->execute();
Prepared Statements and Stored Procedures• The query only needs to be parsed (or prepared) once,
but can be executed multiple times with the same or different parameters.
• The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur
Prepared Statements Input Query Examples
http://php.net/manual/en/pdo.prepared-statements.php
Prepared Statements for fetching data
Stored Procedure
Input Sanitization• Initialize an empty array in which to store filtered data.
After verifying that is valid, then can store it in this array:• $filters = array(
'name' => array('filter' =>FILTER_VALIDATE_REGEXP, 'options' => array('regexp' => '/^[a-z]+$/i')),
'age' => array('filter' => FILTER_VALIDATE_INT, 'options' => array('min_range' => 13))
);• $clean = filter_input_array(INPUT_POST, $filters);
• For other filter reference:• http://www.w3schools.com/php/php_ref_filter.asp
Coding Standard for Java (Java Rules from CERT) – Injection Attacks• Methods to prevent Injection Attacks
• Validation• Sanitization• Canonicalization and Normalization
Java-specific Safeguards from OWASP• PreparedStatements• CallableStatements (Stored Procedures)• Control error messages
Java PreparedStatements from OWASPPreparedStatement updateSales =
con.prepareStatement(“UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?”);
updateSales.setInt(1, 75);updateSales.setString(2, “Columbian”);updateSales.executeUpdate();
Java CallableStatements from OWASPCallableStatement cs = con.prepareCall(“{call
SHOW_SUPPLIERS}”);cs.setInt(1, 75);cs.setString(2, “Columbian”);ResultSet rs = cs.executeQuery();
Control Error Messages from OWASP• Error pages allow you to replace the default verbose JSP
error page• In web.xml, <error-page> signifies the section of the file
devoted to specifying error behavior• <error-code> or <exception-type> define the HTTP error code or
Java exception types to be handled• <location> defines the location of the resource to display in
response to the error
OWASP TOP 10 & COUNTERMEASURESA3 – Cross-Site Scripting
A3: Cross-site Scripting (XSS)
(Source: OWASP)
How to prevent?1. Golden rule: sanitizing all user provided content
• Filter out / escape special characters like single quotes, and etc• You need to know the exact set of characters to be filtered out J• Whitelist approach is always better than blacklist approach
• Verify the type of the value is a good idea
2. Minimize the impact of XSS• Do not store sensitive data in client side• Limit the access of user script to session cookies (setting the
HttpOnly flag)• Disable TRACE/TRACK HTTP method that can bypass the HttpOnly
restriction• Properly arrange the domain - cookies are restricted to domain only.
Separate sensitive & non-sensitive service into two domain• Set proper Cross-domain Security Policies
Same Origin Policy- An security feature implemented in modern browsers that
restrict communication of content from different domain- E.g.
- Cannot send XHR to page on other domain- Cannot access the cookie from another domain
- Usually use the URL to compare the “origin”- Protocol checks: https:// vs http://- Domain checks: example1.com vs example2.com- Host check: xxx.example.com vs yyy.example.com- Port check: xxx.example.com:80 vs xxx.example.com:8080
Strategies for handling XSS in PHP• Filter IN Encode OUT
• Sanitize All user-submitted inputs, including URIs, POST parameters and HTTP Headers.
• Encode output to escape HTML syntax meaning• Use a Proven XSS Filter on HTML Input• Test for protection against XSS
Prevent XSS by output encoding• Use htmlentities() to encode output to HTML safe format.
• htmlentities($string, ENT_QUOTES);• From: $string = "A 'quote' is <b>bold</b>";• To: A 'quote' is <b>bold</b>• Removing the syntax meaning of < and >.
• Many flags available to the function for different encoding needs.
• Default options is still vulnerable to XSS with single quotes only, must use with ENT_QUOTES flags.
Validating Input with Java from OWASP• Java regular expressions to validate input
• JSF 2.0 input field validator
• JSF 2.0 Bean Validation Framework
Output Encoding with Java from OWASP
• Use Struts output mechanisms such as style=“font-family: monospace;”><bean:write…>, or use the default JSTL escapeXML=“true” attribute in <c:out …>
• JSF output components filter output and escape dangerous characters as XHTML entities.
Output Encoding (Java) from OWASP
OWASP TOP 10 & COUNTERMEASURESA8 – Cross Site Request Forgery
A8: Cross-site Request Forgery (CSRF)
(Source: OWASP)
How to prevent?1. Configure proper Cross-domain Security Policies
2. Check the source of the requests on critical functions• HTTP REFER header
• HTTP ORIGIN header
3. Using HTTP POST to submit data add little bit difficulties in exploiting CSRF than using HTTP GET to submit data
Protect Against CSRF• Consider to use HTTP POST request rather than a GET request.• Append a form-specific token to important HTML forms
• <?php• $_SESSION[‘form-A-token'] =
$token=hash("sha512",mt_rand(0,mt_getrandmax()));• $_SESSION[' form-A-token_timestamp'] = time();• ?>
• <!– CSRF protected form -->• <form method="POST' action="/edit_photos.php'>• <input type="hidden' name="signature' value="<?php echo $_SESSION[‘form-
A-token']; ?>'/>• <input type="text' name="search' />• <input type="submit' />• </form>
• Reference: https://www.owasp.org/index.php/PHP_CSRF_Guard
GENERAL SECURING IN WEB SERVERS AND APPLICATIONS
Secure Your Web site encryption• In 2015, HKCERT detected that
25% of the web site has vulnerabilities• multiple known vulnerabilities
identified• POODLE• Heartbleed • FREAK
• SSL/TLS Configuration test• COMODO SSL Analyzer
• https://sslanalyzer.comodoca.com/• QUALYS SSL Server Test
• https://www.ssllabs.com/ssltest/• Symantec SSL Certificate Installation
Checker• https://cryptoreport.websecurity.syman
tec.com/checker/
Web Securing Checklist (from HKCERT)• Follow HKCERT website for latest updates• Change all default application passwords• Use strong password or two-step verification• Restrict access and protect web admin login page• Validate user supplied inputs in web applications• Remove all unused modules and application extensions• Separate the web and Database servers• Use web application firewall• Perform penetration testing and vulnerability scanning on
a regular basis• Consider code scanning for critical applications
Infrastructure Security (1)• Segregate Components via security controls
• Network segmentation, firewall rules, security groups (cloud)• Tired-architecture
• Web / application / database• Appropriate security zoning & access control
• Separate environments• Development / Testing / production• Proper access rights
• Components and libraries• Up-to-date• Hardened
Infrastructure Security (2)• Proper permission control:
• Default denied (i.e. whitelisting) to external servers• Integrity control
• Via authorized administrators or tools• Time source
• Synchronized to authenticated time source
INPUT VALIDATIONGuidelines on Secure Application Development
Input Validation (1)• Control against buffer overflows
• Boundary checks• Check before used
• Always use server side input validation• Consistent input validation practices• SQL enquires:
• Always use parameterized queries• Assist with sanitization
Input Validation (2)• Context-aware sanitization:
• SQL statements• LDAP queries• OS command / path• HTML / XML• HTTP headers / URL• Etc
• Be careful on WYSIWYG editors
Hexadecimal
Characters
0x00 NULL0x08 Back space0x09 TAB0x0a LF0x0d CR0x1a SUB0x25 %0x26 &0x3a :0x3b ;0x3d =
SENSITIVE DATA HANDLINGGuidelines on Secure Application Development
Sensitive Data Handling (1)• Sensitive data should not be stored on client side
• Cookies• HTML5 storage• Flash storage• Etc
• Disable client side caching on sensitive data• Connection to external systems:
• Authenticated • Encrypted
• Access to sensitive data should be logged
AUTHENTICATION, PASSWORD AND SESSION MANAGEMENTGuidelines on Secure Application Development
Authentication (1)• Implicit requirement on authentication except public pages• No pre-filled credentials
• This require passwords to be stored in reversible encryption or clear text which is explicitly prohibited
• Server-side enforced authentication controls• Fail securely to avoid unauthorized access• Authentication should be done over properly encrypted
links• Confidentiality• Integrity
Password (1)• Avoid the possibility of information enumeration via login,
password reset, forgot account functionalities• E.g. consistent error messages
• Randomly generated initial passwords / confirmation code• Complexity• Length
• Changing password must require old password• Forgot password feature do not reveal current password
Session Management (1)• Assign new user sessions on security context change
• Avoid Session Fixation• Protect Session ID and cookies
• TLS connections• HTTPOnly / Secure Flags
• Sufficient entropy for session ID• Invalidate session (server side) during logout• Session timeout after inactivity
Session Management (2)• Authorization done with centralized mechanism
• Default deny• Role-based access controls
• Better manageability• Privileges should be granted at minimal and needed basis• Explicit checks on privileges before action is conducted
• Whether the user is allowed to conduct to such action• Whether the user is allowed to conduct the action on target object
• CSRF protection• Easy and visible access to logout functionality
CRYPTOGRAPHYGuidelines on Secure Application Development
Cryptography (1)• Use only proven and up-to-date cryptography scheme
• Do NOT invent on your own• Ensure cryptographic functions failed securely• Sufficient random security tokens, keys, GUIDs
• Strong random number generators (RNG)• e.g. mt_rand() in PHP has weak entropy
• Secrets should be replaceable• No hardcode of secrets• Proper access controls and protection in place
Cryptography (2)• Use of suitable encrypted communication channels
• TLS 1.2 or above• NO more SSL!• Strong enough ciphers with strong keys (>112-bits)• Weak ciphers/crypto functions: RC4, MD5, SHA1
• Use of proper digital certificates• Signed with strong key and crypto schemes• Maintain chain of trust
• Proper encryption key handlings• No clear text storage• Erase in memory after use• Avoid storing keys in fixed memory location• Lock memory page for key storage / paging• Use hardware / OS provided key storage if available
SECURE BACKEND APIS AND SERVERGuidelines on Secure Application Development
Secure Backend APIs and Server (1)• Enforce strong server-side controls
• Client side data is untrusted• Proper authentication, authorization and session
management scheme in place for API• Secure application servers • Access controls to administrative functions• Securing REST services
• Authorized & authenticated• Avoid reply attacks• Quota and rate limited
Secure Backend APIs and Server (1)• Enforce HTTP security controls, e.g.:
• HSTS (HTTP Strict Transport Security)• Blocks unexpected methods• Proper encoding and content-type
• Consistent encoding between clients and servers
EXCEPTION MANAGEMENTGuidelines on Secure Application Development
Exception Management (1)• Avoid excessive information leaked to users via
exceptions• Record exception details on server side• Customized error pages
• With reference number to assist issue reporting by user if needed• Proper use of try-catch-finally block
• Consider having a top-level exception handler• Error handling for security controls and business logic
should deny access by default
PRIVACYGuidelines on Secure Application Development
Privacy (1)• Compliance to legislative and regulative requirements
• Personal data (Privacy) Ordinance (PDPO) for HK• Six Data Protection Principles
• Collection Purpose & Means• Lawful and fair
• Accuracy & Retention• Use
• Avoid logging• Security
• Encryption at rest and in transit• Openness
• Personal Information Collection Statements (PICS)• Data Access & Correction
USE OF 3RD PARTY LIBRARIES AND COMPONENTSGuidelines on Secure Application Development
Use of 3rd Party Libraries and Components (1)• Refer to “Guidelines on Use of Third Party Libraries in
Software Solution”• In general:
• Keep inventory of 3rd party libraries and components• Keep up-to-date• Ensure adequate support
• Internal• External
APPLICATION DEPLOYMENT AND DISTRIBUTIONGuidelines on Secure Application Development
Application Deployment and Distribution (1)• Keep inventory of deployed applications• Avoid test, debug, develop data / configuration in production
• And vise versa for data – masking if needed• Ensure local file system metadata are removed from production
• Thumbs.db• .DS_Store• .git• .svn
• Ensure update mechanism is secure• Files / codes from untrusted sources should be stored outside
web-root• with limited permissions• Should not be executed by applications
AUDITING AND REPORTINGGuidelines on Secure Application Development
Auditing and Reporting (1)• Protect audit logs
• Ensure integrity• Avoid unauthorized access
• Centralized logging facility in application• Centralized logging across applications is a plus if applicable
• Audit log should include:• User ID• Date/time of logon, log-off• Source location / other identities• Successful / failure system access attempts• Successful / failure data / resources access attempts
Auditing and Reporting (1)• Protect audit logs
• Ensure integrity• Avoid unauthorized access
• Centralized logging facility in application• Centralized logging across applications is a plus if applicable
• Audit log should include:• User ID• Date/time of logon, log-off• Source location / other identities• Successful / failure system access attempts• Successful / failure data / resources access attempts
• Details requirement should be defined and agreed with users depending on the nature of the system
Auditing and Reporting (2)• Don’t write confidential / privacy data to the log
• No passwords• No personal data• When unavoidable, mask or encrypt the data before written to log
file• Basic attributes to be included in log:
• Severity level• Timestamps in standard formats• Origin• Descriptions
• Use unique printable special characters as delimiter• Properly encode log data
Auditing and Reporting (3)• Archive log to safe location when retention
• Security of archiving channel• Access control• Encryption at storage?
• Separate log files by time frame• Depending on log volume, retention policy and storage• E.g. per day
MISCELLANEOUSGuidelines on Secure Application Development
Miscellaneous (1)• Take reference to industrial best practices
• Standards from well-established organizations:• OWASP• ENISA• NIST, etc
• Enforce strong segregation of duties• With proper permission controls
• Enforce flow control in application• Check for out-of-order, skipped tests• Rate limiting
Miscellaneous (2)• Avoid use of non-web standard (e.g. W3C) components, e.g.:
• Adobe Flash• Active-X• Silverlight• NACL (native client)• Java Applets
• Proper protection on mobile client functions, activities, indents• Exports, access controls
• Proper use of CAPTCHA• No client-side fixing• Invalidate code after each checks• Prefer using well-established and supported libraries
Q&A