Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Validation. 2 Objective : To ensure that the application is robust against all forms of input data, whether obtained from the user, infrastructure,

Similar presentations


Presentation on theme: "Data Validation. 2 Objective : To ensure that the application is robust against all forms of input data, whether obtained from the user, infrastructure,"— Presentation transcript:

1 Data Validation

2 2 Objective : To ensure that the application is robust against all forms of input data, whether obtained from the user, infrastructure, external entities or database systems. Objective : To ensure that the application is robust against all forms of input data, whether obtained from the user, infrastructure, external entities or database systems.

3 3 Data Validation The most common web application security weakness is the failure to properly validate input from the client or environment. This weakness leads to almost all of the major vulnerabilities in applications, such as XSS, SQL Injection The most common web application security weakness is the failure to properly validate input from the client or environment. This weakness leads to almost all of the major vulnerabilities in applications, such as XSS, SQL Injection Data from the client should never be trusted for the client has every possibility to tamper with the data. Data from the client should never be trusted for the client has every possibility to tamper with the data.

4 4 Data Validation Data Validation Strategies : There are four strategies for validating data, and they should be used in this order: Data Validation Strategies : There are four strategies for validating data, and they should be used in this order: Accept known good Accept known good Reject known bad Reject known bad Sanitize with Whitelist Sanitize with Whitelist Sanitize with Blacklist Sanitize with Blacklist

5 5 1. Accept known good This strategy is also known as "whitelist" or "positive" validation. The idea is that you should check that the data is one of a set of tightly constrained known good values. Any data that doesn't match should be rejected. Data should be: This strategy is also known as "whitelist" or "positive" validation. The idea is that you should check that the data is one of a set of tightly constrained known good values. Any data that doesn't match should be rejected. Data should be: Strongly typed at all times Strongly typed at all times Length checked and fields length minimized Length checked and fields length minimized Range checked if a numeric Range checked if a numeric Unsigned unless required to be signed Unsigned unless required to be signed Syntax or grammar should be checked prior to first use or inspection Syntax or grammar should be checked prior to first use or inspection If you expect a postcode, validate for a postcode (type, length and syntax) If you expect a postcode, validate for a postcode (type, length and syntax)

6 6 2. Reject known bad This strategy, also known as "negative" or "blacklist" validation is a weak alternative to positive validation. Essentially, if you don't expect to see characters such as %3f or JavaScript or similar, reject strings containing them. This strategy, also known as "negative" or "blacklist" validation is a weak alternative to positive validation. Essentially, if you don't expect to see characters such as %3f or JavaScript or similar, reject strings containing them. This is a dangerous strategy, because the set of possible bad data is potentially infinite. Adopting this strategy means that you will have to maintain the list of "known bad" characters and patterns forever, and you will by definition have incomplete protection. This is a dangerous strategy, because the set of possible bad data is potentially infinite. Adopting this strategy means that you will have to maintain the list of "known bad" characters and patterns forever, and you will by definition have incomplete protection.

7 7 3. Sanitize with Whitelist Any characters which are not part of an approved list can be removed, encoded or replaced. Any characters which are not part of an approved list can be removed, encoded or replaced. Here are some examples: Here are some examples: If you expect a phone number, you can strip out all non-digit characters. Thus, "(555)123-1234“ or "555.123.1234“. All can be converted to 5551231234. If you expect a phone number, you can strip out all non-digit characters. Thus, "(555)123-1234“ or "555.123.1234“. All can be converted to 5551231234. Note that you should proceed to validate the resulting numbers as well. As you see, this is not only beneficial for security, but it also allows you to accept and use a wider range of valid user input. Note that you should proceed to validate the resulting numbers as well. As you see, this is not only beneficial for security, but it also allows you to accept and use a wider range of valid user input.

8 8 4. Sanitize with Blacklist Eliminate or translate characters (such as to HTML entities or to remove quotes) in an effort to make the input "safe". Eliminate or translate characters (such as to HTML entities or to remove quotes) in an effort to make the input "safe". Eg., Eg.,

9 9Security PHP & Security PHP keeps on growing as a language, making headway into enterprise and corporate markets. PHP keeps on growing as a language, making headway into enterprise and corporate markets. Consequently PHP applications often end up working with sensitive data. Consequently PHP applications often end up working with sensitive data. Unauthorized access to this data is unacceptable. Unauthorized access to this data is unacceptable. To prevent problems a secure design is needed. To prevent problems a secure design is needed.

