search
HomeDatabaseMysql TutorialWhat are the three ways of sql injection?

The three ways of sql injection are: 1. Numeric injection. When the input parameter is an integer, there may be a numeric injection vulnerability; 2. Character injection. When the input parameter is a string, There may be a character injection vulnerability; 3. Search injection, the search parameters are not filtered when performing data search.

What are the three ways of sql injection?

The operating environment of this tutorial: Windows 7 system, mysql version 8.0, Dell G3 computer.

SQL injection principle

SQL injection attacks refer to constructing special inputs as parameters and passing them into Web applications, and most of these inputs are some combinations in SQL syntax. By executing SQL statements Then the operation required by the attacker is performed. The main reason is that the program does not carefully filter the data input by the user, causing illegal data to invade the system.

SQL injection classification

1. Numeric injection

When the input parameter is an integer, there may be a numeric injection vulnerability.

Assume that there is a URL: HTTP://www.aaa.com/test.php?id=1

You can guess the background SQL statement as:

SELECT * FROM table WHERE id=1

SQL injection point to determine numeric vulnerabilities:

① First enter a SQL statement such as single quote '

in the input box It will become:

SELECT * FROM table WHERE id=1',

does not conform to the syntax, so the statement will definitely make an error, causing the script program to be unable to obtain data from the database, thus making the original There is an exception on the page.

② Enter and 1 = 1 in the input box

The SQL statement becomes:

SELECT * FROM table WHERE id=1 and 1 = 1

The statement is correct, the execution is normal, and the returned data is no different from the original request.

③ Enter and 1 = 2 in the database

The SQL statement becomes:

SELECT * FROM table WHERE id=1 and 1 = 2

Although the syntax is correct and the statement executes normally, the logic is wrong because 1 = 2 is permanently false, so the returned data is different from the original request.

If all the above three steps are met, the program may have a numeric SQL injection vulnerability.

2. Character injection

When the input parameter is a string, a character injection vulnerability may exist. The biggest difference between numeric and character injection is that numeric types do not need to be closed with single quotes, while character types generally need to be closed with single quotes.

The most critical thing about character injection is how to close the SQL statement and comment out the redundant code.

Assume that the background SQL statement is as follows:

SELECT * FROM table WHERE username = 'admin'

The SQL injection point to determine the character type vulnerability:

① It is better to enter the single quotation mark admin' first to test the SQL statement

. It will become:

SELECT * FROM table WHERE username = 'admin''.

Page exception.

② Input: admin' and 1 = 1 --

Note: There is a single quotation mark' after admin, which is used to close the string, and finally there is a comment character--(two There is a space after the bar!!!).
The SQL statement becomes:

SELECT * FROM table WHERE username = 'admin' and 1 = 1 --

The page is displayed correctly.

③ Input: admin' and 1 = 2 --

SQL statement becomes:

SELECT * FROM table WHERE username = 'admin' and 1 = 2 --

Page error.

If the above three steps are met, character SQL injection may exist.

3. Search injection

This is a special type of injection. This type of injection mainly refers to not filtering the search parameters when performing data searches. Generally, there is "keyword=keyword" in the link address. Some are not displayed in the link address, but are submitted directly through the search box form. The prototype of the SQL statement submitted by this type of injection point is roughly: select * from table name where field like '%keyword%' If there is injection, we can construct a SQL injection statement similar to the following for blasting: select * from table Name where field like '%test%' and '%1%'='%1%'

The following are some common injection names:

  • POST injection : Inject the field in the POST data

  • Cookie injection: Inject the field in the Cookie data

  • Delayed injection: Inject using the database delay feature

  • Search injection: The injection location is the search place

  • base64 injection: The injected string needs to be base64 encrypted

Common database injection

For database injection, attackers simply use the database to obtain more data or greater permissions. The methods of utilization can be summarized into the following categories:

  • Query data

  • Read and write files

  • Execute command

The attacker is doing these three things for program injection, regardless of any database, but the SQL statements injected into different databases are different.

Here are the injections of three databases: Oracle 11g, MySQL 5.1 and SQL Server 2008.

SQL Server

1. Use error messages to extract information

SQL Server database is a very good database, it can accurately locate error information, which is a great advantage for attackers. This is a very good thing, because the attacker can extract the data he wants through the error message.

① Enumerate the current table or column

Assume that such a table exists:

What are the three ways of sql injection?

Query the detailed information of the root user, SQL The statement guess is as follows:

SELECT * FROM user WHERE username = 'root' AND password = 'root'

The attacker can use SQL Server features to obtain sensitive information, enter the following in the input box Statement:

' having 1 = 1 --

The final executed SQL statement will become:

SELECT * FROM user WHERE username = 'root' AND password = 'root' HAVING 1 = 1 --

Then the SQL executor may throw an error:

What are the three ways of sql injection?

The attacker can discover the current table Named user, and the field id exists.

