许 志强

许 志强

1656071340

什么是 SQL 注入,为什么它很危险?

处理 Web 应用程序的开发人员看到了许多威胁到他们构建的东西的东西。其中一些包括针对人的攻击(例如,社会工程),其中一些攻击(DoS 或 DDoS 攻击、跨站点脚本、跨站点请求伪造、身份验证损坏、敏感数据暴露、访问控制损坏、不安全反序列化等)针对 Web 应用程序的部分。但是,一些攻击主要针对您的数据库和存储在其中的数据——其中一种攻击是 SQL 注入(简称 SQLi)。在这篇博文中,我们将研究这种攻击可能产生的影响。

什么是 SQL 注入,为什么它很危险?

SQL 注入是一种经常针对 Web 应用程序的攻击。这种攻击的目的经常是从数据库中窃取敏感数据并将其用于攻击者的个人利益。这种攻击如此普遍和危险,正是因为许多开发人员在创建面向 Web 的公共解决方案时忽略了安全性的重要性。当安全漏洞被忽视时,恶意方通常会发现并利用它们。这些邪恶的行为者利用这些漏洞,因为他们可以通过出售在违规期间被盗的数据获利。

这种攻击的影响取决于您的 Web 应用程序。假设您的应用程序不存储敏感信息,在这种情况下,攻击可能不会产生任何深远的后果。但是,如果不是这种情况,您的手上可能会遇到严重问题——敏感数据可能会被盗并出售以获取利润,由于重设密码和在其他地方更改信息的压力,会给您的业务和客户带来不必要的问题。

SQL 注入是如何工作的?

SQL 注入的概念非常简单:这种攻击之所以有效,是因为一些开发人员将用户在给定输入字段中写入的所有内容放入查询中并将其传递给数据库。易受攻击的基本代码片段如下所示(您也可以使用 $_GET 代替 $_POST,前提是相同的):

$Input = $_POST['input'];

SELECT * FROM demo_table WHERE column [= | < | > | <= | >= | LIKE ...] '$Input';