10 10Security Input Validation One of the key concepts you must accept is that user input is unreliable and not to be trusted. One of the key concepts you must accept is that user input is unreliable and not to be trusted. Partially lost in transmission between server & client. Partially lost in transmission between server & client. Corrupted by some in-between process. Corrupted by some in-between process. Modified by the user in an unexpected manner. Modified by the user in an unexpected manner. Intentional attempt to gain unauthorized access or to crash the application. Intentional attempt to gain unauthorized access or to crash the application. Which is why it is absolutely essential to validate any user input before use. Which is why it is absolutely essential to validate any user input before use.

11 11Security Accessing Input Data As of PHP 4.1, there are a series of super-globals that offer very simple access to the input data. As of PHP 4.1, there are a series of super-globals that offer very simple access to the input data. $_GET – data from get requests. $_GET – data from get requests. $_POST – post request data. $_POST – post request data. $_COOKIE – cookie information. $_COOKIE – cookie information. $_FILES – uploaded file data. $_FILES – uploaded file data. $_SERVER – server data $_SERVER – server data $_ENV – environment variables $_ENV – environment variables $_REQUEST – combination of GET/POST/COOKIE $_REQUEST – combination of GET/POST/COOKIE

12 12Security Register Globals Arguably the most common source of vulnerabilities in PHP applications. Arguably the most common source of vulnerabilities in PHP applications. Any input parameters are translated to variables. Any input parameters are translated to variables. ?foo=bar >> $foo = “bar”; ?foo=bar >> $foo = “bar”; No way to determine the input source. No way to determine the input source. Prioritized sources like cookies can overwrite GET values. Prioritized sources like cookies can overwrite GET values. Un-initialized variables can be “injected” via user inputs. Un-initialized variables can be “injected” via user inputs.

13 13Security Register Globals if (authenticated_user()) { $authorized = true; } if ($authorized) { include '/highly/sensitive/data.php'; } Because $authorized is left un-initialized if user authentication fails, an attacker could access privileged data by simply passing the value via GET. http://example.com/script.php?authorized=1

14 14Security Solutions To Register Globals Disable register_globals in PHP.ini. Disable register_globals in PHP.ini. Already done by default as of PHP 4.2.0 Already done by default as of PHP 4.2.0 Code with error_reporting set to E_ALL. Code with error_reporting set to E_ALL. Allows you to see warnings about the use of un-initialized variables. Allows you to see warnings about the use of un-initialized variables.

15 15Security Validating Strings PHP comes with a ctype, extension that offers a very quick mechanism for validating string content. PHP comes with a ctype, extension that offers a very quick mechanism for validating string content. if (!ctype_alnum($_GET['login'])) { echo "Only A-Za-z0-9 are allowed."; } if (!ctype_alpha($_GET['captcha'])) { echo "Only A-Za-z are allowed."; } if (!ctype_xdigit($_GET['color'])) { echo "Only hexadecimal values are allowed"; }

16 16Security XSS Cross Site Scripting (XSS) is a situation where by attacker injects HTML code, which is then displayed on the page without further validation. Cross Site Scripting (XSS) is a situation where by attacker injects HTML code, which is then displayed on the page without further validation. Can lead to embarrassment. Can lead to embarrassment. Session take-over. Session take-over. Password theft. Password theft. User tracking by 3 rd parties. User tracking by 3 rd parties.

17 17Security Preventing XSS Prevention of XSS is as simple as filtering input data via one of the following: Prevention of XSS is as simple as filtering input data via one of the following: htmlspecialchars() htmlspecialchars() Encodes ‘, “,, & Encodes ‘, “,, & Eg (& (ampersand) becomes &) Eg (& (ampersand) becomes &) htmlentities() htmlentities() Convert anything that there is HTML entity for. Convert anything that there is HTML entity for. Eg (&nbsp => newline ;%amp => &) Eg (&nbsp => newline ;%amp => &) strip_tags() strip_tags() Strips anything that resembles HTML tag. Strips anything that resembles HTML tag. echo strip_tags("Hello world! "); echo strip_tags("Hello world! "); Output (Hello world!) Output (Hello world!)

18 18Security Preventing XSS $str = strip_tags($_POST['message']); // encode any foreign & special chars $str = htmlentities($str); // maintain new lines, by converting them to echo nl2br($str); // strip tags can be told to "keep" certain tags $str = strip_tags($_POST['message'], ' '); $str = htmlentities($str); echo nl2br($str); Tag allowances in strip_tags() are dangerous, because attributes of those tags are not being validated in any way. Tag allowances in strip_tags() are dangerous, because attributes of those tags are not being validated in any way.

