Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP / MySQL forms: escaping, sanitizing, hashing.... where do I even start?

I'm usually pretty resourceful about finding information on my own, but when it comes to this subject, it's really daunting the sheer amount of stuff there is out there. I'm getting a bit of information overload.

I've found dozens of articles on individual security topics, but I can't get a sense of the bigger picture and how it all comes together in practice.

I need to see a bird's-eye roadmap. Take this hypothetical example:

A Simple Hypothetical "Comments" Section:

  • Sign up: create a password/username combo that is to be stored safely in a MySQL table.

  • Log in.

  • Leave a comment.

What would be a "security roadmap" to follow on this most basic case?

It doesn't help that every tutorial and PHP book on the planet uses the MySQL extensions, which, if I understand correctly, is a bad idea?

like image 204
o_o_o-- Avatar asked Sep 04 '12 05:09

o_o_o--


People also ask

Is sanitization compulsory in PHP?

Therefore, to safeguard the database from hackers, it is necessary to sanitize and filter the user entered data before sending it to the database.


2 Answers

A. In general…

  1. I’m assuming here that the programmer is not also the server administrator, and that the server admin more or less knows how to configure LAMP correctly and securely by default.

    Of course, if necessary, a programmer can override most PHP settings in a custom php.ini file located in the web root.

  2. Use an MVC framework.

    I use CakePHP. The framework itself goes a long way to ensure fundamentally sound and secure coding practices.

B. Incoming data…

  1. Sanitize and validate all data contained in $_GET, $_POST, $_COOKIE, and $_REQUEST before programmatically manipulating the data.

  2. SQL Injection

    Definition: Code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed.

    Prevention: Parameterised queries using a library such as mysqli or PDO. See the OWASP SQL Injection cheat sheet (string escaping functions like mysql_real_escape_string are not recommended)

  3. Cross Site Scripting (XSS)

    Definition: Security vulnerability typically found in web applications that allows code injection by malicious web users into the web pages viewed by other users. Examples of such code include client-side scripts (i.e., JavaScript).

    Prevention: Context-dependent output escaping and encoding. See the OWASP XSS prevention cheat sheet.

C. Browser requests…

  1. Cross Site Request Forgery (CSRF)

    Definition: Type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts. Unlike cross-site scripting (XSS), which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user's browser.

    Prevention: Generate a unique “token”, typically when a browser session starts. Pass the token in all POST and GET requests. Following the POST/GET action, check for the existence of the token in the session and then confirm the token sent by POST/GET is identical to the token stored in the session. (An MVC framework like CakePHP makes this relatively easy to implement uniformly throughout your application.)

D. Sessions…

  1. Destroy session data when killing a session

    After a session is complete (”logout”), destroy its data and don’t just clear the cookie (a malicious user could otherwise just re-instate the cookie and use the session again). Unset all indexes in $_SESSION by assigning it to an empty array.

  2. Store sessions as files above the web root or in a database

    The default path for saving sessions on the server can be hijacked -- especially in a shared hosting environment.

E. Passwords…

  1. Enforce the selection of strong passwords

    • Require numbers, symbols, upper and lowercase letters in passwords

    • Password length should be around 12 to 14 characters

  2. Hash and Salt all passwords

    Do not use sha1(), md5() or hash() to hash passwords. They're not designed for this. You will want to use a function like bcrypt or PBDFK2. There's some really good suggestions on this question. Your salt value should be completely random, and stored in the database (it's not really a secret). An additional secret value (generally called "pepper") can be stored in your application and prepended to passwords before using bcrypt, but it's not clear how much security this really adds.

F. In a custom php.ini located in web root…

  1. Disable register_globals

    Prevention: register_globals = Off

  2. Disable magic quotes

    Prevention: magic_quotes_gpc = Off

  3. Disable error reporting

    Prevention: display_errors = Off

  4. Enable error logging and save log file to a directory above web root

    Prevention:

    log_errors = On; 
    ignore_repeated_errors = On; 
    html_errors = Off; 
    error_log = /path/above/webroot/logs/php_error_log
    
  5. Store session data inside a directory above web root

    Prevention: session.save_path = /path/above/webroot/sessions

G. In a .htaccess file located in web root…

  1. Disable directory listings site-wide

    Prevention: Options -Indexes

H. Valuable/Sensitive files…

  1. Prevent unauthorized access/downloads by storing such files above the web root

    This includes site administration/members-only sections and site/database configuration files!!

  2. Use an intermediary script to serve the files inline or as an attachment

  3. Keep your scripts(WordPress, PHPMyAdmin, etc.) updated.

  4. Only allow access to PHPMyAdmin when you are using it. This prevents people from being able to use zero-day exploits on your install.

I. Uploaded files…

  1. Validate file name stored in $_FILES before using it for any kind of data manipulation

  2. Be aware that the provided mime type can be spoofed or otherwise wrong

  3. Move all user-uploaded files to a directory above web root!!!

  4. Don’t execute/serve uploaded files with include()

  5. Try to not serve files with content types of “application/octet-stream,” “application/unknown,” or “plain/text”

J. Misc…

  1. All “utility” files/programs in the web root created and used by the developer during the development of a site/application, that are not intended or required to be accessed by future site users, or otherwise pose some kind of security risk, should be removed when the site goes live.

    For example, this includes a phpinfo.php file (a files that prints the results of phpinfo()), database utility scripts, etc.

like image 188
shail Avatar answered Oct 11 '22 16:10

shail


Well, to make it safe, first start with constructing the mysql side before moving to the server side programming (e.g. php). Create stored procedures, views, prepared statements.. transactions perhaps. They are their to make the application more secure..too bad php programmers dont use them often.

Then when you come to the server side programming, use pdo (I like it more than mysqli), it enables you to bind parameters (which is a safe strategy used in asp.net too).

You could also use validation strategies.. to see if input is an email, a credit card..etc that would give you a white list of things to expect (building a black list is a less secure idea..I remember reading this from some hacking book).

Escaping and filtering can be used depending on what you want, on passwords you may want to strip tags, but with comments you might not..

Good luck!

like image 22
Dmitry Makovetskiyd Avatar answered Oct 11 '22 16:10

Dmitry Makovetskiyd