An attacker can use this feature to continue to obtain other column names by entering the following statement:

' GROUP BY users.id HAVING 1 = 1 --

Then the SQL statement becomes For:

SELECT * FROM user WHERE username = 'root' AND password = 'root' GROUP BY users.id HAVING 1 = 1 --

Throws error:

What are the three ways of sql injection?

You can see that the column name username is included. You can query recursively once until there is no error message returned, so you can use the HAVING clause to get all the column names of the current table.

Note: Each column specified by Select should appear in the Group By clause, unless an aggregate function is used for this column

②. Extract data using data type errors

The SQL Editor will throw an exception if you try to compare a string with a non-string, or convert a string to another incompatible type.

The following SQL statement:

SELECT * FROM user WHERE username = 'abc' AND password = 'abc' AND 1 > (SELECT TOP 1 username FROM users)

Executor error message:

What are the three ways of sql injection?

#You can get the user name root. Because in the subquery SELECT TOP 1 username FROM users, the first queried username is returned. The return type is varchar type, and then compared with 1 of int type. The two different types of data cannot be compared and an error is reported. This resulted in a data breach.

Use this method to recursively deduce all account information:

SELECT * FROM users WHERE username = 'abc' AND password = 'abc' AND 1 > (SELECT TOP 1 username FROM users WHERE not in ('root')).

By constructing this statement, you can get the next user name; if you replace the username in the subquery with other column names, you can get the information of other columns, which will not be described here.

2. Obtain metadata

SQL Server provides a large number of views to facilitate obtaining metadata. You can first guess the number of columns in the table, and then use UNION to construct a SQL statement to obtain the data.

For example:

SELECT *** FROM *** WHERE id = *** UNION SELECT 1, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

If the number of columns in the current table is 2, you can use the UNION statement to obtain the current database table. How to guess the number of columns in the current table will be described later.

Some commonly used system database views:

Database view Description
SYS.DATABASES All databases in SQL Server
SYS.SQL_LOGINS All logins in SQL Server
INFORMATION_SCHEMA.TABLES All data tables in the current user database
INFORMATION_SCHEMA.COLUMNS Current user All columns in the database
SYS.ALL_COLUMNS Union of all columns of user-defined objects and system objects
SYS .DATABASE_PRINCIPALS Exception permissions for each permission or column in the database
SYS.DATABASE_FILES Database files stored in the database
SYSOBJECTS Every object created in the database (including constraints, logs, and stored procedures)
3. ORDER BY clause guesses the number of columns

You can use the ORDER BY statement to determine the number of columns in the current table.

For example:

① SELECT * FROM users WHERE id = 1——SQL execution is normal

②SELECT * FROM users WHERE id = 1 ORDER BY 1 (according to the first column Sorting) - SQL execution is normal

③ SELECT * FROM users WHERE id = 1 ORDER BY 2 (sorted according to the second column) - SQL execution is normal

④ SELECT * FROM users WHERE id = 1 ORDER BY 3 (sorted by the third column) - SQL executes normally

⑤ SELECT * FROM users WHERE id = 1 ORDER BY 4 (sorted by the fourth column) - SQL throws an exception:

What are the three ways of sql injection?

It can be concluded that the number of columns in the current table is only 3, because an error is reported when sorting according to the 4th column. This method also works in Oracle and MySql databases.

After knowing the number of columns, the attacker usually cooperates with the UNION keyword to carry out the next attack.

4. UNION query

The UNION keyword combines two or more query results into a single result set. Most databases support UNION queries. However, there are the following basic rules for merging two results using UNION:

  • The number of columns in all queries must be the same

  • The data types must be compatible

① Use UNION query to guess the number of columns

Not only can you use the ORDER BY method to guess the number of columns, the UNION method can also be used.

There are 5 columns in the previously assumed user table. If we use UNION to query:

SELECT * FROM users WHERE id = 1 UNION SELECT 1

The database will issue Exception:

What are the three ways of sql injection?

You can query recursively until no errors occur, then you can know the number of query fields in the User table:

UNION SELECT 1,2, UNION SELECT 1,2,3

You can also change the number after SELECT to null, so that incompatible exceptions are less likely to occur.

② Union query for sensitive information

After knowing that the number of columns is 4, you can use the following statement to continue injecting:

UNION SELECT 'x', null, null, null FROM SYSOBJECT WHERE xtype='U' (Note: xtype='U' means the object type is a table)

If the data type of the first column does not match, the database will report an error, then you can query recursively until the statements are compatible . When the statement is executed normally, you can replace x with a SQL statement to query sensitive information.

5. Use the system functions provided by SQL Server

SQL Server provides a lot of system functions. You can use these system functions to access the information in the SQL Server system tables without using SQL queries. statement.