19 19Security Tag Allowance Problems TAKE UP ENTIRE SCREEN Lot's of text Let's track users

20 20Security SQL Injection SQL injection is similar to XSS, in the fact that not validated data is being used. But in this case this data is passed to the database. SQL injection is similar to XSS, in the fact that not validated data is being used. But in this case this data is passed to the database. Arbitrary query execution Arbitrary query execution Removal of data. Removal of data. Modification of existing values. Modification of existing values. Denial of service. Denial of service. Arbitrary data injection. Arbitrary data injection.

21 21Security SQL Escaping If database interface extension offers dedicated escaping functions, USE THEM! If database interface extension offers dedicated escaping functions, USE THEM! MySQL MySQL mysql_escape_string() mysql_escape_string() mysql_real_escape_string() mysql_real_escape_string() PostgreSQL PostgreSQL pg_escape_string() pg_escape_string() pg_escape_bytea() pg_escape_bytea() SQLite SQLite sqlite_escape_string() sqlite_escape_string()

22 22Security Solution DO NOT PLACE USER INPUT INTO EXECUTABLE STATEMENTS!!

23 23Security Error Reporting By default PHP will print all errors to screen, startling your users and in some cases disclosing privileged information. By default PHP will print all errors to screen, startling your users and in some cases disclosing privileged information. File paths. File paths. Un-initialized variables. Un-initialized variables. Sensitive function arguments such as passwords. Sensitive function arguments such as passwords. At the same time, disabling error reporting would make bug tracking near impossible. At the same time, disabling error reporting would make bug tracking near impossible.

24 24Security Solution? This problem can be solved by disabling displaying of error messages to screen This problem can be solved by disabling displaying of error messages to screen ini_set(“display_errors”, FALSE); And enabling logging of errors And enabling logging of errors ini_set(“log_errors”, TRUE); to a file to a file ini_set(“error_log”, “/var/log/php.log”); or to system central error tracking facility or to system central error tracking facility ini_set(“error_log”, “syslog”);

25 25Security Session Security Sessions are a common tool for user tracking across a web site. Sessions are a common tool for user tracking across a web site. For the duration of a visit, the session is effectively the user’s identity. For the duration of a visit, the session is effectively the user’s identity. If an active session can be obtained by 3 rd party, it can assume the identify of the user who’s session was compromised. If an active session can be obtained by 3 rd party, it can assume the identify of the user who’s session was compromised.

26 26Security Session Fixation Session fixation is an attack designed to hard- code the session id to a known value. Session fixation is an attack designed to hard- code the session id to a known value. If successful the attack simply sends the known session id and assumes the identity of the victim. If successful the attack simply sends the known session id and assumes the identity of the victim.

27 27Security Exploit A most common form of an exploit involves having the user click on a link that has a session id embedded into it. A most common form of an exploit involves having the user click on a link that has a session id embedded into it. If the user does no have an existing session their session id will be “hackme”. If the user does no have an existing session their session id will be “hackme”. <a href= “http://php.net/manual/?PHPSESSID=hackme”> PHP.net Manual

28 28Security Securing Against Session Fixation To avoid this problem you should regenerate the session id on any privilege (Ex. Login) change. To avoid this problem you should regenerate the session id on any privilege (Ex. Login) change. <?php session_start(); // some login code if ($login_ok) { // user logging in session_regenerate_id(); // make new session id } ?>

29 29Security Shared Hosting Most PHP applications run in shared environments where all users “share” the same web server instances. Most PHP applications run in shared environments where all users “share” the same web server instances. This means that all files that are involved in serving content must be accessible to the web server (world readable). This means that all files that are involved in serving content must be accessible to the web server (world readable). Consequently it means that any user could read the content of files of all other users. Consequently it means that any user could read the content of files of all other users.

30 30Security The PHP Solution PHP’s solution to this problem are 2 INI directives. PHP’s solution to this problem are 2 INI directives. open_basedir – limits file access to one or more specified directories. open_basedir – limits file access to one or more specified directories. Relatively Efficient. Relatively Efficient. Uncomplicated. Uncomplicated. safe_mode – limits file access based on uid/gid of running script and file to be accessed. safe_mode – limits file access based on uid/gid of running script and file to be accessed. Slow and complex approach. Slow and complex approach. Can be bypassed with little effort. Can be bypassed with little effort.

31 31Security Questions


Download ppt "Data Validation. 2 Objective : To ensure that the application is robust against all forms of input data, whether obtained from the user, infrastructure,"

Similar presentations


Ads by Google