Python——flask漏洞探究
1|1hello world
我們先從基礎的開始,在網頁上打出hello world
,python程式碼如下:
其中@app.route
就有點類似於Java的@WebServlet
了,上述程式碼中,當你在瀏覽器訪問127.0.0.1:5000/
時就能夠看到輸出了,5000是flask的預設埠
1|2模板
flask使用的渲染引擎是Jinja2
,我們可以直接return一些HTML程式碼來實現網頁的格式化,但是這樣會導致XSS漏洞,如下
methods
傳參表示/
僅接受GET,POST
型別的傳參,這裡我們接受了名為test
的GET
傳參然後替換了html
<script>alert(1)</script>
就可以看到引起了XSS注入
render_template_string
為了避免XSS,可以使用render_tempplate_string對輸入的文字進行渲染,程式碼如下
from flask import Flask,render_template,request,render_template_string app=Flask(__name__) @app.route('/',methods=['GET','POST']) def test(): html='<html>{{var}}<html>' test = request.args.get('test') return render_template_string(html,var=test){{}}
為變數包裹標示符,在render_template_string
傳參即可替換{{var}}
為GET傳參變數test
,再次進行XSS實驗,可以看到已經被轉義了
render_template
在py檔案中寫HTML有點麻煩,不直觀。在flask中就有一種叫做模板的東西,我們可以藉助render_template
從templates資料夾中載入我們想要的html檔案,然後對裡面的內容進行修改輸出。首先我在templates中放入這樣的一個index.html
:
index.py
程式碼如下:
可以理解為我使用render_template
函式引用了templates
資料夾下面的index.html
模板,然後傳入一個引數var
,用來控制模板中的{{var}},我們再到瀏覽器中看看
可以看到{{var}}已經被替換成了test
,當我們傳入XSS語句時是不會執行的,他同樣會自動渲染
1|3SSTI檔案讀取/命令執行
SSTI(Server-Side Template Injection) 服務端模板注入,就是伺服器模板中拼接了惡意使用者輸入導致各種漏洞。通過模板,Web應用可以把輸入轉換成特定的HTML檔案或者email格式
在Jinja2引擎中,{{}}
不僅僅是變數標示符,也能執行一些簡單的表示式,產生該漏洞的程式碼如下
當我們傳入?test={{7*7}},神奇的事情發生了
接下來我在演示介紹一下如何利用這個漏洞實現檔案讀寫和命令執行,其大致思路如下
找到父類<type 'object'>–>尋找子類 __subclasses__()–>找關於命令執行或者檔案操作的模組讀取檔案
- 獲取
’‘
的類物件
- 追溯繼承樹
可以看到object
已經出來了
- 繼而向下查詢
object
的子類
耐心找一下,可以找到第40個為<type> 'file'
- 執行命令
執行完這條命令就能得到passwd
檔案了
寫入檔案
寫入檔案的方法和上面類似
''.__class__.__mro__[2].__subclasses__()[40]('/tmp/1','w').write('123')執行命令
執行命令有很多種方法,這裡要找的是<class 'site._Printer'>
,找一下,在第71個,那麼我們執行命令
這樣就可以載入到os模組並執行ls命令,命令執行結果方法不唯一,payload也不一定一致,但思路大體就是這樣了