For example:

  • SELECT suser_name(): Returns the user’s login identification name

  • SELECT user_name(): Based on the specified The identification number returns the database user name

  • SELECT db_name(): returns the database name

  • SELECT is_member('db_owner'): whether it is a database Role

  • SELECT convert(int, '5'): Data type conversion

6. Stored procedure

Stored procedure (Stored Procedure) is a set of SQL "functions" used to complete specific functions in large database systems, such as executing system commands, viewing the registry, reading disk directories, etc.

The stored procedure most commonly used by attackers is "xp_cmdshell". This stored procedure allows users to execute operating system commands.

For example: If there is an injection point in http://www.aaa.org/test.aspx?id=1, then the attacker can implement a command attack:
http://www.aaa. org/test.aspx?id=1; exec xp_cmdshell 'net user test test /add'

The final executed SQL statement is as follows:

SELECT * FROM table WHERE id=1; exec xp_cmdshell 'net user test test /add'

The statement after the semicolon can create a new user with the username test and password test for the attacker on the other party's server.

Note: Not any database user can use this type of stored procedure, the user must hold CONTROL SERVER permissions.

Common dangerous stored procedures are as follows:

Stored procedures Description
sp_addlogin Creates a new SQL Server login that allows users to connect to a SQL Server instance using the SQL Server identity
sp_dropuser Delete the database user from the current database
xp_enumgroups Provide a Microsoft Windows local group list or define a global group list in the specified Windows domain
xp_regread Read the registry
xp_regwrite Write the registry
xp_redeletevalue Delete registry
xp_dirtree Read directory
sp_password Change password
xp_servicecontrol Stop or activate a service

In addition, any database requires specific permissions when using some special functions or stored procedures. Common SQL Server database roles and permissions are as follows:

Role Permission
bulkadmin Can run BULK INSERT statement
dbcreator Can create, change, delete and restore any database
diskadmin Can manage disk files
processadmin Can plant instances running in the database engine
securityadmin Can manage login names and their attributes; can take advantage of GRANT, DENY, and REVOKE server-level permissions; can also take advantage of GRANT, DENY, and REVOKE database-level permissions; in addition, you can re- Set the password for the SQL Server login
serveradmin You can change server-wide configuration options and shut down the server
setupadmin Can add and delete linked servers, and can execute certain system stored procedures
sysadmin Can perform any activity in the database engine
7. Dynamic execution

SQL Server supports dynamic execution of statements, and users can submit a string to execute SQL statements.

For example: exec('SELECT username, password FROM users')

You can also define a hexadecimal SQL statement and use the exec function to execute it. Most web applications and firewalls filter single quotes. Using exec to execute hexadecimal SQL statements can break through many firewalls and anti-injection programs, such as:

declare @query varchar(888)
select @query=0x73656C6563742031
exec(@query)

or:

declare/ **/@query/**/varchar(888)/**/select/**/@query=0x73656C6563742031/**/exec(@query)

Related recommendations: "mysql tutorial

The above is the detailed content of What are the three ways of sql injection?. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
MySQL's Place: Databases and ProgrammingMySQL's Place: Databases and ProgrammingApr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL: From Small Businesses to Large EnterprisesMySQL: From Small Businesses to Large EnterprisesApr 13, 2025 am 12:17 AM

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?Apr 13, 2025 am 12:16 AM

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.

MySQL: Not a Programming Language, But...MySQL: Not a Programming Language, But...Apr 13, 2025 am 12:03 AM

MySQL is not a programming language, but its query language SQL has the characteristics of a programming language: 1. SQL supports conditional judgment, loops and variable operations; 2. Through stored procedures, triggers and functions, users can perform complex logical operations in the database.

MySQL: An Introduction to the World's Most Popular DatabaseMySQL: An Introduction to the World's Most Popular DatabaseApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

The Importance of MySQL: Data Storage and ManagementThe Importance of MySQL: Data Storage and ManagementApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system suitable for data storage, management, query and security. 1. It supports a variety of operating systems and is widely used in Web applications and other fields. 2. Through the client-server architecture and different storage engines, MySQL processes data efficiently. 3. Basic usage includes creating databases and tables, inserting, querying and updating data. 4. Advanced usage involves complex queries and stored procedures. 5. Common errors can be debugged through the EXPLAIN statement. 6. Performance optimization includes the rational use of indexes and optimized query statements.

Why Use MySQL? Benefits and AdvantagesWhy Use MySQL? Benefits and AdvantagesApr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Apr 12, 2025 am 12:16 AM

InnoDB's lock mechanisms include shared locks, exclusive locks, intention locks, record locks, gap locks and next key locks. 1. Shared lock allows transactions to read data without preventing other transactions from reading. 2. Exclusive lock prevents other transactions from reading and modifying data. 3. Intention lock optimizes lock efficiency. 4. Record lock lock index record. 5. Gap lock locks index recording gap. 6. The next key lock is a combination of record lock and gap lock to ensure data consistency.

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.