如您所见,在某些情况下,易受攻击的代码非常简单(它也可能变得复杂,我们稍后会进入不同的场景)——然后攻击者经常使用引号字符 (') 来利用这些易受攻击的代码诱发错误。一旦它引发错误,攻击者就知道代码易受攻击,他们可以攻击我们的应用程序。

SQL 注入的类型

SQL 注入攻击分为几类:

  • 经典 SQL 注入——一种基本的 SQL 注入类型,当攻击者旨在在数据库中执行 SQL 代码以访问应用程序或任何其他已在其数据库架构中实现 MySQL 的系统时。
  • 基于联合的 SQL 注入——一种 SQL 注入类型,攻击者使用 MySQL 中的 UNION 子句组合查询结果,返回对攻击者有用的响应。
  • 基于错误的 SQL 注入——一种 SQL 注入,攻击者主要通过在被攻击的应用程序上显示(或不存在)错误消息来收集数据。基于错误的 SQL 注入本身有几种类型。
  • 带外 (OOB) SQL 注入- 一种 SQL 注入,攻击者无法使用相同的应用程序进行攻击和结果收集。一种鲜为人知的 SQL 注入类型,但仍然是一种类型。

攻击者使用上面列出的每种类型来实现不同的目标——如果攻击者对系统的内部工作有一些隐含的了解,经典的 SQL 注入很有用,如果攻击者结合了几个结果,则基于联合的 SQL 注入可能很有用将SELECT语句放入单个结果集中,当应用程序“静默”时使用基于错误的 SQL 注入(这意味着它不返回任何响应,因此攻击者在发出某些类型的查询时会寻找功能更改)

保护您的应用程序免受 SQL 注入

至此,您应该对什么是 SQL 注入以及它的类型有一个很好的了解,但是如何保护您的应用程序免受此类攻击呢?值得庆幸的是,有几种众所周知的方法可以降低现在或将来利用此类漏洞的风险:

  • 使所有应用程序组件保持最新并安装所有必要的安全补丁——使应用程序组件保持最新应该是抵御任何攻击的有效第一道防线。
  • 验证输入——由于此类攻击的成功很大程度上取决于攻击者向系统提供的输入,因此输入验证可能是现在和将来防止 SQL 注入攻击的另一种成功方法。
  • 使用参数化语句——使用参数化语句可能是防御 SQL 注入攻击的最有效方法。当使用参数化语句时,服务器总是将用户输入解释为一个值而不解析它。例如:
/* Prepare MySQL statement */if (!($statement = $mysqli->prepare(	"SELECT customerID     FROM orders     WHERE item = ?"    ))) {    	echo "Failed: (" . $mysqli->errno . ") " . $mysqli->error;}/* Bind variables to statement as parameters using bind_param().The type (first) parameter can take integers (i), doubles (d), strings(s), and blobs (b).*/$purchasedItem = 'ice cream';if (!$statement->bind_param("s", $purchasedItem)) {        echo "Failed: (" . $statement->errno . ") " . $statement->error;}/* Execute prepared MySQL statement */if (!$statement->execute()) {    echo "Failed: (" . $statement->errno . ") " . $statement->error;}

 

  • 使用 Web 应用程序防火墙——使用 Web 应用程序防火墙 (WAF) 是另一个有效的防线,因为 Web 应用程序防火墙通常能够识别和阻止多种类型的攻击,包括 SQL 注入、跨站点脚本、跨站点请求伪造、损坏的访问控制、敏感数据暴露、DoS 或 DDoS 攻击等。理想情况下,Web 应用程序防火墙应与参数化语句一起使用,以最大限度地提高效率并防御 SQL 注入和其他类型的攻击。
  • 使用 MySQL 或其他供应商提供的以安全为中心的应用程序——MySQL 提供了一种方法来保护您的应用程序免受企业级别的 SQL 注入,方法是使用 MySQL Enterprise Firewall 工具,该工具可以针对特定于数据库的威胁提供实时保护。此外,还有几个其他供应商值得进一步讨论(除了 MySQL,其中一些包括 MariaDB、MinervaDB、MongoDB、Oracle、Shounnines 等)。不过,对于这篇博文,我们不会过多介绍。
  • 在可能没有必要时避免授予管理权限——避免授予不必要的权限可以成为抵御多种攻击的有效堡垒,包括权限提升,当然还有 SQL 注入。例如,如果使用您的应用程序的用户只需要某些访问权限,请考虑仅授予完成任务所需的权限。在数据库级别强制执行最低权限规则也是一个好主意。

牢记这些要点应该有助于让您的应用程序顺利运行。

保护您的数据库免受 SQL 注入

使用准备好的语句,使用 MySQL 提供的以安全为中心的插件,避免授予不必要的管理权限,并考虑其他上述预防措施,应该让您和您的数据库走上一条良好的道路。但是,如果您想更深入地研究 MySQL 并了解 SQL 查询的工作方式以及为什么使用例如 Web 应用程序防火墙 (WAF) 可以保护您免受包括 SQL 注入在内的多种攻击,请考虑以下几点:

  • 将每个查询视为由较小任务组成的大任务。
  • 可以通过运行观察查询的任务SHOW PROFILE FOR QUERY [query id here];

如果使用得当,在大多数情况下,输出将为您提供查询所做的事情和任务的持续时间。您还将能够观察到许多有趣的事情,包括获得以下问题的答案:

  • 查询开始需要多长时间?
  • 查询检查权限需要多长时间?
  • MySQL开表需要多少时间?
  • MySQL初始化进程需要多少时间?
  • MySQL 优化、准备和(或)执行查询需要多少时间?
  • MySQL 花了多长时间将数据发回给您以供查看?
  • MySQL 结束查询、关闭表、释放项目需要多少时间?

这些问题的一些答案可能会帮助您理解为什么 SQL 注入会以这种方式工作。例如,SHOW PROFILE FOR QUERY再次发出查询,您将看到以下内容:

查询输出的一部分SHOW PROFILE FOR QUERY

标记的行表示在开始运行查询后,MySQL 会立即检查权限。还记得我们之前讨论过的吗?正是出于这个原因,您应该避免授予不必要的权限——如果攻击者所针对的 MySQL 帐户没有足够的权限,则查询将失败。由于SHOW PROFILE FOR QUERY查询的功能不在本博文的范围内,因此我们不会在此详细介绍,但您可以了解遵循上述建议的方式和原因很重要。

上面列出的大多数建议也适用于数据库空间:

  • 使您的所有应用程序组件保持最新包括 phpMyAdmin。
  • 验证输入包括验证所有输入,而不仅仅是验证作为某事物一部分的输入。
  • 参数化语句可以(并且应该)用于所有使用 SQL 查询来避免从某些表中泄露数据的场合。
  • 使用 Web 应用程序防火墙并使用以安全为中心的插件可能会阻止攻击者访问您的数据库。
  • 避免授予太多权限也可能使您的数据库免于灾难(请参阅上面的示例)

考虑到上面的建议,您应该可以很好地缓解现在或将来可能会影响您的数据库的 SQL 注入问题。

概括

正如您可能会说的,大多数帮助您保护应用程序和数据库免受 SQL 注入攻击的建议都非常笼统和直接。但是,保护您的数据库免受 SQL 注入也不是火箭科学——请牢记上面概述的指导方针,您应该一切顺利! 

来源:https ://arctype.com/blog/sql-injection/

#sql 

What is GEEK

Buddha Community

什么是 SQL 注入,为什么它很危险?
Cayla  Erdman

Cayla Erdman

1594369800

Introduction to Structured Query Language SQL pdf

SQL stands for Structured Query Language. SQL is a scripting language expected to store, control, and inquiry information put away in social databases. The main manifestation of SQL showed up in 1974, when a gathering in IBM built up the principal model of a social database. The primary business social database was discharged by Relational Software later turning out to be Oracle.

Models for SQL exist. In any case, the SQL that can be utilized on every last one of the major RDBMS today is in various flavors. This is because of two reasons:

1. The SQL order standard is genuinely intricate, and it isn’t handy to actualize the whole standard.

2. Every database seller needs an approach to separate its item from others.

Right now, contrasts are noted where fitting.

#programming books #beginning sql pdf #commands sql #download free sql full book pdf #introduction to sql pdf #introduction to sql ppt #introduction to sql #practical sql pdf #sql commands pdf with examples free download #sql commands #sql free bool download #sql guide #sql language #sql pdf #sql ppt #sql programming language #sql tutorial for beginners #sql tutorial pdf #sql #structured query language pdf #structured query language ppt #structured query language

Cayla  Erdman

Cayla Erdman

1596441660

Welcome Back the T-SQL Debugger with SQL Complete – SQL Debugger

When you develop large chunks of T-SQL code with the help of the SQL Server Management Studio tool, it is essential to test the “Live” behavior of your code by making sure that each small piece of code works fine and being able to allocate any error message that may cause a failure within that code.

The easiest way to perform that would be to use the T-SQL debugger feature, which used to be built-in over the SQL Server Management Studio tool. But since the T-SQL debugger feature was removed completely from SQL Server Management Studio 18 and later editions, we need a replacement for that feature. This is because we cannot keep using the old versions of SSMS just to support the T-SQL Debugger feature without “enjoying” the new features and bug fixes that are released in the new SSMS versions.

If you plan to wait for SSMS to bring back the T-SQL Debugger feature, vote in the Put Debugger back into SSMS 18 to ask Microsoft to reintroduce it.

As for me, I searched for an alternative tool for a T-SQL Debugger SSMS built-in feature and found that Devart company rolled out a new T-SQL Debugger feature to version 6.4 of SQL – Complete tool. SQL Complete is an add-in for Visual Studio and SSMS that offers scripts autocompletion capabilities, which help develop and debug your SQL database project.

The SQL Debugger feature of SQL Complete allows you to check the execution of your scripts, procedures, functions, and triggers step by step by adding breakpoints to the lines where you plan to start, suspend, evaluate, step through, and then to continue the execution of your script.

You can download SQL Complete from the dbForge Download page and install it on your machine using a straight-forward installation wizard. The wizard will ask you to specify the installation path for the SQL Complete tool and the versions of SSMS and Visual Studio that you plan to install the SQL Complete on, as an add-in, from the versions that are installed on your machine, as shown below:

Once SQL Complete is fully installed on your machine, the dbForge SQL Complete installation wizard will notify you of whether the installation was completed successfully or the wizard faced any specific issue that you can troubleshoot and fix easily. If there are no issues, the wizard will provide you with an option to open the SSMS tool and start using the SQL Complete tool, as displayed below:

When you open SSMS, you will see a new “Debug” tools menu, under which you can navigate the SQL Debugger feature options. Besides, you will see a list of icons that will be used to control the debug mode of the T-SQL query at the leftmost side of the SSMS tool. If you cannot see the list, you can go to View -> Toolbars -> Debugger to make these icons visible.

During the debugging session, the SQL Debugger icons will be as follows:

The functionality of these icons within the SQL Debugger can be summarized as:

  • Adding Breakpoints to control the execution pause of the T-SQL script at a specific statement allows you to check the debugging information of the T-SQL statements such as the values for the parameters and the variables.
  • Step Into is “navigate” through the script statements one by one, allowing you to check how each statement behaves.
  • Step Over is “execute” a specific stored procedure if you are sure that it contains no error.
  • Step Out is “return” from the stored procedure, function, or trigger to the main debugging window.
  • Continue executing the script until reaching the next breakpoint.
  • Stop Debugging is “terminate” the debugging session.
  • Restart “stop and start” the current debugging session.

#sql server #sql #sql debugger #sql server #sql server stored procedure #ssms #t-sql queries

Cayla  Erdman

Cayla Erdman

1596448980

The Easy Guide on How to Use Subqueries in SQL Server

Let’s say the chief credit and collections officer asks you to list down the names of people, their unpaid balances per month, and the current running balance and wants you to import this data array into Excel. The purpose is to analyze the data and come up with an offer making payments lighter to mitigate the effects of the COVID19 pandemic.

Do you opt to use a query and a nested subquery or a join? What decision will you make?

SQL Subqueries – What Are They?

Before we do a deep dive into syntax, performance impact, and caveats, why not define a subquery first?

In the simplest terms, a subquery is a query within a query. While a query that embodies a subquery is the outer query, we refer to a subquery as the inner query or inner select. And parentheses enclose a subquery similar to the structure below:

SELECT 
 col1
,col2
,(subquery) as col3
FROM table1
[JOIN table2 ON table1.col1 = table2.col2]
WHERE col1 <operator> (subquery)

We are going to look upon the following points in this post:

  • SQL subquery syntax depending on different subquery types and operators.
  • When and in what sort of statements one can use a subquery.
  • Performance implications vs. JOINs.
  • Common caveats when using SQL subqueries.

As is customary, we provide examples and illustrations to enhance understanding. But bear in mind that the main focus of this post is on subqueries in SQL Server.

Now, let’s get started.

Make SQL Subqueries That Are Self-Contained or Correlated

For one thing, subqueries are categorized based on their dependency on the outer query.

Let me describe what a self-contained subquery is.

Self-contained subqueries (or sometimes referred to as non-correlated or simple subqueries) are independent of the tables in the outer query. Let me illustrate this:

-- Get sales orders of customers from Southwest United States 
-- (TerritoryID = 4)

USE [AdventureWorks]
GO
SELECT CustomerID, SalesOrderID
FROM Sales.SalesOrderHeader
WHERE CustomerID IN (SELECT [CustomerID]
                     FROM [AdventureWorks].[Sales].[Customer]
                     WHERE TerritoryID = 4)

As demonstrated in the above code, the subquery (enclosed in parentheses below) has no references to any column in the outer query. Additionally, you can highlight the subquery in SQL Server Management Studio and execute it without getting any runtime errors.

Which, in turn, leads to easier debugging of self-contained subqueries.

The next thing to consider is correlated subqueries. Compared to its self-contained counterpart, this one has at least one column being referenced from the outer query. To clarify, I will provide an example:

USE [AdventureWorks]
GO
SELECT DISTINCT a.LastName, a.FirstName, b.BusinessEntityID
FROM Person.Person AS p
JOIN HumanResources.Employee AS e ON p.BusinessEntityID = e.BusinessEntityID
WHERE 1262000.00 IN
    (SELECT [SalesQuota]
    FROM Sales.SalesPersonQuotaHistory spq
    WHERE p.BusinessEntityID = spq.BusinessEntityID)

Were you attentive enough to notice the reference to BusinessEntityID from the Person table? Well done!

Once a column from the outer query is referenced in the subquery, it becomes a correlated subquery. One more point to consider: if you highlight a subquery and execute it, an error will occur.

And yes, you are absolutely right: this makes correlated subqueries pretty harder to debug.

To make debugging possible, follow these steps:

  • isolate the subquery.
  • replace the reference to the outer query with a constant value.

Isolating the subquery for debugging will make it look like this:

SELECT [SalesQuota]
    FROM Sales.SalesPersonQuotaHistory spq
    WHERE spq.BusinessEntityID = <constant value>

Now, let’s dig a little deeper into the output of subqueries.

Make SQL Subqueries With 3 Possible Returned Values

Well, first, let’s think of what returned values can we expect from SQL subqueries.

In fact, there are 3 possible outcomes:

  • A single value
  • Multiple values
  • Whole tables

Single Value

Let’s start with single-valued output. This type of subquery can appear anywhere in the outer query where an expression is expected, like the WHERE clause.

-- Output a single value which is the maximum or last TransactionID
USE [AdventureWorks]
GO
SELECT TransactionID, ProductID, TransactionDate, Quantity
FROM Production.TransactionHistory
WHERE TransactionID = (SELECT MAX(t.TransactionID) 
                       FROM Production.TransactionHistory t)

When you use a MAX() function, you retrieve a single value. That’s exactly what happened to our subquery above. Using the equal (=) operator tells SQL Server that you expect a single value. Another thing: if the subquery returns multiple values using the equals (=) operator, you get an error, similar to the one below:

Msg 512, Level 16, State 1, Line 20
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Multiple Values

Next, we examine the multi-valued output. This kind of subquery returns a list of values with a single column. Additionally, operators like IN and NOT IN will expect one or more values.

-- Output multiple values which is a list of customers with lastnames that --- start with 'I'

USE [AdventureWorks]
GO
SELECT [SalesOrderID], [OrderDate], [ShipDate], [CustomerID]
FROM Sales.SalesOrderHeader
WHERE [CustomerID] IN (SELECT c.[CustomerID] FROM Sales.Customer c
INNER JOIN Person.Person p ON c.PersonID = p.BusinessEntityID
WHERE p.lastname LIKE N'I%' AND p.PersonType='SC')

Whole Table Values

And last but not least, why not delve into whole table outputs.

-- Output a table of values based on sales orders
USE [AdventureWorks]
GO
SELECT [ShipYear],
COUNT(DISTINCT [CustomerID]) AS CustomerCount
FROM (SELECT YEAR([ShipDate]) AS [ShipYear], [CustomerID] 
      FROM Sales.SalesOrderHeader) AS Shipments
GROUP BY [ShipYear]
ORDER BY [ShipYear]

Have you noticed the FROM clause?

Instead of using a table, it used a subquery. This is called a derived table or a table subquery.

And now, let me present you some ground rules when using this sort of query:

  • All columns in the subquery should have unique names. Much like a physical table, a derived table should have unique column names.
  • ORDER BY is not allowed unless TOP is also specified. That’s because the derived table represents a relational table where rows have no defined order.

In this case, a derived table has the benefits of a physical table. That’s why in our example, we can use COUNT() in one of the columns of the derived table.

That’s about all regarding subquery outputs. But before we get any further, you may have noticed that the logic behind the example for multiple values and others as well can also be done using a JOIN.

-- Output multiple values which is a list of customers with lastnames that start with 'I'
USE [AdventureWorks]
GO
SELECT o.[SalesOrderID], o.[OrderDate], o.[ShipDate], o.[CustomerID]
FROM Sales.SalesOrderHeader o
INNER JOIN Sales.Customer c on o.CustomerID = c.CustomerID
INNER JOIN Person.Person p ON c.PersonID = p.BusinessEntityID
WHERE p.LastName LIKE N'I%' AND p.PersonType = 'SC'

In fact, the output will be the same. But which one performs better?

Before we get into that, let me tell you that I have dedicated a section to this hot topic. We’ll examine it with complete execution plans and have a look at illustrations.

So, bear with me for a moment. Let’s discuss another way to place your subqueries.

#sql server #sql query #sql server #sql subqueries #t-sql statements #sql

Ruth  Nabimanya

Ruth Nabimanya

1621850444

List of Available Database for Current User In SQL Server

Introduction

When working in the SQL Server, we may have to check some other databases other than the current one which we are working. In that scenario we may not be sure that does we have access to those Databases?. In this article we discuss the list of databases that are available for the current logged user in SQL Server

Get the list of database
Conclusion

#sql server #available databases for current user #check database has access #list of available database #sql #sql query #sql server database #sql tips #sql tips and tricks #tips

Introduction to Recursive CTE

This article will introduce the concept of SQL recursive. Recursive CTE is a really cool. We will see that it can often simplify our code, and avoid a cascade of SQL queries!

Why use a recursive CTE ?

The recursive queries are used to query hierarchical data. It avoids a cascade of SQL queries, you can only do one query to retrieve the hierarchical data.

What is recursive CTE ?

First, what is a CTE? A CTE (Common Table Expression) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. For example, you can use CTE when, in a query, you will use the same subquery more than once.

A recursive CTE is one having a subquery that refers to its own name!

Recursive CTE is defined in the SQL standard.

How to make a recursive CTE?

A recursive CTE has this structure:

  • The WITH clause must begin with “WITH RECURSIVE”
  • The recursive CTE subquery has two parts, separated by “UNION [ALL]” or “UNION DISTINCT”:
  • The first part produces the initial row(s) for the CTE. This SELECT does not refer to the CTE name.
  • The second part recurses by referring to the CTE name in its FROM clause.

Practice / Example

In this example, we use hierarchical data. Each row can have zero or one parent. And it parent can also have a parent etc.

Create table test (id integer, parent_id integer);

insert into test (id, parent_id) values (1, null);

insert into test (id, parent_id) values (11, 1);
insert into test (id, parent_id) values (111, 11);

insert into test (id, parent_id) values (112, 11);

insert into test (id, parent_id) values (12, 1);

insert into test (id, parent_id) values (121, 12);

For example, the row with id 111 has as ancestors: 11 and 1.

Before knowing the recursive CTE, I was doing several queries to get all the ancestors of a row.

For example, to retrieve all the ancestors of the row with id 111.

While (has parent)

	Select id, parent_id from test where id = X

With recursive CTE, we can retrieve all ancestors of a row with only one SQL query :)

WITH RECURSIVE cte_test AS (
	SELECT id, parent_id FROM test WHERE id = 111
	UNION 
	SELECT test.id, test.parent_id FROM test JOIN cte_test ON cte_test.id = test.parent_id

) SELECT * FROM cte_test

Explanations:

  • “WITH RECURSIVE”:

It indicates we will make recursive

  • “SELECT id, parent_id FROM test WHERE id = 111”:

It is the initial query.

  • “UNION … JOIN cte_test” :

It is the recursive expression! We make a jointure with the current CTE!

Replay this example here

#sql #database #sql-server #sql-injection #writing-sql-queries #sql-beginner-tips #better-sql-querying-tips #sql-top-story