国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial PHP database security - SQL injection and preventive measures

PHP database security - SQL injection and preventive measures

Nov 22, 2016 am 10:45 AM
php php database

Many web developers don’t realize that SQL queries can be tampered with, so they treat SQL queries as trusted commands. Little did they know that SQL queries could bypass access controls, thereby bypassing authentication and permission checks. What's more, it's possible to run host operating system level commands via SQL queries.

Direct SQL command injection is a technique commonly used by attackers to create or modify existing SQL statements to obtain hidden data, overwrite key values, or even execute database host operating system commands. This is accomplished by the application taking user input and combining it with static parameters into an SQL query. Some real examples will be given below.

Due to the lack of validation of the entered data and using a superuser or other database account with the authority to create new users to connect, the attacker can create a new superuser in the database.

Example #1 A piece of code that implements paging display of data...can also be used to create a superuser (PostgreSQL system).

<?php
    $offset = $argv[0]; // 注意,沒有輸入驗證!
    $query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
    $result = pg_query($conn, $query);
?>

General users will click on the "previous page" and "next page" links where $offset has been binned. The original code only thinks that $offset is a numerical value. However, if someone tries to urlencode() the following statement and then add it to the URL:

0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select &#39;crack&#39;, usesysid, &#39;t&#39;,&#39;t&#39;,&#39;crack&#39;
    from pg_shadow where usename=&#39;postgres&#39;;
--

then he can create a super user. Note that 0; is just to provide a correct offset to complete the original query so that it does not make errors.

Note:

-- is the comment mark of SQL, which can generally be used to tell the SQL interpreter to ignore the following statements.

A possible way to get the password is by targeting the page that displays the search results. All the attacker has to do is find out which variables were submitted for SQL statements and mishandled them. Such variables are usually used in conditional statements in SELECT queries, such as WHERE, ORDER BY, LIMIT and OFFSET. If the database supports the UNION construct, an attacker may also append a complete SQL query to the original statement to obtain the password from an arbitrary data table. Therefore, it is important to encrypt the password field.

Example #2 Display article... and some passwords (any database system)

<?php
    $query = "SELECT id, name, inserted, size FROM products
        WHERE size = &#39;$size&#39;
        ORDER BY $order LIMIT $limit, $offset;";
    $result = odbc_exec($conn, $query);
?>

You can add another SELECT query to the original query to get the passwords:

&#39;
union select &#39;1&#39;, concat(uname||&#39;-&#39;||passwd) as name, &#39;1971-01-01&#39;, &#39;0&#39; from usertable;
--

