Common PHP security attacks and workarounds

Source: Internet
Author: User
Tags csrf attack
This article is mainly to share with you common PHP security attacks and solutions to understand common PHP application Security threats, you can ensure that your PHP application is not vulnerable. Therefore, this article will list 6 common PHP security attacks, you are welcome to read and learn.

1. SQL injection

SQL injection is a malicious attack that affects normal SQL execution by entering SQL statements in form fields. Another is injected through the system () or EXEC () command, which has the same SQL injection mechanism, but only for shell commands.

    $username = $_post[' username '];02    $query = "SELECT * FROM auth where username = '". $username. "'"; 0 3    Echo $query,    $db = new mysqli (' localhost ', ' demo ', ' demo ', ' Demodemo ');    $result = $db->query ($    if ($result && $result->num_rows) {        "echo" <br/>logged in successfully ";    else {        <br/>login failed ";    

The above code, in the first line, does not filter or escape the user input value ($_post[' username '). So the query might fail or even corrupt the database, which depends on whether $username contains a transformation of your SQL statement to something else.

Prevent SQL injection

Options:

Use Mysql_real_escape_string () filter data to manually check if each data is the correct data type use preprocessing statements and bind variables

Using prepared pre-processing statements

Separating data and SQL logic preprocessing statements will automatically filter (e.g. escape) it as an encoding specification that can help new team members avoid encountering the above problems
    $query = ' Select Name, district from city where Countrycode=? '; 0 2    if ($stmt = $db->prepare ($query))        $countrycode = ' HK '        , $stmt->bind_param ("s", $ CountryCode);        $stmt->execute (),        $stmt->bind_result ($name, $district); while        ($stmt ($stmt->fetch ()) {            <br echo $name. ', '. $district, '            echo '/> ';        }12        $stmt->close ();    

2. XSS attack

XSS (cross-site scripting attacks) is an attack in which users enter some data into your website, which includes client-side scripting (usually JavaScript). If you do not filter the output data to another Web page, this script will be executed.

Receive user-submitted text content

    <?php02    if (file_exists (' comments ')) {        $comments = get_saved_contents_from_file (' comments '); 04    } else {        $comments = ',    }07    if (isset ($_post[' comment ')) {        $comments. = ' <BR/ > '. $_post[' comment '];10        save_contents_to_file (' comments ', $comments);    }12    > Output to (another) User 1    <form action= ' xss.php ' method= ' POST ' >2    Enter your comments here: <br/>3 <textarea    name= ' Comment ' ></textarea> <br/>4    <input type= ' Submit ' value= ' Post comment '/>5    </form >

What's going to happen?

Annoying pop-up windows refresh or redirect corrupted Web page or form stealing Cookieajax (XMLHttpRequest)

Prevent XSS attacks: To prevent XSS attacks, use PHP's Htmlentities () function to filter and then output to the browser. The basic usage of htmlentities () is simple, but there are many advanced controls, see the XSS Quick Check table.

3, Session fixed

Session security, suppose a phpsessid is hard to guess. However, PHP can accept a session ID via a cookie or URL. Thus, spoofing a victim can use a specific (or other) session ID or phishing attack.

4. Meeting Capture and hijacking

This is the same idea as session pinning, however, it involves stealing the session ID. If the session ID is stored in a cookie, the attacker can steal through XSS and JavaScript. If the session ID is included on the URL, it can also be obtained by sniffing or from the proxy server.

Prevent session capture and hijacking

Update ID If you use a session, make sure that the user uses SSL

5. Cross-site request forgery (CSRF)

A csrf attack is a request made by a page that looks like a trusted user of the site, but not intentionally. It has a number of variants, such as the following example:

1    ![] (http://example.com/single_click_to_buy.php?user_id=123&item=12345)

Prevent cross-site request forgery

In general, make sure that users come from your form and match every form that you send out. There are two points to be sure to remember:

Use appropriate security measures for user sessions, such as updating IDs for each session and using SSL for the user. Generate another one-time token and embed it in the form, save it in the session (a session variable), and check it on commit.

6. Code Injection

Code injection is caused by the processing of invalid data by using a computer vulnerability. The problem is that when you accidentally execute arbitrary code, it is usually contained by a file. Poorly written code can allow a remote file to be included and executed. Many PHP functions, such as require, can contain URLs or filenames, for example:

    <form>choose theme:02        <select name = theme>03            <option value = blue>blue</option >04            <option value = green>green</option>05            <option value = red>red</option>06        </select>07        <input type = submit>08    </form>09    <?php10        if ($theme) {11            require ($theme. TXT ');        }13    ?>

In the example above, a file that begins with "http://" is passed as part of a file name or file name entered by the user.

Prevent Code injection

Filter user Input set disable Allow_url_fopen and Allow_url_include in php.ini. This disables the remote file for Require/include/fopen.

Other general principles

    1. Do not rely on server configuration to protect your app, especially when your Web server/PHP is managed by your ISP, or when your site may be migrated/ Deploy elsewhere and migrate/deploy somewhere else in the future.  Embed security-aware checks/logic (HTML, JavaScript, PHP, and so on) in your site code.

    2. Design a server-side security script:
      -for example, using single-line execution-point authentication and data cleansing
      -for example, embedding a PHP function/file on all security-sensitive pages to handle all login/security logic checks

    3. Make sure that your code is updated and that you have the latest patches.

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.