Six common PHP security attacks

Source: Internet
Author: User
Tags csrf attack

Understanding common security threats to PHP applications ensures that your PHP applications are not under attack. Therefore, this article will list six common PHP security attacks. You are welcome to read and learn.

1. SQL Injection

SQL injection is a malicious attack. Users can input SQL statements in form fields to affect normal SQL Execution. Another method is injection through the system () or exec () command. It has the same SQL Injection mechanism, but only for shell commands.

$username = $_POST['username'];$query = "select * from auth where username = '".$username."'";echo $query;$db = new mysqli('localhost', 'demo', ‘demo', ‘demodemo');$result = $db->query($query);if ($result && $result->num_rows) {    echo "<br />Logged in successfully";} else {    echo "<br />Login failed";}

The above Code does not filter or escape user input values ($ _ POST ['username']) in the first line. Therefore, the query may fail or even damage the database. It depends on whether $ username contains your SQL statement to be transformed into something else.

Prevent SQL Injection

Option:

  • Use mysql_real_escape_string () to filter data
  • Manually check whether each data is of the correct data type
  • Use pre-processing statements and bind variables

Use prepared pre-processing statements
  • Separate data from SQL Logic
  • The pre-processing statement will be automatically filtered (for example, escape)
  • Using it as a code specification can help new people in the team avoid the above problems
$query = 'select name, district from city where countrycode=?';if ($stmt = $db->prepare($query) ){    $countrycode = 'hk';    $stmt->bind_param("s", $countrycode);      $stmt->execute();    $stmt->bind_result($name, $district);    while ( $stmt ($stmt->fetch() ){        echo $name.', '.$district;        echo '<br />';    }    $stmt->close();}
2. XSS attacks

XSS (Cross-Site Scripting) is an attack that allows users to input some data to your website, including client scripts (usually JavaScript ). If you do not filter the output data to another web page, the script will be executed.

Receive text content submitted by the user
<?phpif (file_exists('comments')) {    $comments = get_saved_contents_from_file('comments');} else {    $comments = '';}if (isset($_POST['comment'])) {    $comments .= '<br />' . $_POST['comment'];    save_contents_to_file('comments', $comments);}>
Output content to (another) User
<form action='xss.php' method='POST'>Enter your comments here: <br /><textarea name='comment'></textarea> <br /><input type='submit' value='Post comment' /></form>

What will happen?
  • Annoying pop-up window
  • Refresh or redirect
  • Damage webpages or forms
  • Cookie Theft
  • AJAX (XMLHttpRequest)


Prevent XSS attacks

To prevent XSS attacks, use the htmlentities () function of PHP to filter and output the data to the browser. The basic usage of htmlentities () is very simple, but there are also many advanced controls, see XSS quick query table.

3. Fixed sessions

Session Security. Suppose a phpsessid is hard to guess. However, PHP can accept a session ID through a Cookie or URL. Therefore, spoofing a victim can use a specific (or other) session ID or phishing attack.

4. Meeting capturing and hijacking

This is the same idea as session fixation. However, it involves stealing session IDs. If session IDs are stored in cookies, attackers can steal them through XSS and JavaScript. If the session ID is included in the URL, it can also be obtained through sniffing or from the proxy server.

Prevent session capture and hijacking

  • Update ID
  • If you use a session, make sure that you use SSL


5. Cross-Site Request Forgery (CSRF)

A csrf attack refers to a request sent by a page. It looks like a trusted user of a website, but it is not intentional. It has many variants, such as the following example:


Prevents Cross-Site Request Forgery 

In general, make sure that the user comes from your form and matches every form you send. There are 2.1 things to remember:
  1. Use appropriate security measures for user sessions, such as updating the id of each session and using SSL for the user.
  2. Generate another one-time token, embed it into the form, save it in the Session (a session variable), and check it when submitting.


6. Code Injection

Code injection uses computer vulnerabilities to process invalid data. The problem is that when you accidentally execute arbitrary code, it is usually contained in a file. Poorly written code allows a remote file to be included and executed. For example, many PHP functions, such as require, can contain URLs or file names, for example:

<form>Choose theme:    <select name = theme>        <option value = blue>Blue</option>        <option value = green>Green</option>        <option value = red>Red</option>    </select>    <input type = submit></form><?php    if($theme) {        require($theme.'.txt');    }?>

In the preceding example, a file name or a part of the file name entered by the user is passed to include a file starting with "http.

Prevent code injection

  • Filter user input
  • Disable allow_url_fopen and allow_url_include in php. ini. This will disable remote files of require/include/fopen.
Other general principles

1. do not rely on server configurations to protect your applications, especially when your web server/PHP is managed by your ISP, or when your website may be migrated/deployed elsewhere, migrate/deploy data from other locations in the future. Embed security-aware inspection/logic (HTML, JavaScript, PHP, etc.) in website code ).
2. design the server-side security script:
-For example, use a single row for single-point authentication and data cleanup
-For example, a PHP function/file is embedded on all security-sensitive pages to process all logon/security logic checks.
3. Make sure your code is updated with the latest patch.

OSChina Translation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.