If the above statement (using ' and --) If it is added to any variable in $query, then it will be troublesome.

UPDATE in SQL is also vulnerable. This query may also be inserted or appended to another complete request as in the example above. But attackers prefer to target the SET clause so they can change some data in the table. In this case, you must know the structure of the database in order to modify the query successfully. Fields can be guessed based on variable names on the form, or brute force cracked. There are not many ways to name the fields that store usernames and passwords.

Example #3 From resetting password... to gaining more permissions (any database system)

<?php
    $query = "UPDATE usertable SET pwd=&#39;$pwd&#39; WHERE uid=&#39;$uid&#39;;";
?>

But malicious users will submit ' or uid like '%admin%'; -- as the value of the variable to $uid Change the admin password, or submit the value of $pwd to "hehehe', admin='yes', trusted=100" (there is a space after it) to obtain more permissions. By doing this, the query actually becomes:

<?php
    // $uid == &#39; or uid like&#39;%admin%&#39;; --
    $query = "UPDATE usertable SET pwd=&#39;...&#39; WHERE uid=&#39;&#39; or uid like &#39;%admin%&#39;; --";
    // $pwd == "hehehe&#39;, admin=&#39;yes&#39;, trusted=100 "
    $query = "UPDATE usertable SET pwd=&#39;hehehe&#39;, admin=&#39;yes&#39;, trusted=100 WHERE
        ...;";
?>

The following horrific example will demonstrate how to execute system commands on some databases.

Example #4 Attack the operating system of the host where the database is located (MSSQL Server)

<?php
    $query  = "SELECT * FROM products WHERE id LIKE &#39;%$prod%&#39;";
    $result = mssql_query($query);
?>

If the attack submits a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- as the value of the variable $prod, then $query will become

<?php
    $query = "SELECT * FROM products WHERE id LIKE &#39;%a%&#39;
        exec master..xp_cmdshell &#39;net user test testpass /ADD&#39;--";
    $result = mssql_query($query);
?>

MSSQL server will execute this SQL statement, including the command after it for adding users to the system. If this program is running as sa and the MSSQLSERVER service has sufficient permissions, the attacker can obtain a system account to access the host.

Note:

Although the above example is for a specific database system, it does not mean that similar attacks cannot be carried out on other database systems. Using different methods, various databases can suffer.

Precautionary Measures

Some people may comfort themselves by saying that the attacker needs to know the information about the database structure to carry out the above attack. Yes, it is. But no one can guarantee that attackers will not get this information. Once they do, the database is in danger of being leaked. If you are using an open source software package to access the database, such as a forum program, it is easy for an attacker to obtain the relevant code. The risk is even greater if the code is poorly designed.

這些攻擊總是建立在發(fā)掘安全意識不強的代碼上的。所以,永遠不要信任外界輸入的數(shù)據(jù),特別是來自于客戶端的,包括選擇框、表單隱藏域和 cookie。就如上面的第一個例子那樣,就算是正常的查詢也有可能造成災(zāi)難。

永遠不要使用超級用戶或所有者帳號去連接數(shù)據(jù)庫。要用權(quán)限被嚴格限制的帳號。

檢查輸入的數(shù)據(jù)是否具有所期望的數(shù)據(jù)格式。PHP 有很多可以用于檢查輸入的函數(shù),從簡單的變量函數(shù)和字符類型函數(shù)(比如 is_numeric(), ctype_digit())到復(fù)雜的Perl 兼容正則表達式函數(shù)都可以完成這個工作。

如果程序等待輸入一個數(shù)字,可以考慮使用 is_numeric() 來檢查,或者直接使用 settype() 來轉(zhuǎn)換它的類型,也可以用 sprintf() 把它格式化為數(shù)字。

Example #5 一個實現(xiàn)分頁更安全的方法

<?php
    settype($offset, &#39;integer&#39;);
    $query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
    // 請注意格式字符串中的 %d,如果用 %s 就毫無意義了
    $query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
        $offset);
?>

使用數(shù)據(jù)庫特定的敏感字符轉(zhuǎn)義函數(shù)(比如?mysql_escape_string()?和?sql_escape_string())把用戶提交上來的非數(shù)字數(shù)據(jù)進行轉(zhuǎn)義。如果數(shù)據(jù)庫沒有專門的敏感字符轉(zhuǎn)義功能的話?addslashes()?和?str_replace()?可以代替完成這個工作??纯吹谝粋€例子,此例顯示僅在查詢的靜態(tài)部分加上引號是不夠的,查詢很容易被攻破。

要不擇手段避免顯示出任何有關(guān)數(shù)據(jù)庫的信心,尤其是數(shù)據(jù)庫結(jié)構(gòu)。

也可以選擇使用數(shù)據(jù)庫的存儲過程和預(yù)定義指針等特性來抽象數(shù)庫訪問,使用戶不能直接訪問數(shù)據(jù)表和視圖。但這個辦法又有別的影響。

除此之外,在允許的情況下,使用代碼或數(shù)據(jù)庫系統(tǒng)保存查詢?nèi)罩疽彩且粋€好辦法。顯然,日志并不能防止任何攻擊,但利用它可以跟蹤到哪個程序曾經(jīng)被嘗試攻擊過。日志本身沒用,要查閱其中包含的信息才行。畢竟,更多的信息總比沒有要好。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A Simple Guide to PHP Setup A Simple Guide to PHP Setup Jul 18, 2025 am 04:25 AM

The key to setting up PHP is to clarify the installation method, configure php.ini, connect to the web server and enable necessary extensions. 1. Install PHP: Use apt for Linux, Homebrew for Mac, and XAMPP recommended for Windows; 2. Configure php.ini: Adjust error reports, upload restrictions, etc. and restart the server; 3. Use web server: Apache uses mod_php, Nginx uses PHP-FPM; 4. Install commonly used extensions: such as mysqli, json, mbstring, etc. to support full functions.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

Mastering PHP Block Comments Mastering PHP Block Comments Jul 18, 2025 am 04:35 AM

PHPblockcommentsareusefulforwritingmulti-lineexplanations,temporarilydisablingcode,andgeneratingdocumentation.Theyshouldnotbenestedorleftunclosed.BlockcommentshelpindocumentingfunctionswithPHPDoc,whichtoolslikePhpStormuseforauto-completionanderrorche

Writing Effective PHP Comments Writing Effective PHP Comments Jul 18, 2025 am 04:44 AM

Comments cannot be careless because they want to explain the reasons for the existence of the code rather than the functions, such as compatibility with old interfaces or third-party restrictions, otherwise people who read the code can only rely on guessing. The areas that must be commented include complex conditional judgments, special error handling logic, and temporary bypass restrictions. A more practical way to write comments is to select single-line comments or block comments based on the scene. Use document block comments to explain parameters and return values at the beginning of functions, classes, and files, and keep comments updated. For complex logic, you can add a line to the previous one to summarize the overall intention. At the same time, do not use comments to seal code, but use version control tools.

Improving Readability with Comments Improving Readability with Comments Jul 18, 2025 am 04:46 AM

The key to writing good comments is to explain "why" rather than just "what was done" to improve the readability of the code. 1. Comments should explain logical reasons, such as considerations behind value selection or processing; 2. Use paragraph annotations for complex logic to summarize the overall idea of functions or algorithms; 3. Regularly maintain comments to ensure consistency with the code, avoid misleading, and delete outdated content if necessary; 4. Synchronously check comments when reviewing the code, and record public logic through documents to reduce the burden of code comments.

See all articles